ASTContext.cpp revision 54e14c4db764c0636160d26c5bbf491637c83a76
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "RecordLayoutBuilder.h"
29
30using namespace clang;
31
32enum FloatingRank {
33  FloatRank, DoubleRank, LongDoubleRank
34};
35
36ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
37                       TargetInfo &t,
38                       IdentifierTable &idents, SelectorTable &sels,
39                       Builtin::Context &builtins,
40                       bool FreeMem, unsigned size_reserve) :
41  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
42  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
43  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
44  SourceMgr(SM), LangOpts(LOpts),
45  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
46  Idents(idents), Selectors(sels),
47  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
48  ObjCIdRedefinitionType = QualType();
49  ObjCClassRedefinitionType = QualType();
50  if (size_reserve > 0) Types.reserve(size_reserve);
51  TUDecl = TranslationUnitDecl::Create(*this);
52  InitBuiltinTypes();
53}
54
55ASTContext::~ASTContext() {
56  // Deallocate all the types.
57  while (!Types.empty()) {
58    Types.back()->Destroy(*this);
59    Types.pop_back();
60  }
61
62  {
63    llvm::FoldingSet<ExtQuals>::iterator
64      I = ExtQualNodes.begin(), E = ExtQualNodes.end();
65    while (I != E)
66      Deallocate(&*I++);
67  }
68
69  {
70    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
71      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
72    while (I != E) {
73      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
74      delete R;
75    }
76  }
77
78  {
79    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
80      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
81    while (I != E) {
82      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
83      delete R;
84    }
85  }
86
87  // Destroy nested-name-specifiers.
88  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
89         NNS = NestedNameSpecifiers.begin(),
90         NNSEnd = NestedNameSpecifiers.end();
91       NNS != NNSEnd;
92       /* Increment in loop */)
93    (*NNS++).Destroy(*this);
94
95  if (GlobalNestedNameSpecifier)
96    GlobalNestedNameSpecifier->Destroy(*this);
97
98  TUDecl->Destroy(*this);
99}
100
101void
102ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
103  ExternalSource.reset(Source.take());
104}
105
106void ASTContext::PrintStats() const {
107  fprintf(stderr, "*** AST Context Stats:\n");
108  fprintf(stderr, "  %d types total.\n", (int)Types.size());
109
110  unsigned counts[] = {
111#define TYPE(Name, Parent) 0,
112#define ABSTRACT_TYPE(Name, Parent)
113#include "clang/AST/TypeNodes.def"
114    0 // Extra
115  };
116
117  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
118    Type *T = Types[i];
119    counts[(unsigned)T->getTypeClass()]++;
120  }
121
122  unsigned Idx = 0;
123  unsigned TotalBytes = 0;
124#define TYPE(Name, Parent)                                              \
125  if (counts[Idx])                                                      \
126    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
127  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
128  ++Idx;
129#define ABSTRACT_TYPE(Name, Parent)
130#include "clang/AST/TypeNodes.def"
131
132  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
133
134  if (ExternalSource.get()) {
135    fprintf(stderr, "\n");
136    ExternalSource->PrintStats();
137  }
138}
139
140
141void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
142  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
143  R = QualType(Ty, 0);
144  Types.push_back(Ty);
145}
146
147void ASTContext::InitBuiltinTypes() {
148  assert(VoidTy.isNull() && "Context reinitialized?");
149
150  // C99 6.2.5p19.
151  InitBuiltinType(VoidTy,              BuiltinType::Void);
152
153  // C99 6.2.5p2.
154  InitBuiltinType(BoolTy,              BuiltinType::Bool);
155  // C99 6.2.5p3.
156  if (LangOpts.CharIsSigned)
157    InitBuiltinType(CharTy,            BuiltinType::Char_S);
158  else
159    InitBuiltinType(CharTy,            BuiltinType::Char_U);
160  // C99 6.2.5p4.
161  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
162  InitBuiltinType(ShortTy,             BuiltinType::Short);
163  InitBuiltinType(IntTy,               BuiltinType::Int);
164  InitBuiltinType(LongTy,              BuiltinType::Long);
165  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
166
167  // C99 6.2.5p6.
168  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
169  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
170  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
171  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
172  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
173
174  // C99 6.2.5p10.
175  InitBuiltinType(FloatTy,             BuiltinType::Float);
176  InitBuiltinType(DoubleTy,            BuiltinType::Double);
177  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
178
179  // GNU extension, 128-bit integers.
180  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
181  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
182
183  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
184    InitBuiltinType(WCharTy,           BuiltinType::WChar);
185  else // C99
186    WCharTy = getFromTargetType(Target.getWCharType());
187
188  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
189    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
190  else // C99
191    Char16Ty = getFromTargetType(Target.getChar16Type());
192
193  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
194    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
195  else // C99
196    Char32Ty = getFromTargetType(Target.getChar32Type());
197
198  // Placeholder type for functions.
199  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
200
201  // Placeholder type for type-dependent expressions whose type is
202  // completely unknown. No code should ever check a type against
203  // DependentTy and users should never see it; however, it is here to
204  // help diagnose failures to properly check for type-dependent
205  // expressions.
206  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
207
208  // Placeholder type for C++0x auto declarations whose real type has
209  // not yet been deduced.
210  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
211
212  // C99 6.2.5p11.
213  FloatComplexTy      = getComplexType(FloatTy);
214  DoubleComplexTy     = getComplexType(DoubleTy);
215  LongDoubleComplexTy = getComplexType(LongDoubleTy);
216
217  BuiltinVaListType = QualType();
218
219  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
220  ObjCIdTypedefType = QualType();
221  ObjCClassTypedefType = QualType();
222
223  // Builtin types for 'id' and 'Class'.
224  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
225  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
226
227  ObjCConstantStringType = QualType();
228
229  // void * type
230  VoidPtrTy = getPointerType(VoidTy);
231
232  // nullptr type (C++0x 2.14.7)
233  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
234}
235
236MemberSpecializationInfo *
237ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
238  assert(Var->isStaticDataMember() && "Not a static data member");
239  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
240    = InstantiatedFromStaticDataMember.find(Var);
241  if (Pos == InstantiatedFromStaticDataMember.end())
242    return 0;
243
244  return Pos->second;
245}
246
247void
248ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
249                                                TemplateSpecializationKind TSK) {
250  assert(Inst->isStaticDataMember() && "Not a static data member");
251  assert(Tmpl->isStaticDataMember() && "Not a static data member");
252  assert(!InstantiatedFromStaticDataMember[Inst] &&
253         "Already noted what static data member was instantiated from");
254  InstantiatedFromStaticDataMember[Inst]
255    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
256}
257
258UnresolvedUsingDecl *
259ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
260  llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
261    = InstantiatedFromUnresolvedUsingDecl.find(UUD);
262  if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
263    return 0;
264
265  return Pos->second;
266}
267
268void
269ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
270                                                   UnresolvedUsingDecl *UUD) {
271  assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
272         "Already noted what using decl what instantiated from");
273  InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
274}
275
276FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
277  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
278    = InstantiatedFromUnnamedFieldDecl.find(Field);
279  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
280    return 0;
281
282  return Pos->second;
283}
284
285void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
286                                                     FieldDecl *Tmpl) {
287  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
288  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
289  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
290         "Already noted what unnamed field was instantiated from");
291
292  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
293}
294
295namespace {
296  class BeforeInTranslationUnit
297    : std::binary_function<SourceRange, SourceRange, bool> {
298    SourceManager *SourceMgr;
299
300  public:
301    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
302
303    bool operator()(SourceRange X, SourceRange Y) {
304      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
305    }
306  };
307}
308
309/// \brief Determine whether the given comment is a Doxygen-style comment.
310///
311/// \param Start the start of the comment text.
312///
313/// \param End the end of the comment text.
314///
315/// \param Member whether we want to check whether this is a member comment
316/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
317/// we only return true when we find a non-member comment.
318static bool
319isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
320                 bool Member = false) {
321  const char *BufferStart
322    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
323  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
324  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
325
326  if (End - Start < 4)
327    return false;
328
329  assert(Start[0] == '/' && "Not a comment?");
330  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
331    return false;
332  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
333    return false;
334
335  return (Start[3] == '<') == Member;
336}
337
338/// \brief Retrieve the comment associated with the given declaration, if
339/// it has one.
340const char *ASTContext::getCommentForDecl(const Decl *D) {
341  if (!D)
342    return 0;
343
344  // Check whether we have cached a comment string for this declaration
345  // already.
346  llvm::DenseMap<const Decl *, std::string>::iterator Pos
347    = DeclComments.find(D);
348  if (Pos != DeclComments.end())
349    return Pos->second.c_str();
350
351  // If we have an external AST source and have not yet loaded comments from
352  // that source, do so now.
353  if (ExternalSource && !LoadedExternalComments) {
354    std::vector<SourceRange> LoadedComments;
355    ExternalSource->ReadComments(LoadedComments);
356
357    if (!LoadedComments.empty())
358      Comments.insert(Comments.begin(), LoadedComments.begin(),
359                      LoadedComments.end());
360
361    LoadedExternalComments = true;
362  }
363
364  // If there are no comments anywhere, we won't find anything.
365  if (Comments.empty())
366    return 0;
367
368  // If the declaration doesn't map directly to a location in a file, we
369  // can't find the comment.
370  SourceLocation DeclStartLoc = D->getLocStart();
371  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
372    return 0;
373
374  // Find the comment that occurs just before this declaration.
375  std::vector<SourceRange>::iterator LastComment
376    = std::lower_bound(Comments.begin(), Comments.end(),
377                       SourceRange(DeclStartLoc),
378                       BeforeInTranslationUnit(&SourceMgr));
379
380  // Decompose the location for the start of the declaration and find the
381  // beginning of the file buffer.
382  std::pair<FileID, unsigned> DeclStartDecomp
383    = SourceMgr.getDecomposedLoc(DeclStartLoc);
384  const char *FileBufferStart
385    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
386
387  // First check whether we have a comment for a member.
388  if (LastComment != Comments.end() &&
389      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
390      isDoxygenComment(SourceMgr, *LastComment, true)) {
391    std::pair<FileID, unsigned> LastCommentEndDecomp
392      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
393    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
394        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
395          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
396                                     LastCommentEndDecomp.second)) {
397      // The Doxygen member comment comes after the declaration starts and
398      // is on the same line and in the same file as the declaration. This
399      // is the comment we want.
400      std::string &Result = DeclComments[D];
401      Result.append(FileBufferStart +
402                      SourceMgr.getFileOffset(LastComment->getBegin()),
403                    FileBufferStart + LastCommentEndDecomp.second + 1);
404      return Result.c_str();
405    }
406  }
407
408  if (LastComment == Comments.begin())
409    return 0;
410  --LastComment;
411
412  // Decompose the end of the comment.
413  std::pair<FileID, unsigned> LastCommentEndDecomp
414    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
415
416  // If the comment and the declaration aren't in the same file, then they
417  // aren't related.
418  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
419    return 0;
420
421  // Check that we actually have a Doxygen comment.
422  if (!isDoxygenComment(SourceMgr, *LastComment))
423    return 0;
424
425  // Compute the starting line for the declaration and for the end of the
426  // comment (this is expensive).
427  unsigned DeclStartLine
428    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
429  unsigned CommentEndLine
430    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
431                              LastCommentEndDecomp.second);
432
433  // If the comment does not end on the line prior to the declaration, then
434  // the comment is not associated with the declaration at all.
435  if (CommentEndLine + 1 != DeclStartLine)
436    return 0;
437
438  // We have a comment, but there may be more comments on the previous lines.
439  // Keep looking so long as the comments are still Doxygen comments and are
440  // still adjacent.
441  unsigned ExpectedLine
442    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
443  std::vector<SourceRange>::iterator FirstComment = LastComment;
444  while (FirstComment != Comments.begin()) {
445    // Look at the previous comment
446    --FirstComment;
447    std::pair<FileID, unsigned> Decomp
448      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
449
450    // If this previous comment is in a different file, we're done.
451    if (Decomp.first != DeclStartDecomp.first) {
452      ++FirstComment;
453      break;
454    }
455
456    // If this comment is not a Doxygen comment, we're done.
457    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
458      ++FirstComment;
459      break;
460    }
461
462    // If the line number is not what we expected, we're done.
463    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
464    if (Line != ExpectedLine) {
465      ++FirstComment;
466      break;
467    }
468
469    // Set the next expected line number.
470    ExpectedLine
471      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
472  }
473
474  // The iterator range [FirstComment, LastComment] contains all of the
475  // BCPL comments that, together, are associated with this declaration.
476  // Form a single comment block string for this declaration that concatenates
477  // all of these comments.
478  std::string &Result = DeclComments[D];
479  while (FirstComment != LastComment) {
480    std::pair<FileID, unsigned> DecompStart
481      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
482    std::pair<FileID, unsigned> DecompEnd
483      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
484    Result.append(FileBufferStart + DecompStart.second,
485                  FileBufferStart + DecompEnd.second + 1);
486    ++FirstComment;
487  }
488
489  // Append the last comment line.
490  Result.append(FileBufferStart +
491                  SourceMgr.getFileOffset(LastComment->getBegin()),
492                FileBufferStart + LastCommentEndDecomp.second + 1);
493  return Result.c_str();
494}
495
496//===----------------------------------------------------------------------===//
497//                         Type Sizing and Analysis
498//===----------------------------------------------------------------------===//
499
500/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
501/// scalar floating point type.
502const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
503  const BuiltinType *BT = T->getAs<BuiltinType>();
504  assert(BT && "Not a floating point type!");
505  switch (BT->getKind()) {
506  default: assert(0 && "Not a floating point type!");
507  case BuiltinType::Float:      return Target.getFloatFormat();
508  case BuiltinType::Double:     return Target.getDoubleFormat();
509  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
510  }
511}
512
513/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
514/// specified decl.  Note that bitfields do not have a valid alignment, so
515/// this method will assert on them.
516unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
517  unsigned Align = Target.getCharWidth();
518
519  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
520    Align = std::max(Align, AA->getAlignment());
521
522  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
523    QualType T = VD->getType();
524    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
525      unsigned AS = RT->getPointeeType().getAddressSpace();
526      Align = Target.getPointerAlign(AS);
527    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
528      // Incomplete or function types default to 1.
529      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
530        T = cast<ArrayType>(T)->getElementType();
531
532      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
533    }
534  }
535
536  return Align / Target.getCharWidth();
537}
538
539/// getTypeSize - Return the size of the specified type, in bits.  This method
540/// does not work on incomplete types.
541///
542/// FIXME: Pointers into different addr spaces could have different sizes and
543/// alignment requirements: getPointerInfo should take an AddrSpace, this
544/// should take a QualType, &c.
545std::pair<uint64_t, unsigned>
546ASTContext::getTypeInfo(const Type *T) {
547  uint64_t Width=0;
548  unsigned Align=8;
549  switch (T->getTypeClass()) {
550#define TYPE(Class, Base)
551#define ABSTRACT_TYPE(Class, Base)
552#define NON_CANONICAL_TYPE(Class, Base)
553#define DEPENDENT_TYPE(Class, Base) case Type::Class:
554#include "clang/AST/TypeNodes.def"
555    assert(false && "Should not see dependent types");
556    break;
557
558  case Type::FunctionNoProto:
559  case Type::FunctionProto:
560    // GCC extension: alignof(function) = 32 bits
561    Width = 0;
562    Align = 32;
563    break;
564
565  case Type::IncompleteArray:
566  case Type::VariableArray:
567    Width = 0;
568    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
569    break;
570
571  case Type::ConstantArray: {
572    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
573
574    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
575    Width = EltInfo.first*CAT->getSize().getZExtValue();
576    Align = EltInfo.second;
577    break;
578  }
579  case Type::ExtVector:
580  case Type::Vector: {
581    const VectorType *VT = cast<VectorType>(T);
582    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
583    Width = EltInfo.first*VT->getNumElements();
584    Align = Width;
585    // If the alignment is not a power of 2, round up to the next power of 2.
586    // This happens for non-power-of-2 length vectors.
587    if (VT->getNumElements() & (VT->getNumElements()-1)) {
588      Align = llvm::NextPowerOf2(Align);
589      Width = llvm::RoundUpToAlignment(Width, Align);
590    }
591    break;
592  }
593
594  case Type::Builtin:
595    switch (cast<BuiltinType>(T)->getKind()) {
596    default: assert(0 && "Unknown builtin type!");
597    case BuiltinType::Void:
598      // GCC extension: alignof(void) = 8 bits.
599      Width = 0;
600      Align = 8;
601      break;
602
603    case BuiltinType::Bool:
604      Width = Target.getBoolWidth();
605      Align = Target.getBoolAlign();
606      break;
607    case BuiltinType::Char_S:
608    case BuiltinType::Char_U:
609    case BuiltinType::UChar:
610    case BuiltinType::SChar:
611      Width = Target.getCharWidth();
612      Align = Target.getCharAlign();
613      break;
614    case BuiltinType::WChar:
615      Width = Target.getWCharWidth();
616      Align = Target.getWCharAlign();
617      break;
618    case BuiltinType::Char16:
619      Width = Target.getChar16Width();
620      Align = Target.getChar16Align();
621      break;
622    case BuiltinType::Char32:
623      Width = Target.getChar32Width();
624      Align = Target.getChar32Align();
625      break;
626    case BuiltinType::UShort:
627    case BuiltinType::Short:
628      Width = Target.getShortWidth();
629      Align = Target.getShortAlign();
630      break;
631    case BuiltinType::UInt:
632    case BuiltinType::Int:
633      Width = Target.getIntWidth();
634      Align = Target.getIntAlign();
635      break;
636    case BuiltinType::ULong:
637    case BuiltinType::Long:
638      Width = Target.getLongWidth();
639      Align = Target.getLongAlign();
640      break;
641    case BuiltinType::ULongLong:
642    case BuiltinType::LongLong:
643      Width = Target.getLongLongWidth();
644      Align = Target.getLongLongAlign();
645      break;
646    case BuiltinType::Int128:
647    case BuiltinType::UInt128:
648      Width = 128;
649      Align = 128; // int128_t is 128-bit aligned on all targets.
650      break;
651    case BuiltinType::Float:
652      Width = Target.getFloatWidth();
653      Align = Target.getFloatAlign();
654      break;
655    case BuiltinType::Double:
656      Width = Target.getDoubleWidth();
657      Align = Target.getDoubleAlign();
658      break;
659    case BuiltinType::LongDouble:
660      Width = Target.getLongDoubleWidth();
661      Align = Target.getLongDoubleAlign();
662      break;
663    case BuiltinType::NullPtr:
664      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
665      Align = Target.getPointerAlign(0); //   == sizeof(void*)
666      break;
667    }
668    break;
669  case Type::FixedWidthInt:
670    // FIXME: This isn't precisely correct; the width/alignment should depend
671    // on the available types for the target
672    Width = cast<FixedWidthIntType>(T)->getWidth();
673    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
674    Align = Width;
675    break;
676  case Type::ObjCObjectPointer:
677    Width = Target.getPointerWidth(0);
678    Align = Target.getPointerAlign(0);
679    break;
680  case Type::BlockPointer: {
681    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
682    Width = Target.getPointerWidth(AS);
683    Align = Target.getPointerAlign(AS);
684    break;
685  }
686  case Type::Pointer: {
687    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
688    Width = Target.getPointerWidth(AS);
689    Align = Target.getPointerAlign(AS);
690    break;
691  }
692  case Type::LValueReference:
693  case Type::RValueReference:
694    // "When applied to a reference or a reference type, the result is the size
695    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
696    // FIXME: This is wrong for struct layout: a reference in a struct has
697    // pointer size.
698    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
699  case Type::MemberPointer: {
700    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
701    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
702    // If we ever want to support other ABIs this needs to be abstracted.
703
704    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
705    std::pair<uint64_t, unsigned> PtrDiffInfo =
706      getTypeInfo(getPointerDiffType());
707    Width = PtrDiffInfo.first;
708    if (Pointee->isFunctionType())
709      Width *= 2;
710    Align = PtrDiffInfo.second;
711    break;
712  }
713  case Type::Complex: {
714    // Complex types have the same alignment as their elements, but twice the
715    // size.
716    std::pair<uint64_t, unsigned> EltInfo =
717      getTypeInfo(cast<ComplexType>(T)->getElementType());
718    Width = EltInfo.first*2;
719    Align = EltInfo.second;
720    break;
721  }
722  case Type::ObjCInterface: {
723    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
724    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
725    Width = Layout.getSize();
726    Align = Layout.getAlignment();
727    break;
728  }
729  case Type::Record:
730  case Type::Enum: {
731    const TagType *TT = cast<TagType>(T);
732
733    if (TT->getDecl()->isInvalidDecl()) {
734      Width = 1;
735      Align = 1;
736      break;
737    }
738
739    if (const EnumType *ET = dyn_cast<EnumType>(TT))
740      return getTypeInfo(ET->getDecl()->getIntegerType());
741
742    const RecordType *RT = cast<RecordType>(TT);
743    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
744    Width = Layout.getSize();
745    Align = Layout.getAlignment();
746    break;
747  }
748
749  case Type::SubstTemplateTypeParm:
750    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
751                       getReplacementType().getTypePtr());
752
753  case Type::Elaborated:
754    return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
755                         .getTypePtr());
756
757  case Type::Typedef: {
758    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
759    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
760      Align = Aligned->getAlignment();
761      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
762    } else
763      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
764    break;
765  }
766
767  case Type::TypeOfExpr:
768    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
769                         .getTypePtr());
770
771  case Type::TypeOf:
772    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
773
774  case Type::Decltype:
775    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
776                        .getTypePtr());
777
778  case Type::QualifiedName:
779    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
780
781  case Type::TemplateSpecialization:
782    assert(getCanonicalType(T) != T &&
783           "Cannot request the size of a dependent type");
784    // FIXME: this is likely to be wrong once we support template
785    // aliases, since a template alias could refer to a typedef that
786    // has an __aligned__ attribute on it.
787    return getTypeInfo(getCanonicalType(T));
788  }
789
790  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
791  return std::make_pair(Width, Align);
792}
793
794/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
795/// type for the current target in bits.  This can be different than the ABI
796/// alignment in cases where it is beneficial for performance to overalign
797/// a data type.
798unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
799  unsigned ABIAlign = getTypeAlign(T);
800
801  // Double and long long should be naturally aligned if possible.
802  if (const ComplexType* CT = T->getAs<ComplexType>())
803    T = CT->getElementType().getTypePtr();
804  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
805      T->isSpecificBuiltinType(BuiltinType::LongLong))
806    return std::max(ABIAlign, (unsigned)getTypeSize(T));
807
808  return ABIAlign;
809}
810
811static void CollectLocalObjCIvars(ASTContext *Ctx,
812                                  const ObjCInterfaceDecl *OI,
813                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
814  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
815       E = OI->ivar_end(); I != E; ++I) {
816    ObjCIvarDecl *IVDecl = *I;
817    if (!IVDecl->isInvalidDecl())
818      Fields.push_back(cast<FieldDecl>(IVDecl));
819  }
820}
821
822void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
823                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
824  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
825    CollectObjCIvars(SuperClass, Fields);
826  CollectLocalObjCIvars(this, OI, Fields);
827}
828
829/// ShallowCollectObjCIvars -
830/// Collect all ivars, including those synthesized, in the current class.
831///
832void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
833                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
834                                 bool CollectSynthesized) {
835  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836         E = OI->ivar_end(); I != E; ++I) {
837     Ivars.push_back(*I);
838  }
839  if (CollectSynthesized)
840    CollectSynthesizedIvars(OI, Ivars);
841}
842
843void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
844                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
845  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
846       E = PD->prop_end(); I != E; ++I)
847    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
848      Ivars.push_back(Ivar);
849
850  // Also look into nested protocols.
851  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
852       E = PD->protocol_end(); P != E; ++P)
853    CollectProtocolSynthesizedIvars(*P, Ivars);
854}
855
856/// CollectSynthesizedIvars -
857/// This routine collect synthesized ivars for the designated class.
858///
859void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
860                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
861  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
862       E = OI->prop_end(); I != E; ++I) {
863    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
864      Ivars.push_back(Ivar);
865  }
866  // Also look into interface's protocol list for properties declared
867  // in the protocol and whose ivars are synthesized.
868  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
869       PE = OI->protocol_end(); P != PE; ++P) {
870    ObjCProtocolDecl *PD = (*P);
871    CollectProtocolSynthesizedIvars(PD, Ivars);
872  }
873}
874
875unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
876  unsigned count = 0;
877  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
878       E = PD->prop_end(); I != E; ++I)
879    if ((*I)->getPropertyIvarDecl())
880      ++count;
881
882  // Also look into nested protocols.
883  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
884       E = PD->protocol_end(); P != E; ++P)
885    count += CountProtocolSynthesizedIvars(*P);
886  return count;
887}
888
889unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
890  unsigned count = 0;
891  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
892       E = OI->prop_end(); I != E; ++I) {
893    if ((*I)->getPropertyIvarDecl())
894      ++count;
895  }
896  // Also look into interface's protocol list for properties declared
897  // in the protocol and whose ivars are synthesized.
898  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
899       PE = OI->protocol_end(); P != PE; ++P) {
900    ObjCProtocolDecl *PD = (*P);
901    count += CountProtocolSynthesizedIvars(PD);
902  }
903  return count;
904}
905
906/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
907ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
908  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
909    I = ObjCImpls.find(D);
910  if (I != ObjCImpls.end())
911    return cast<ObjCImplementationDecl>(I->second);
912  return 0;
913}
914/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
915ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
916  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
917    I = ObjCImpls.find(D);
918  if (I != ObjCImpls.end())
919    return cast<ObjCCategoryImplDecl>(I->second);
920  return 0;
921}
922
923/// \brief Set the implementation of ObjCInterfaceDecl.
924void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
925                           ObjCImplementationDecl *ImplD) {
926  assert(IFaceD && ImplD && "Passed null params");
927  ObjCImpls[IFaceD] = ImplD;
928}
929/// \brief Set the implementation of ObjCCategoryDecl.
930void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
931                           ObjCCategoryImplDecl *ImplD) {
932  assert(CatD && ImplD && "Passed null params");
933  ObjCImpls[CatD] = ImplD;
934}
935
936/// \brief Allocate an uninitialized DeclaratorInfo.
937///
938/// The caller should initialize the memory held by DeclaratorInfo using
939/// the TypeLoc wrappers.
940///
941/// \param T the type that will be the basis for type source info. This type
942/// should refer to how the declarator was written in source code, not to
943/// what type semantic analysis resolved the declarator to.
944DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
945                                                 unsigned DataSize) {
946  if (!DataSize)
947    DataSize = TypeLoc::getFullDataSizeForType(T);
948  else
949    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
950           "incorrect data size provided to CreateDeclaratorInfo!");
951
952  DeclaratorInfo *DInfo =
953    (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
954  new (DInfo) DeclaratorInfo(T);
955  return DInfo;
956}
957
958/// getInterfaceLayoutImpl - Get or compute information about the
959/// layout of the given interface.
960///
961/// \param Impl - If given, also include the layout of the interface's
962/// implementation. This may differ by including synthesized ivars.
963const ASTRecordLayout &
964ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
965                          const ObjCImplementationDecl *Impl) {
966  assert(!D->isForwardDecl() && "Invalid interface decl!");
967
968  // Look up this layout, if already laid out, return what we have.
969  ObjCContainerDecl *Key =
970    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
971  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
972    return *Entry;
973
974  // Add in synthesized ivar count if laying out an implementation.
975  if (Impl) {
976    unsigned FieldCount = D->ivar_size();
977    unsigned SynthCount = CountSynthesizedIvars(D);
978    FieldCount += SynthCount;
979    // If there aren't any sythesized ivars then reuse the interface
980    // entry. Note we can't cache this because we simply free all
981    // entries later; however we shouldn't look up implementations
982    // frequently.
983    if (SynthCount == 0)
984      return getObjCLayout(D, 0);
985  }
986
987  const ASTRecordLayout *NewEntry =
988    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
989  ObjCLayouts[Key] = NewEntry;
990
991  return *NewEntry;
992}
993
994const ASTRecordLayout &
995ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
996  return getObjCLayout(D, 0);
997}
998
999const ASTRecordLayout &
1000ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1001  return getObjCLayout(D->getClassInterface(), D);
1002}
1003
1004/// getASTRecordLayout - Get or compute information about the layout of the
1005/// specified record (struct/union/class), which indicates its size and field
1006/// position information.
1007const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
1008  D = D->getDefinition(*this);
1009  assert(D && "Cannot get layout of forward declarations!");
1010
1011  // Look up this layout, if already laid out, return what we have.
1012  // Note that we can't save a reference to the entry because this function
1013  // is recursive.
1014  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
1015  if (Entry) return *Entry;
1016
1017  const ASTRecordLayout *NewEntry =
1018    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
1019  ASTRecordLayouts[D] = NewEntry;
1020
1021  return *NewEntry;
1022}
1023
1024//===----------------------------------------------------------------------===//
1025//                   Type creation/memoization methods
1026//===----------------------------------------------------------------------===//
1027
1028QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1029  unsigned Fast = Quals.getFastQualifiers();
1030  Quals.removeFastQualifiers();
1031
1032  // Check if we've already instantiated this type.
1033  llvm::FoldingSetNodeID ID;
1034  ExtQuals::Profile(ID, TypeNode, Quals);
1035  void *InsertPos = 0;
1036  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1037    assert(EQ->getQualifiers() == Quals);
1038    QualType T = QualType(EQ, Fast);
1039    return T;
1040  }
1041
1042  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1043  ExtQualNodes.InsertNode(New, InsertPos);
1044  QualType T = QualType(New, Fast);
1045  return T;
1046}
1047
1048QualType ASTContext::getVolatileType(QualType T) {
1049  QualType CanT = getCanonicalType(T);
1050  if (CanT.isVolatileQualified()) return T;
1051
1052  QualifierCollector Quals;
1053  const Type *TypeNode = Quals.strip(T);
1054  Quals.addVolatile();
1055
1056  return getExtQualType(TypeNode, Quals);
1057}
1058
1059QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1060  QualType CanT = getCanonicalType(T);
1061  if (CanT.getAddressSpace() == AddressSpace)
1062    return T;
1063
1064  // If we are composing extended qualifiers together, merge together
1065  // into one ExtQuals node.
1066  QualifierCollector Quals;
1067  const Type *TypeNode = Quals.strip(T);
1068
1069  // If this type already has an address space specified, it cannot get
1070  // another one.
1071  assert(!Quals.hasAddressSpace() &&
1072         "Type cannot be in multiple addr spaces!");
1073  Quals.addAddressSpace(AddressSpace);
1074
1075  return getExtQualType(TypeNode, Quals);
1076}
1077
1078QualType ASTContext::getObjCGCQualType(QualType T,
1079                                       Qualifiers::GC GCAttr) {
1080  QualType CanT = getCanonicalType(T);
1081  if (CanT.getObjCGCAttr() == GCAttr)
1082    return T;
1083
1084  if (T->isPointerType()) {
1085    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1086    if (Pointee->isAnyPointerType()) {
1087      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1088      return getPointerType(ResultType);
1089    }
1090  }
1091
1092  // If we are composing extended qualifiers together, merge together
1093  // into one ExtQuals node.
1094  QualifierCollector Quals;
1095  const Type *TypeNode = Quals.strip(T);
1096
1097  // If this type already has an ObjCGC specified, it cannot get
1098  // another one.
1099  assert(!Quals.hasObjCGCAttr() &&
1100         "Type cannot have multiple ObjCGCs!");
1101  Quals.addObjCGCAttr(GCAttr);
1102
1103  return getExtQualType(TypeNode, Quals);
1104}
1105
1106QualType ASTContext::getNoReturnType(QualType T) {
1107  QualType ResultType;
1108  if (T->isPointerType()) {
1109    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1110    ResultType = getNoReturnType(Pointee);
1111    ResultType = getPointerType(ResultType);
1112  } else if (T->isBlockPointerType()) {
1113    QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
1114    ResultType = getNoReturnType(Pointee);
1115    ResultType = getBlockPointerType(ResultType);
1116  } else {
1117    assert (T->isFunctionType()
1118            && "can't noreturn qualify non-pointer to function or block type");
1119
1120    if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1121      ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
1122    } else {
1123      const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1124      ResultType
1125        = getFunctionType(F->getResultType(), F->arg_type_begin(),
1126                          F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1127                          F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1128                          F->getNumExceptions(), F->exception_begin(), true);
1129    }
1130  }
1131
1132  return getQualifiedType(ResultType, T.getQualifiers());
1133}
1134
1135/// getComplexType - Return the uniqued reference to the type for a complex
1136/// number with the specified element type.
1137QualType ASTContext::getComplexType(QualType T) {
1138  // Unique pointers, to guarantee there is only one pointer of a particular
1139  // structure.
1140  llvm::FoldingSetNodeID ID;
1141  ComplexType::Profile(ID, T);
1142
1143  void *InsertPos = 0;
1144  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1145    return QualType(CT, 0);
1146
1147  // If the pointee type isn't canonical, this won't be a canonical type either,
1148  // so fill in the canonical type field.
1149  QualType Canonical;
1150  if (!T.isCanonical()) {
1151    Canonical = getComplexType(getCanonicalType(T));
1152
1153    // Get the new insert position for the node we care about.
1154    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1155    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1156  }
1157  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1158  Types.push_back(New);
1159  ComplexTypes.InsertNode(New, InsertPos);
1160  return QualType(New, 0);
1161}
1162
1163QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1164  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1165     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1166  FixedWidthIntType *&Entry = Map[Width];
1167  if (!Entry)
1168    Entry = new FixedWidthIntType(Width, Signed);
1169  return QualType(Entry, 0);
1170}
1171
1172/// getPointerType - Return the uniqued reference to the type for a pointer to
1173/// the specified type.
1174QualType ASTContext::getPointerType(QualType T) {
1175  // Unique pointers, to guarantee there is only one pointer of a particular
1176  // structure.
1177  llvm::FoldingSetNodeID ID;
1178  PointerType::Profile(ID, T);
1179
1180  void *InsertPos = 0;
1181  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1182    return QualType(PT, 0);
1183
1184  // If the pointee type isn't canonical, this won't be a canonical type either,
1185  // so fill in the canonical type field.
1186  QualType Canonical;
1187  if (!T.isCanonical()) {
1188    Canonical = getPointerType(getCanonicalType(T));
1189
1190    // Get the new insert position for the node we care about.
1191    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1192    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1193  }
1194  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1195  Types.push_back(New);
1196  PointerTypes.InsertNode(New, InsertPos);
1197  return QualType(New, 0);
1198}
1199
1200/// getBlockPointerType - Return the uniqued reference to the type for
1201/// a pointer to the specified block.
1202QualType ASTContext::getBlockPointerType(QualType T) {
1203  assert(T->isFunctionType() && "block of function types only");
1204  // Unique pointers, to guarantee there is only one block of a particular
1205  // structure.
1206  llvm::FoldingSetNodeID ID;
1207  BlockPointerType::Profile(ID, T);
1208
1209  void *InsertPos = 0;
1210  if (BlockPointerType *PT =
1211        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1212    return QualType(PT, 0);
1213
1214  // If the block pointee type isn't canonical, this won't be a canonical
1215  // type either so fill in the canonical type field.
1216  QualType Canonical;
1217  if (!T.isCanonical()) {
1218    Canonical = getBlockPointerType(getCanonicalType(T));
1219
1220    // Get the new insert position for the node we care about.
1221    BlockPointerType *NewIP =
1222      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1223    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1224  }
1225  BlockPointerType *New
1226    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1227  Types.push_back(New);
1228  BlockPointerTypes.InsertNode(New, InsertPos);
1229  return QualType(New, 0);
1230}
1231
1232/// getLValueReferenceType - Return the uniqued reference to the type for an
1233/// lvalue reference to the specified type.
1234QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1235  // Unique pointers, to guarantee there is only one pointer of a particular
1236  // structure.
1237  llvm::FoldingSetNodeID ID;
1238  ReferenceType::Profile(ID, T, SpelledAsLValue);
1239
1240  void *InsertPos = 0;
1241  if (LValueReferenceType *RT =
1242        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1243    return QualType(RT, 0);
1244
1245  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1246
1247  // If the referencee type isn't canonical, this won't be a canonical type
1248  // either, so fill in the canonical type field.
1249  QualType Canonical;
1250  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1251    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1252    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1253
1254    // Get the new insert position for the node we care about.
1255    LValueReferenceType *NewIP =
1256      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1257    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1258  }
1259
1260  LValueReferenceType *New
1261    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1262                                                     SpelledAsLValue);
1263  Types.push_back(New);
1264  LValueReferenceTypes.InsertNode(New, InsertPos);
1265
1266  return QualType(New, 0);
1267}
1268
1269/// getRValueReferenceType - Return the uniqued reference to the type for an
1270/// rvalue reference to the specified type.
1271QualType ASTContext::getRValueReferenceType(QualType T) {
1272  // Unique pointers, to guarantee there is only one pointer of a particular
1273  // structure.
1274  llvm::FoldingSetNodeID ID;
1275  ReferenceType::Profile(ID, T, false);
1276
1277  void *InsertPos = 0;
1278  if (RValueReferenceType *RT =
1279        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1280    return QualType(RT, 0);
1281
1282  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1283
1284  // If the referencee type isn't canonical, this won't be a canonical type
1285  // either, so fill in the canonical type field.
1286  QualType Canonical;
1287  if (InnerRef || !T.isCanonical()) {
1288    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1289    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1290
1291    // Get the new insert position for the node we care about.
1292    RValueReferenceType *NewIP =
1293      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1294    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1295  }
1296
1297  RValueReferenceType *New
1298    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1299  Types.push_back(New);
1300  RValueReferenceTypes.InsertNode(New, InsertPos);
1301  return QualType(New, 0);
1302}
1303
1304/// getMemberPointerType - Return the uniqued reference to the type for a
1305/// member pointer to the specified type, in the specified class.
1306QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1307  // Unique pointers, to guarantee there is only one pointer of a particular
1308  // structure.
1309  llvm::FoldingSetNodeID ID;
1310  MemberPointerType::Profile(ID, T, Cls);
1311
1312  void *InsertPos = 0;
1313  if (MemberPointerType *PT =
1314      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1315    return QualType(PT, 0);
1316
1317  // If the pointee or class type isn't canonical, this won't be a canonical
1318  // type either, so fill in the canonical type field.
1319  QualType Canonical;
1320  if (!T.isCanonical()) {
1321    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1322
1323    // Get the new insert position for the node we care about.
1324    MemberPointerType *NewIP =
1325      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1326    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1327  }
1328  MemberPointerType *New
1329    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1330  Types.push_back(New);
1331  MemberPointerTypes.InsertNode(New, InsertPos);
1332  return QualType(New, 0);
1333}
1334
1335/// getConstantArrayType - Return the unique reference to the type for an
1336/// array of the specified element type.
1337QualType ASTContext::getConstantArrayType(QualType EltTy,
1338                                          const llvm::APInt &ArySizeIn,
1339                                          ArrayType::ArraySizeModifier ASM,
1340                                          unsigned EltTypeQuals) {
1341  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1342         "Constant array of VLAs is illegal!");
1343
1344  // Convert the array size into a canonical width matching the pointer size for
1345  // the target.
1346  llvm::APInt ArySize(ArySizeIn);
1347  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1348
1349  llvm::FoldingSetNodeID ID;
1350  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1351
1352  void *InsertPos = 0;
1353  if (ConstantArrayType *ATP =
1354      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1355    return QualType(ATP, 0);
1356
1357  // If the element type isn't canonical, this won't be a canonical type either,
1358  // so fill in the canonical type field.
1359  QualType Canonical;
1360  if (!EltTy.isCanonical()) {
1361    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1362                                     ASM, EltTypeQuals);
1363    // Get the new insert position for the node we care about.
1364    ConstantArrayType *NewIP =
1365      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1366    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1367  }
1368
1369  ConstantArrayType *New = new(*this,TypeAlignment)
1370    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1371  ConstantArrayTypes.InsertNode(New, InsertPos);
1372  Types.push_back(New);
1373  return QualType(New, 0);
1374}
1375
1376/// getVariableArrayType - Returns a non-unique reference to the type for a
1377/// variable array of the specified element type.
1378QualType ASTContext::getVariableArrayType(QualType EltTy,
1379                                          Expr *NumElts,
1380                                          ArrayType::ArraySizeModifier ASM,
1381                                          unsigned EltTypeQuals,
1382                                          SourceRange Brackets) {
1383  // Since we don't unique expressions, it isn't possible to unique VLA's
1384  // that have an expression provided for their size.
1385
1386  VariableArrayType *New = new(*this, TypeAlignment)
1387    VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
1388
1389  VariableArrayTypes.push_back(New);
1390  Types.push_back(New);
1391  return QualType(New, 0);
1392}
1393
1394/// getDependentSizedArrayType - Returns a non-unique reference to
1395/// the type for a dependently-sized array of the specified element
1396/// type.
1397QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1398                                                Expr *NumElts,
1399                                                ArrayType::ArraySizeModifier ASM,
1400                                                unsigned EltTypeQuals,
1401                                                SourceRange Brackets) {
1402  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1403         "Size must be type- or value-dependent!");
1404
1405  llvm::FoldingSetNodeID ID;
1406  DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1407                                   EltTypeQuals, NumElts);
1408
1409  void *InsertPos = 0;
1410  DependentSizedArrayType *Canon
1411    = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1412  DependentSizedArrayType *New;
1413  if (Canon) {
1414    // We already have a canonical version of this array type; use it as
1415    // the canonical type for a newly-built type.
1416    New = new (*this, TypeAlignment)
1417      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1418                              NumElts, ASM, EltTypeQuals, Brackets);
1419  } else {
1420    QualType CanonEltTy = getCanonicalType(EltTy);
1421    if (CanonEltTy == EltTy) {
1422      New = new (*this, TypeAlignment)
1423        DependentSizedArrayType(*this, EltTy, QualType(),
1424                                NumElts, ASM, EltTypeQuals, Brackets);
1425      DependentSizedArrayTypes.InsertNode(New, InsertPos);
1426    } else {
1427      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1428                                                  ASM, EltTypeQuals,
1429                                                  SourceRange());
1430      New = new (*this, TypeAlignment)
1431        DependentSizedArrayType(*this, EltTy, Canon,
1432                                NumElts, ASM, EltTypeQuals, Brackets);
1433    }
1434  }
1435
1436  Types.push_back(New);
1437  return QualType(New, 0);
1438}
1439
1440QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1441                                            ArrayType::ArraySizeModifier ASM,
1442                                            unsigned EltTypeQuals) {
1443  llvm::FoldingSetNodeID ID;
1444  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1445
1446  void *InsertPos = 0;
1447  if (IncompleteArrayType *ATP =
1448       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1449    return QualType(ATP, 0);
1450
1451  // If the element type isn't canonical, this won't be a canonical type
1452  // either, so fill in the canonical type field.
1453  QualType Canonical;
1454
1455  if (!EltTy.isCanonical()) {
1456    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1457                                       ASM, EltTypeQuals);
1458
1459    // Get the new insert position for the node we care about.
1460    IncompleteArrayType *NewIP =
1461      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1462    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1463  }
1464
1465  IncompleteArrayType *New = new (*this, TypeAlignment)
1466    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1467
1468  IncompleteArrayTypes.InsertNode(New, InsertPos);
1469  Types.push_back(New);
1470  return QualType(New, 0);
1471}
1472
1473/// getVectorType - Return the unique reference to a vector type of
1474/// the specified element type and size. VectorType must be a built-in type.
1475QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1476  BuiltinType *baseType;
1477
1478  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1479  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1480
1481  // Check if we've already instantiated a vector of this type.
1482  llvm::FoldingSetNodeID ID;
1483  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1484  void *InsertPos = 0;
1485  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1486    return QualType(VTP, 0);
1487
1488  // If the element type isn't canonical, this won't be a canonical type either,
1489  // so fill in the canonical type field.
1490  QualType Canonical;
1491  if (!vecType.isCanonical()) {
1492    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1493
1494    // Get the new insert position for the node we care about.
1495    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1496    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1497  }
1498  VectorType *New = new (*this, TypeAlignment)
1499    VectorType(vecType, NumElts, Canonical);
1500  VectorTypes.InsertNode(New, InsertPos);
1501  Types.push_back(New);
1502  return QualType(New, 0);
1503}
1504
1505/// getExtVectorType - Return the unique reference to an extended vector type of
1506/// the specified element type and size. VectorType must be a built-in type.
1507QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1508  BuiltinType *baseType;
1509
1510  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1511  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1512
1513  // Check if we've already instantiated a vector of this type.
1514  llvm::FoldingSetNodeID ID;
1515  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1516  void *InsertPos = 0;
1517  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1518    return QualType(VTP, 0);
1519
1520  // If the element type isn't canonical, this won't be a canonical type either,
1521  // so fill in the canonical type field.
1522  QualType Canonical;
1523  if (!vecType.isCanonical()) {
1524    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1525
1526    // Get the new insert position for the node we care about.
1527    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1528    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1529  }
1530  ExtVectorType *New = new (*this, TypeAlignment)
1531    ExtVectorType(vecType, NumElts, Canonical);
1532  VectorTypes.InsertNode(New, InsertPos);
1533  Types.push_back(New);
1534  return QualType(New, 0);
1535}
1536
1537QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1538                                                    Expr *SizeExpr,
1539                                                    SourceLocation AttrLoc) {
1540  llvm::FoldingSetNodeID ID;
1541  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1542                                       SizeExpr);
1543
1544  void *InsertPos = 0;
1545  DependentSizedExtVectorType *Canon
1546    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1547  DependentSizedExtVectorType *New;
1548  if (Canon) {
1549    // We already have a canonical version of this array type; use it as
1550    // the canonical type for a newly-built type.
1551    New = new (*this, TypeAlignment)
1552      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1553                                  SizeExpr, AttrLoc);
1554  } else {
1555    QualType CanonVecTy = getCanonicalType(vecType);
1556    if (CanonVecTy == vecType) {
1557      New = new (*this, TypeAlignment)
1558        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1559                                    AttrLoc);
1560      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1561    } else {
1562      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1563                                                      SourceLocation());
1564      New = new (*this, TypeAlignment)
1565        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1566    }
1567  }
1568
1569  Types.push_back(New);
1570  return QualType(New, 0);
1571}
1572
1573/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1574///
1575QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
1576  // Unique functions, to guarantee there is only one function of a particular
1577  // structure.
1578  llvm::FoldingSetNodeID ID;
1579  FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
1580
1581  void *InsertPos = 0;
1582  if (FunctionNoProtoType *FT =
1583        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1584    return QualType(FT, 0);
1585
1586  QualType Canonical;
1587  if (!ResultTy.isCanonical()) {
1588    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
1589
1590    // Get the new insert position for the node we care about.
1591    FunctionNoProtoType *NewIP =
1592      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1593    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1594  }
1595
1596  FunctionNoProtoType *New = new (*this, TypeAlignment)
1597    FunctionNoProtoType(ResultTy, Canonical, NoReturn);
1598  Types.push_back(New);
1599  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1600  return QualType(New, 0);
1601}
1602
1603/// getFunctionType - Return a normal function type with a typed argument
1604/// list.  isVariadic indicates whether the argument list includes '...'.
1605QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1606                                     unsigned NumArgs, bool isVariadic,
1607                                     unsigned TypeQuals, bool hasExceptionSpec,
1608                                     bool hasAnyExceptionSpec, unsigned NumExs,
1609                                     const QualType *ExArray, bool NoReturn) {
1610  // Unique functions, to guarantee there is only one function of a particular
1611  // structure.
1612  llvm::FoldingSetNodeID ID;
1613  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1614                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1615                             NumExs, ExArray, NoReturn);
1616
1617  void *InsertPos = 0;
1618  if (FunctionProtoType *FTP =
1619        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1620    return QualType(FTP, 0);
1621
1622  // Determine whether the type being created is already canonical or not.
1623  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1624  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1625    if (!ArgArray[i].isCanonicalAsParam())
1626      isCanonical = false;
1627
1628  // If this type isn't canonical, get the canonical version of it.
1629  // The exception spec is not part of the canonical type.
1630  QualType Canonical;
1631  if (!isCanonical) {
1632    llvm::SmallVector<QualType, 16> CanonicalArgs;
1633    CanonicalArgs.reserve(NumArgs);
1634    for (unsigned i = 0; i != NumArgs; ++i)
1635      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1636
1637    Canonical = getFunctionType(getCanonicalType(ResultTy),
1638                                CanonicalArgs.data(), NumArgs,
1639                                isVariadic, TypeQuals, false,
1640                                false, 0, 0, NoReturn);
1641
1642    // Get the new insert position for the node we care about.
1643    FunctionProtoType *NewIP =
1644      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1645    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1646  }
1647
1648  // FunctionProtoType objects are allocated with extra bytes after them
1649  // for two variable size arrays (for parameter and exception types) at the
1650  // end of them.
1651  FunctionProtoType *FTP =
1652    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1653                                 NumArgs*sizeof(QualType) +
1654                                 NumExs*sizeof(QualType), TypeAlignment);
1655  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1656                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1657                              ExArray, NumExs, Canonical, NoReturn);
1658  Types.push_back(FTP);
1659  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1660  return QualType(FTP, 0);
1661}
1662
1663/// getTypeDeclType - Return the unique reference to the type for the
1664/// specified type declaration.
1665QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1666  assert(Decl && "Passed null for Decl param");
1667  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1668
1669  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1670    return getTypedefType(Typedef);
1671  else if (isa<TemplateTypeParmDecl>(Decl)) {
1672    assert(false && "Template type parameter types are always available.");
1673  } else if (ObjCInterfaceDecl *ObjCInterface
1674               = dyn_cast<ObjCInterfaceDecl>(Decl))
1675    return getObjCInterfaceType(ObjCInterface);
1676
1677  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1678    if (PrevDecl)
1679      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1680    else
1681      Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1682  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1683    if (PrevDecl)
1684      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1685    else
1686      Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1687  } else
1688    assert(false && "TypeDecl without a type?");
1689
1690  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1691  return QualType(Decl->TypeForDecl, 0);
1692}
1693
1694/// getTypedefType - Return the unique reference to the type for the
1695/// specified typename decl.
1696QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1697  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1698
1699  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1700  Decl->TypeForDecl = new(*this, TypeAlignment)
1701    TypedefType(Type::Typedef, Decl, Canonical);
1702  Types.push_back(Decl->TypeForDecl);
1703  return QualType(Decl->TypeForDecl, 0);
1704}
1705
1706/// \brief Retrieve a substitution-result type.
1707QualType
1708ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1709                                         QualType Replacement) {
1710  assert(Replacement.isCanonical()
1711         && "replacement types must always be canonical");
1712
1713  llvm::FoldingSetNodeID ID;
1714  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1715  void *InsertPos = 0;
1716  SubstTemplateTypeParmType *SubstParm
1717    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1718
1719  if (!SubstParm) {
1720    SubstParm = new (*this, TypeAlignment)
1721      SubstTemplateTypeParmType(Parm, Replacement);
1722    Types.push_back(SubstParm);
1723    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1724  }
1725
1726  return QualType(SubstParm, 0);
1727}
1728
1729/// \brief Retrieve the template type parameter type for a template
1730/// parameter or parameter pack with the given depth, index, and (optionally)
1731/// name.
1732QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1733                                             bool ParameterPack,
1734                                             IdentifierInfo *Name) {
1735  llvm::FoldingSetNodeID ID;
1736  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1737  void *InsertPos = 0;
1738  TemplateTypeParmType *TypeParm
1739    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1740
1741  if (TypeParm)
1742    return QualType(TypeParm, 0);
1743
1744  if (Name) {
1745    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1746    TypeParm = new (*this, TypeAlignment)
1747      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1748  } else
1749    TypeParm = new (*this, TypeAlignment)
1750      TemplateTypeParmType(Depth, Index, ParameterPack);
1751
1752  Types.push_back(TypeParm);
1753  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1754
1755  return QualType(TypeParm, 0);
1756}
1757
1758QualType
1759ASTContext::getTemplateSpecializationType(TemplateName Template,
1760                                          const TemplateArgument *Args,
1761                                          unsigned NumArgs,
1762                                          QualType Canon) {
1763  if (!Canon.isNull())
1764    Canon = getCanonicalType(Canon);
1765  else {
1766    // Build the canonical template specialization type.
1767    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1768    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1769    CanonArgs.reserve(NumArgs);
1770    for (unsigned I = 0; I != NumArgs; ++I)
1771      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1772
1773    // Determine whether this canonical template specialization type already
1774    // exists.
1775    llvm::FoldingSetNodeID ID;
1776    TemplateSpecializationType::Profile(ID, CanonTemplate,
1777                                        CanonArgs.data(), NumArgs, *this);
1778
1779    void *InsertPos = 0;
1780    TemplateSpecializationType *Spec
1781      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1782
1783    if (!Spec) {
1784      // Allocate a new canonical template specialization type.
1785      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1786                            sizeof(TemplateArgument) * NumArgs),
1787                           TypeAlignment);
1788      Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
1789                                                  CanonArgs.data(), NumArgs,
1790                                                  Canon);
1791      Types.push_back(Spec);
1792      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1793    }
1794
1795    if (Canon.isNull())
1796      Canon = QualType(Spec, 0);
1797    assert(Canon->isDependentType() &&
1798           "Non-dependent template-id type must have a canonical type");
1799  }
1800
1801  // Allocate the (non-canonical) template specialization type, but don't
1802  // try to unique it: these types typically have location information that
1803  // we don't unique and don't want to lose.
1804  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1805                        sizeof(TemplateArgument) * NumArgs),
1806                       TypeAlignment);
1807  TemplateSpecializationType *Spec
1808    = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1809                                           Canon);
1810
1811  Types.push_back(Spec);
1812  return QualType(Spec, 0);
1813}
1814
1815QualType
1816ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1817                                 QualType NamedType) {
1818  llvm::FoldingSetNodeID ID;
1819  QualifiedNameType::Profile(ID, NNS, NamedType);
1820
1821  void *InsertPos = 0;
1822  QualifiedNameType *T
1823    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1824  if (T)
1825    return QualType(T, 0);
1826
1827  T = new (*this) QualifiedNameType(NNS, NamedType,
1828                                    getCanonicalType(NamedType));
1829  Types.push_back(T);
1830  QualifiedNameTypes.InsertNode(T, InsertPos);
1831  return QualType(T, 0);
1832}
1833
1834QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1835                                     const IdentifierInfo *Name,
1836                                     QualType Canon) {
1837  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1838
1839  if (Canon.isNull()) {
1840    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1841    if (CanonNNS != NNS)
1842      Canon = getTypenameType(CanonNNS, Name);
1843  }
1844
1845  llvm::FoldingSetNodeID ID;
1846  TypenameType::Profile(ID, NNS, Name);
1847
1848  void *InsertPos = 0;
1849  TypenameType *T
1850    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1851  if (T)
1852    return QualType(T, 0);
1853
1854  T = new (*this) TypenameType(NNS, Name, Canon);
1855  Types.push_back(T);
1856  TypenameTypes.InsertNode(T, InsertPos);
1857  return QualType(T, 0);
1858}
1859
1860QualType
1861ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1862                            const TemplateSpecializationType *TemplateId,
1863                            QualType Canon) {
1864  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1865
1866  if (Canon.isNull()) {
1867    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1868    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1869    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1870      const TemplateSpecializationType *CanonTemplateId
1871        = CanonType->getAs<TemplateSpecializationType>();
1872      assert(CanonTemplateId &&
1873             "Canonical type must also be a template specialization type");
1874      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1875    }
1876  }
1877
1878  llvm::FoldingSetNodeID ID;
1879  TypenameType::Profile(ID, NNS, TemplateId);
1880
1881  void *InsertPos = 0;
1882  TypenameType *T
1883    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1884  if (T)
1885    return QualType(T, 0);
1886
1887  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1888  Types.push_back(T);
1889  TypenameTypes.InsertNode(T, InsertPos);
1890  return QualType(T, 0);
1891}
1892
1893QualType
1894ASTContext::getElaboratedType(QualType UnderlyingType,
1895                              ElaboratedType::TagKind Tag) {
1896  llvm::FoldingSetNodeID ID;
1897  ElaboratedType::Profile(ID, UnderlyingType, Tag);
1898
1899  void *InsertPos = 0;
1900  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1901  if (T)
1902    return QualType(T, 0);
1903
1904  QualType Canon = getCanonicalType(UnderlyingType);
1905
1906  T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1907  Types.push_back(T);
1908  ElaboratedTypes.InsertNode(T, InsertPos);
1909  return QualType(T, 0);
1910}
1911
1912/// CmpProtocolNames - Comparison predicate for sorting protocols
1913/// alphabetically.
1914static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1915                            const ObjCProtocolDecl *RHS) {
1916  return LHS->getDeclName() < RHS->getDeclName();
1917}
1918
1919static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
1920                                unsigned NumProtocols) {
1921  if (NumProtocols == 0) return true;
1922
1923  for (unsigned i = 1; i != NumProtocols; ++i)
1924    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1925      return false;
1926  return true;
1927}
1928
1929static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
1930                                   unsigned &NumProtocols) {
1931  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1932
1933  // Sort protocols, keyed by name.
1934  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1935
1936  // Remove duplicates.
1937  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1938  NumProtocols = ProtocolsEnd-Protocols;
1939}
1940
1941/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1942/// the given interface decl and the conforming protocol list.
1943QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
1944                                              ObjCProtocolDecl **Protocols,
1945                                              unsigned NumProtocols) {
1946  llvm::FoldingSetNodeID ID;
1947  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
1948
1949  void *InsertPos = 0;
1950  if (ObjCObjectPointerType *QT =
1951              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1952    return QualType(QT, 0);
1953
1954  // Sort the protocol list alphabetically to canonicalize it.
1955  QualType Canonical;
1956  if (!InterfaceT.isCanonical() ||
1957      !areSortedAndUniqued(Protocols, NumProtocols)) {
1958    if (!areSortedAndUniqued(Protocols, NumProtocols)) {
1959      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
1960      unsigned UniqueCount = NumProtocols;
1961
1962      std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
1963      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
1964
1965      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1966                                           &Sorted[0], UniqueCount);
1967    } else {
1968      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
1969                                           Protocols, NumProtocols);
1970    }
1971
1972    // Regenerate InsertPos.
1973    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1974  }
1975
1976  // No Match;
1977  ObjCObjectPointerType *QType = new (*this, TypeAlignment)
1978    ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
1979
1980  Types.push_back(QType);
1981  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1982  return QualType(QType, 0);
1983}
1984
1985/// getObjCInterfaceType - Return the unique reference to the type for the
1986/// specified ObjC interface decl. The list of protocols is optional.
1987QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1988                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1989  llvm::FoldingSetNodeID ID;
1990  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1991
1992  void *InsertPos = 0;
1993  if (ObjCInterfaceType *QT =
1994      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1995    return QualType(QT, 0);
1996
1997  // Sort the protocol list alphabetically to canonicalize it.
1998  QualType Canonical;
1999  if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2000    llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2001    std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2002
2003    unsigned UniqueCount = NumProtocols;
2004    SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2005
2006    Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2007
2008    ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2009  }
2010
2011  ObjCInterfaceType *QType = new (*this, TypeAlignment)
2012    ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
2013                      Protocols, NumProtocols);
2014
2015  Types.push_back(QType);
2016  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
2017  return QualType(QType, 0);
2018}
2019
2020/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2021/// TypeOfExprType AST's (since expression's are never shared). For example,
2022/// multiple declarations that refer to "typeof(x)" all contain different
2023/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2024/// on canonical type's (which are always unique).
2025QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2026  TypeOfExprType *toe;
2027  if (tofExpr->isTypeDependent()) {
2028    llvm::FoldingSetNodeID ID;
2029    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2030
2031    void *InsertPos = 0;
2032    DependentTypeOfExprType *Canon
2033      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2034    if (Canon) {
2035      // We already have a "canonical" version of an identical, dependent
2036      // typeof(expr) type. Use that as our canonical type.
2037      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2038                                          QualType((TypeOfExprType*)Canon, 0));
2039    }
2040    else {
2041      // Build a new, canonical typeof(expr) type.
2042      Canon
2043        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2044      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2045      toe = Canon;
2046    }
2047  } else {
2048    QualType Canonical = getCanonicalType(tofExpr->getType());
2049    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2050  }
2051  Types.push_back(toe);
2052  return QualType(toe, 0);
2053}
2054
2055/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2056/// TypeOfType AST's. The only motivation to unique these nodes would be
2057/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2058/// an issue. This doesn't effect the type checker, since it operates
2059/// on canonical type's (which are always unique).
2060QualType ASTContext::getTypeOfType(QualType tofType) {
2061  QualType Canonical = getCanonicalType(tofType);
2062  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2063  Types.push_back(tot);
2064  return QualType(tot, 0);
2065}
2066
2067/// getDecltypeForExpr - Given an expr, will return the decltype for that
2068/// expression, according to the rules in C++0x [dcl.type.simple]p4
2069static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2070  if (e->isTypeDependent())
2071    return Context.DependentTy;
2072
2073  // If e is an id expression or a class member access, decltype(e) is defined
2074  // as the type of the entity named by e.
2075  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2076    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2077      return VD->getType();
2078  }
2079  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2080    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2081      return FD->getType();
2082  }
2083  // If e is a function call or an invocation of an overloaded operator,
2084  // (parentheses around e are ignored), decltype(e) is defined as the
2085  // return type of that function.
2086  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2087    return CE->getCallReturnType();
2088
2089  QualType T = e->getType();
2090
2091  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2092  // defined as T&, otherwise decltype(e) is defined as T.
2093  if (e->isLvalue(Context) == Expr::LV_Valid)
2094    T = Context.getLValueReferenceType(T);
2095
2096  return T;
2097}
2098
2099/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2100/// DecltypeType AST's. The only motivation to unique these nodes would be
2101/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2102/// an issue. This doesn't effect the type checker, since it operates
2103/// on canonical type's (which are always unique).
2104QualType ASTContext::getDecltypeType(Expr *e) {
2105  DecltypeType *dt;
2106  if (e->isTypeDependent()) {
2107    llvm::FoldingSetNodeID ID;
2108    DependentDecltypeType::Profile(ID, *this, e);
2109
2110    void *InsertPos = 0;
2111    DependentDecltypeType *Canon
2112      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2113    if (Canon) {
2114      // We already have a "canonical" version of an equivalent, dependent
2115      // decltype type. Use that as our canonical type.
2116      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2117                                       QualType((DecltypeType*)Canon, 0));
2118    }
2119    else {
2120      // Build a new, canonical typeof(expr) type.
2121      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2122      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2123      dt = Canon;
2124    }
2125  } else {
2126    QualType T = getDecltypeForExpr(e, *this);
2127    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2128  }
2129  Types.push_back(dt);
2130  return QualType(dt, 0);
2131}
2132
2133/// getTagDeclType - Return the unique reference to the type for the
2134/// specified TagDecl (struct/union/class/enum) decl.
2135QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2136  assert (Decl);
2137  // FIXME: What is the design on getTagDeclType when it requires casting
2138  // away const?  mutable?
2139  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2140}
2141
2142/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2143/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2144/// needs to agree with the definition in <stddef.h>.
2145QualType ASTContext::getSizeType() const {
2146  return getFromTargetType(Target.getSizeType());
2147}
2148
2149/// getSignedWCharType - Return the type of "signed wchar_t".
2150/// Used when in C++, as a GCC extension.
2151QualType ASTContext::getSignedWCharType() const {
2152  // FIXME: derive from "Target" ?
2153  return WCharTy;
2154}
2155
2156/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2157/// Used when in C++, as a GCC extension.
2158QualType ASTContext::getUnsignedWCharType() const {
2159  // FIXME: derive from "Target" ?
2160  return UnsignedIntTy;
2161}
2162
2163/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2164/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2165QualType ASTContext::getPointerDiffType() const {
2166  return getFromTargetType(Target.getPtrDiffType(0));
2167}
2168
2169//===----------------------------------------------------------------------===//
2170//                              Type Operators
2171//===----------------------------------------------------------------------===//
2172
2173CanQualType ASTContext::getCanonicalParamType(QualType T) {
2174  // Push qualifiers into arrays, and then discard any remaining
2175  // qualifiers.
2176  T = getCanonicalType(T);
2177  const Type *Ty = T.getTypePtr();
2178
2179  QualType Result;
2180  if (isa<ArrayType>(Ty)) {
2181    Result = getArrayDecayedType(QualType(Ty,0));
2182  } else if (isa<FunctionType>(Ty)) {
2183    Result = getPointerType(QualType(Ty, 0));
2184  } else {
2185    Result = QualType(Ty, 0);
2186  }
2187
2188  return CanQualType::CreateUnsafe(Result);
2189}
2190
2191/// getCanonicalType - Return the canonical (structural) type corresponding to
2192/// the specified potentially non-canonical type.  The non-canonical version
2193/// of a type may have many "decorated" versions of types.  Decorators can
2194/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2195/// to be free of any of these, allowing two canonical types to be compared
2196/// for exact equality with a simple pointer comparison.
2197CanQualType ASTContext::getCanonicalType(QualType T) {
2198  QualifierCollector Quals;
2199  const Type *Ptr = Quals.strip(T);
2200  QualType CanType = Ptr->getCanonicalTypeInternal();
2201
2202  // The canonical internal type will be the canonical type *except*
2203  // that we push type qualifiers down through array types.
2204
2205  // If there are no new qualifiers to push down, stop here.
2206  if (!Quals.hasQualifiers())
2207    return CanQualType::CreateUnsafe(CanType);
2208
2209  // If the type qualifiers are on an array type, get the canonical
2210  // type of the array with the qualifiers applied to the element
2211  // type.
2212  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2213  if (!AT)
2214    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2215
2216  // Get the canonical version of the element with the extra qualifiers on it.
2217  // This can recursively sink qualifiers through multiple levels of arrays.
2218  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2219  NewEltTy = getCanonicalType(NewEltTy);
2220
2221  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2222    return CanQualType::CreateUnsafe(
2223             getConstantArrayType(NewEltTy, CAT->getSize(),
2224                                  CAT->getSizeModifier(),
2225                                  CAT->getIndexTypeCVRQualifiers()));
2226  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2227    return CanQualType::CreateUnsafe(
2228             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2229                                    IAT->getIndexTypeCVRQualifiers()));
2230
2231  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2232    return CanQualType::CreateUnsafe(
2233             getDependentSizedArrayType(NewEltTy,
2234                                        DSAT->getSizeExpr() ?
2235                                          DSAT->getSizeExpr()->Retain() : 0,
2236                                        DSAT->getSizeModifier(),
2237                                        DSAT->getIndexTypeCVRQualifiers(),
2238                                        DSAT->getBracketsRange()));
2239
2240  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2241  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2242                                                        VAT->getSizeExpr() ?
2243                                              VAT->getSizeExpr()->Retain() : 0,
2244                                                        VAT->getSizeModifier(),
2245                                              VAT->getIndexTypeCVRQualifiers(),
2246                                                     VAT->getBracketsRange()));
2247}
2248
2249TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2250  // If this template name refers to a template, the canonical
2251  // template name merely stores the template itself.
2252  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2253    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2254
2255  // If this template name refers to a set of overloaded function templates,
2256  /// the canonical template name merely stores the set of function templates.
2257  if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2258    OverloadedFunctionDecl *CanonOvl = 0;
2259    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2260                                                FEnd = Ovl->function_end();
2261         F != FEnd; ++F) {
2262      Decl *Canon = F->get()->getCanonicalDecl();
2263      if (CanonOvl || Canon != F->get()) {
2264        if (!CanonOvl)
2265          CanonOvl = OverloadedFunctionDecl::Create(*this,
2266                                                    Ovl->getDeclContext(),
2267                                                    Ovl->getDeclName());
2268
2269        CanonOvl->addOverload(
2270                    AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2271      }
2272    }
2273
2274    return TemplateName(CanonOvl? CanonOvl : Ovl);
2275  }
2276
2277  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2278  assert(DTN && "Non-dependent template names must refer to template decls.");
2279  return DTN->CanonicalTemplateName;
2280}
2281
2282TemplateArgument
2283ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2284  switch (Arg.getKind()) {
2285    case TemplateArgument::Null:
2286      return Arg;
2287
2288    case TemplateArgument::Expression:
2289      // FIXME: Build canonical expression?
2290      return Arg;
2291
2292    case TemplateArgument::Declaration:
2293      return TemplateArgument(SourceLocation(),
2294                              Arg.getAsDecl()->getCanonicalDecl());
2295
2296    case TemplateArgument::Integral:
2297      return TemplateArgument(SourceLocation(),
2298                              *Arg.getAsIntegral(),
2299                              getCanonicalType(Arg.getIntegralType()));
2300
2301    case TemplateArgument::Type:
2302      return TemplateArgument(SourceLocation(),
2303                              getCanonicalType(Arg.getAsType()));
2304
2305    case TemplateArgument::Pack: {
2306      // FIXME: Allocate in ASTContext
2307      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2308      unsigned Idx = 0;
2309      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2310                                        AEnd = Arg.pack_end();
2311           A != AEnd; (void)++A, ++Idx)
2312        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2313
2314      TemplateArgument Result;
2315      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2316      return Result;
2317    }
2318  }
2319
2320  // Silence GCC warning
2321  assert(false && "Unhandled template argument kind");
2322  return TemplateArgument();
2323}
2324
2325NestedNameSpecifier *
2326ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2327  if (!NNS)
2328    return 0;
2329
2330  switch (NNS->getKind()) {
2331  case NestedNameSpecifier::Identifier:
2332    // Canonicalize the prefix but keep the identifier the same.
2333    return NestedNameSpecifier::Create(*this,
2334                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2335                                       NNS->getAsIdentifier());
2336
2337  case NestedNameSpecifier::Namespace:
2338    // A namespace is canonical; build a nested-name-specifier with
2339    // this namespace and no prefix.
2340    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2341
2342  case NestedNameSpecifier::TypeSpec:
2343  case NestedNameSpecifier::TypeSpecWithTemplate: {
2344    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2345    return NestedNameSpecifier::Create(*this, 0,
2346                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2347                                       T.getTypePtr());
2348  }
2349
2350  case NestedNameSpecifier::Global:
2351    // The global specifier is canonical and unique.
2352    return NNS;
2353  }
2354
2355  // Required to silence a GCC warning
2356  return 0;
2357}
2358
2359
2360const ArrayType *ASTContext::getAsArrayType(QualType T) {
2361  // Handle the non-qualified case efficiently.
2362  if (!T.hasQualifiers()) {
2363    // Handle the common positive case fast.
2364    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2365      return AT;
2366  }
2367
2368  // Handle the common negative case fast.
2369  QualType CType = T->getCanonicalTypeInternal();
2370  if (!isa<ArrayType>(CType))
2371    return 0;
2372
2373  // Apply any qualifiers from the array type to the element type.  This
2374  // implements C99 6.7.3p8: "If the specification of an array type includes
2375  // any type qualifiers, the element type is so qualified, not the array type."
2376
2377  // If we get here, we either have type qualifiers on the type, or we have
2378  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2379  // we must propagate them down into the element type.
2380
2381  QualifierCollector Qs;
2382  const Type *Ty = Qs.strip(T.getDesugaredType());
2383
2384  // If we have a simple case, just return now.
2385  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2386  if (ATy == 0 || Qs.empty())
2387    return ATy;
2388
2389  // Otherwise, we have an array and we have qualifiers on it.  Push the
2390  // qualifiers into the array element type and return a new array type.
2391  // Get the canonical version of the element with the extra qualifiers on it.
2392  // This can recursively sink qualifiers through multiple levels of arrays.
2393  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2394
2395  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2396    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2397                                                CAT->getSizeModifier(),
2398                                           CAT->getIndexTypeCVRQualifiers()));
2399  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2400    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2401                                                  IAT->getSizeModifier(),
2402                                           IAT->getIndexTypeCVRQualifiers()));
2403
2404  if (const DependentSizedArrayType *DSAT
2405        = dyn_cast<DependentSizedArrayType>(ATy))
2406    return cast<ArrayType>(
2407                     getDependentSizedArrayType(NewEltTy,
2408                                                DSAT->getSizeExpr() ?
2409                                              DSAT->getSizeExpr()->Retain() : 0,
2410                                                DSAT->getSizeModifier(),
2411                                              DSAT->getIndexTypeCVRQualifiers(),
2412                                                DSAT->getBracketsRange()));
2413
2414  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2415  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2416                                              VAT->getSizeExpr() ?
2417                                              VAT->getSizeExpr()->Retain() : 0,
2418                                              VAT->getSizeModifier(),
2419                                              VAT->getIndexTypeCVRQualifiers(),
2420                                              VAT->getBracketsRange()));
2421}
2422
2423
2424/// getArrayDecayedType - Return the properly qualified result of decaying the
2425/// specified array type to a pointer.  This operation is non-trivial when
2426/// handling typedefs etc.  The canonical type of "T" must be an array type,
2427/// this returns a pointer to a properly qualified element of the array.
2428///
2429/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2430QualType ASTContext::getArrayDecayedType(QualType Ty) {
2431  // Get the element type with 'getAsArrayType' so that we don't lose any
2432  // typedefs in the element type of the array.  This also handles propagation
2433  // of type qualifiers from the array type into the element type if present
2434  // (C99 6.7.3p8).
2435  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2436  assert(PrettyArrayType && "Not an array type!");
2437
2438  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2439
2440  // int x[restrict 4] ->  int *restrict
2441  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2442}
2443
2444QualType ASTContext::getBaseElementType(QualType QT) {
2445  QualifierCollector Qs;
2446  while (true) {
2447    const Type *UT = Qs.strip(QT);
2448    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2449      QT = AT->getElementType();
2450    } else {
2451      return Qs.apply(QT);
2452    }
2453  }
2454}
2455
2456QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2457  QualType ElemTy = AT->getElementType();
2458
2459  if (const ArrayType *AT = getAsArrayType(ElemTy))
2460    return getBaseElementType(AT);
2461
2462  return ElemTy;
2463}
2464
2465/// getConstantArrayElementCount - Returns number of constant array elements.
2466uint64_t
2467ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2468  uint64_t ElementCount = 1;
2469  do {
2470    ElementCount *= CA->getSize().getZExtValue();
2471    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2472  } while (CA);
2473  return ElementCount;
2474}
2475
2476/// getFloatingRank - Return a relative rank for floating point types.
2477/// This routine will assert if passed a built-in type that isn't a float.
2478static FloatingRank getFloatingRank(QualType T) {
2479  if (const ComplexType *CT = T->getAs<ComplexType>())
2480    return getFloatingRank(CT->getElementType());
2481
2482  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2483  switch (T->getAs<BuiltinType>()->getKind()) {
2484  default: assert(0 && "getFloatingRank(): not a floating type");
2485  case BuiltinType::Float:      return FloatRank;
2486  case BuiltinType::Double:     return DoubleRank;
2487  case BuiltinType::LongDouble: return LongDoubleRank;
2488  }
2489}
2490
2491/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2492/// point or a complex type (based on typeDomain/typeSize).
2493/// 'typeDomain' is a real floating point or complex type.
2494/// 'typeSize' is a real floating point or complex type.
2495QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2496                                                       QualType Domain) const {
2497  FloatingRank EltRank = getFloatingRank(Size);
2498  if (Domain->isComplexType()) {
2499    switch (EltRank) {
2500    default: assert(0 && "getFloatingRank(): illegal value for rank");
2501    case FloatRank:      return FloatComplexTy;
2502    case DoubleRank:     return DoubleComplexTy;
2503    case LongDoubleRank: return LongDoubleComplexTy;
2504    }
2505  }
2506
2507  assert(Domain->isRealFloatingType() && "Unknown domain!");
2508  switch (EltRank) {
2509  default: assert(0 && "getFloatingRank(): illegal value for rank");
2510  case FloatRank:      return FloatTy;
2511  case DoubleRank:     return DoubleTy;
2512  case LongDoubleRank: return LongDoubleTy;
2513  }
2514}
2515
2516/// getFloatingTypeOrder - Compare the rank of the two specified floating
2517/// point types, ignoring the domain of the type (i.e. 'double' ==
2518/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2519/// LHS < RHS, return -1.
2520int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2521  FloatingRank LHSR = getFloatingRank(LHS);
2522  FloatingRank RHSR = getFloatingRank(RHS);
2523
2524  if (LHSR == RHSR)
2525    return 0;
2526  if (LHSR > RHSR)
2527    return 1;
2528  return -1;
2529}
2530
2531/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2532/// routine will assert if passed a built-in type that isn't an integer or enum,
2533/// or if it is not canonicalized.
2534unsigned ASTContext::getIntegerRank(Type *T) {
2535  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2536  if (EnumType* ET = dyn_cast<EnumType>(T))
2537    T = ET->getDecl()->getIntegerType().getTypePtr();
2538
2539  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2540    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2541
2542  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2543    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2544
2545  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2546    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2547
2548  // There are two things which impact the integer rank: the width, and
2549  // the ordering of builtins.  The builtin ordering is encoded in the
2550  // bottom three bits; the width is encoded in the bits above that.
2551  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2552    return FWIT->getWidth() << 3;
2553
2554  switch (cast<BuiltinType>(T)->getKind()) {
2555  default: assert(0 && "getIntegerRank(): not a built-in integer");
2556  case BuiltinType::Bool:
2557    return 1 + (getIntWidth(BoolTy) << 3);
2558  case BuiltinType::Char_S:
2559  case BuiltinType::Char_U:
2560  case BuiltinType::SChar:
2561  case BuiltinType::UChar:
2562    return 2 + (getIntWidth(CharTy) << 3);
2563  case BuiltinType::Short:
2564  case BuiltinType::UShort:
2565    return 3 + (getIntWidth(ShortTy) << 3);
2566  case BuiltinType::Int:
2567  case BuiltinType::UInt:
2568    return 4 + (getIntWidth(IntTy) << 3);
2569  case BuiltinType::Long:
2570  case BuiltinType::ULong:
2571    return 5 + (getIntWidth(LongTy) << 3);
2572  case BuiltinType::LongLong:
2573  case BuiltinType::ULongLong:
2574    return 6 + (getIntWidth(LongLongTy) << 3);
2575  case BuiltinType::Int128:
2576  case BuiltinType::UInt128:
2577    return 7 + (getIntWidth(Int128Ty) << 3);
2578  }
2579}
2580
2581/// \brief Whether this is a promotable bitfield reference according
2582/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2583///
2584/// \returns the type this bit-field will promote to, or NULL if no
2585/// promotion occurs.
2586QualType ASTContext::isPromotableBitField(Expr *E) {
2587  FieldDecl *Field = E->getBitField();
2588  if (!Field)
2589    return QualType();
2590
2591  QualType FT = Field->getType();
2592
2593  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2594  uint64_t BitWidth = BitWidthAP.getZExtValue();
2595  uint64_t IntSize = getTypeSize(IntTy);
2596  // GCC extension compatibility: if the bit-field size is less than or equal
2597  // to the size of int, it gets promoted no matter what its type is.
2598  // For instance, unsigned long bf : 4 gets promoted to signed int.
2599  if (BitWidth < IntSize)
2600    return IntTy;
2601
2602  if (BitWidth == IntSize)
2603    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2604
2605  // Types bigger than int are not subject to promotions, and therefore act
2606  // like the base type.
2607  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2608  // is ridiculous.
2609  return QualType();
2610}
2611
2612/// getPromotedIntegerType - Returns the type that Promotable will
2613/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2614/// integer type.
2615QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2616  assert(!Promotable.isNull());
2617  assert(Promotable->isPromotableIntegerType());
2618  if (Promotable->isSignedIntegerType())
2619    return IntTy;
2620  uint64_t PromotableSize = getTypeSize(Promotable);
2621  uint64_t IntSize = getTypeSize(IntTy);
2622  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2623  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2624}
2625
2626/// getIntegerTypeOrder - Returns the highest ranked integer type:
2627/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2628/// LHS < RHS, return -1.
2629int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2630  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2631  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2632  if (LHSC == RHSC) return 0;
2633
2634  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2635  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2636
2637  unsigned LHSRank = getIntegerRank(LHSC);
2638  unsigned RHSRank = getIntegerRank(RHSC);
2639
2640  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2641    if (LHSRank == RHSRank) return 0;
2642    return LHSRank > RHSRank ? 1 : -1;
2643  }
2644
2645  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2646  if (LHSUnsigned) {
2647    // If the unsigned [LHS] type is larger, return it.
2648    if (LHSRank >= RHSRank)
2649      return 1;
2650
2651    // If the signed type can represent all values of the unsigned type, it
2652    // wins.  Because we are dealing with 2's complement and types that are
2653    // powers of two larger than each other, this is always safe.
2654    return -1;
2655  }
2656
2657  // If the unsigned [RHS] type is larger, return it.
2658  if (RHSRank >= LHSRank)
2659    return -1;
2660
2661  // If the signed type can represent all values of the unsigned type, it
2662  // wins.  Because we are dealing with 2's complement and types that are
2663  // powers of two larger than each other, this is always safe.
2664  return 1;
2665}
2666
2667// getCFConstantStringType - Return the type used for constant CFStrings.
2668QualType ASTContext::getCFConstantStringType() {
2669  if (!CFConstantStringTypeDecl) {
2670    CFConstantStringTypeDecl =
2671      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2672                         &Idents.get("NSConstantString"));
2673    QualType FieldTypes[4];
2674
2675    // const int *isa;
2676    FieldTypes[0] = getPointerType(IntTy.withConst());
2677    // int flags;
2678    FieldTypes[1] = IntTy;
2679    // const char *str;
2680    FieldTypes[2] = getPointerType(CharTy.withConst());
2681    // long length;
2682    FieldTypes[3] = LongTy;
2683
2684    // Create fields
2685    for (unsigned i = 0; i < 4; ++i) {
2686      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2687                                           SourceLocation(), 0,
2688                                           FieldTypes[i], /*DInfo=*/0,
2689                                           /*BitWidth=*/0,
2690                                           /*Mutable=*/false);
2691      CFConstantStringTypeDecl->addDecl(Field);
2692    }
2693
2694    CFConstantStringTypeDecl->completeDefinition(*this);
2695  }
2696
2697  return getTagDeclType(CFConstantStringTypeDecl);
2698}
2699
2700void ASTContext::setCFConstantStringType(QualType T) {
2701  const RecordType *Rec = T->getAs<RecordType>();
2702  assert(Rec && "Invalid CFConstantStringType");
2703  CFConstantStringTypeDecl = Rec->getDecl();
2704}
2705
2706QualType ASTContext::getObjCFastEnumerationStateType() {
2707  if (!ObjCFastEnumerationStateTypeDecl) {
2708    ObjCFastEnumerationStateTypeDecl =
2709      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2710                         &Idents.get("__objcFastEnumerationState"));
2711
2712    QualType FieldTypes[] = {
2713      UnsignedLongTy,
2714      getPointerType(ObjCIdTypedefType),
2715      getPointerType(UnsignedLongTy),
2716      getConstantArrayType(UnsignedLongTy,
2717                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2718    };
2719
2720    for (size_t i = 0; i < 4; ++i) {
2721      FieldDecl *Field = FieldDecl::Create(*this,
2722                                           ObjCFastEnumerationStateTypeDecl,
2723                                           SourceLocation(), 0,
2724                                           FieldTypes[i], /*DInfo=*/0,
2725                                           /*BitWidth=*/0,
2726                                           /*Mutable=*/false);
2727      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2728    }
2729
2730    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2731  }
2732
2733  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2734}
2735
2736QualType ASTContext::getBlockDescriptorType() {
2737  if (BlockDescriptorType)
2738    return getTagDeclType(BlockDescriptorType);
2739
2740  RecordDecl *T;
2741  // FIXME: Needs the FlagAppleBlock bit.
2742  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2743                         &Idents.get("__block_descriptor"));
2744
2745  QualType FieldTypes[] = {
2746    UnsignedLongTy,
2747    UnsignedLongTy,
2748  };
2749
2750  const char *FieldNames[] = {
2751    "reserved",
2752    "Size"
2753  };
2754
2755  for (size_t i = 0; i < 2; ++i) {
2756    FieldDecl *Field = FieldDecl::Create(*this,
2757                                         T,
2758                                         SourceLocation(),
2759                                         &Idents.get(FieldNames[i]),
2760                                         FieldTypes[i], /*DInfo=*/0,
2761                                         /*BitWidth=*/0,
2762                                         /*Mutable=*/false);
2763    T->addDecl(Field);
2764  }
2765
2766  T->completeDefinition(*this);
2767
2768  BlockDescriptorType = T;
2769
2770  return getTagDeclType(BlockDescriptorType);
2771}
2772
2773void ASTContext::setBlockDescriptorType(QualType T) {
2774  const RecordType *Rec = T->getAs<RecordType>();
2775  assert(Rec && "Invalid BlockDescriptorType");
2776  BlockDescriptorType = Rec->getDecl();
2777}
2778
2779QualType ASTContext::getBlockDescriptorExtendedType() {
2780  if (BlockDescriptorExtendedType)
2781    return getTagDeclType(BlockDescriptorExtendedType);
2782
2783  RecordDecl *T;
2784  // FIXME: Needs the FlagAppleBlock bit.
2785  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2786                         &Idents.get("__block_descriptor_withcopydispose"));
2787
2788  QualType FieldTypes[] = {
2789    UnsignedLongTy,
2790    UnsignedLongTy,
2791    getPointerType(VoidPtrTy),
2792    getPointerType(VoidPtrTy)
2793  };
2794
2795  const char *FieldNames[] = {
2796    "reserved",
2797    "Size",
2798    "CopyFuncPtr",
2799    "DestroyFuncPtr"
2800  };
2801
2802  for (size_t i = 0; i < 4; ++i) {
2803    FieldDecl *Field = FieldDecl::Create(*this,
2804                                         T,
2805                                         SourceLocation(),
2806                                         &Idents.get(FieldNames[i]),
2807                                         FieldTypes[i], /*DInfo=*/0,
2808                                         /*BitWidth=*/0,
2809                                         /*Mutable=*/false);
2810    T->addDecl(Field);
2811  }
2812
2813  T->completeDefinition(*this);
2814
2815  BlockDescriptorExtendedType = T;
2816
2817  return getTagDeclType(BlockDescriptorExtendedType);
2818}
2819
2820void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2821  const RecordType *Rec = T->getAs<RecordType>();
2822  assert(Rec && "Invalid BlockDescriptorType");
2823  BlockDescriptorExtendedType = Rec->getDecl();
2824}
2825
2826bool ASTContext::BlockRequiresCopying(QualType Ty) {
2827  if (Ty->isBlockPointerType())
2828    return true;
2829  if (isObjCNSObjectType(Ty))
2830    return true;
2831  if (Ty->isObjCObjectPointerType())
2832    return true;
2833  return false;
2834}
2835
2836QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2837  //  type = struct __Block_byref_1_X {
2838  //    void *__isa;
2839  //    struct __Block_byref_1_X *__forwarding;
2840  //    unsigned int __flags;
2841  //    unsigned int __size;
2842  //    void *__copy_helper;		// as needed
2843  //    void *__destroy_help		// as needed
2844  //    int X;
2845  //  } *
2846
2847  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2848
2849  // FIXME: Move up
2850  static int UniqueBlockByRefTypeID = 0;
2851  char Name[36];
2852  sprintf(Name, "__Block_byref_%d_%s", ++UniqueBlockByRefTypeID, DeclName);
2853  RecordDecl *T;
2854  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2855                         &Idents.get(Name));
2856  T->startDefinition();
2857  QualType Int32Ty = IntTy;
2858  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2859  QualType FieldTypes[] = {
2860    getPointerType(VoidPtrTy),
2861    getPointerType(getTagDeclType(T)),
2862    Int32Ty,
2863    Int32Ty,
2864    getPointerType(VoidPtrTy),
2865    getPointerType(VoidPtrTy),
2866    Ty
2867  };
2868
2869  const char *FieldNames[] = {
2870    "__isa",
2871    "__forwarding",
2872    "__flags",
2873    "__size",
2874    "__copy_helper",
2875    "__destroy_helper",
2876    DeclName,
2877  };
2878
2879  for (size_t i = 0; i < 7; ++i) {
2880    if (!HasCopyAndDispose && i >=4 && i <= 5)
2881      continue;
2882    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2883                                         &Idents.get(FieldNames[i]),
2884                                         FieldTypes[i], /*DInfo=*/0,
2885                                         /*BitWidth=*/0, /*Mutable=*/false);
2886    T->addDecl(Field);
2887  }
2888
2889  T->completeDefinition(*this);
2890
2891  return getPointerType(getTagDeclType(T));
2892}
2893
2894
2895QualType ASTContext::getBlockParmType(
2896  bool BlockHasCopyDispose,
2897  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
2898  // FIXME: Move up
2899  static int UniqueBlockParmTypeID = 0;
2900  char Name[36];
2901  sprintf(Name, "__block_literal_%u", ++UniqueBlockParmTypeID);
2902  RecordDecl *T;
2903  T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2904                         &Idents.get(Name));
2905  QualType FieldTypes[] = {
2906    getPointerType(VoidPtrTy),
2907    IntTy,
2908    IntTy,
2909    getPointerType(VoidPtrTy),
2910    (BlockHasCopyDispose ?
2911     getPointerType(getBlockDescriptorExtendedType()) :
2912     getPointerType(getBlockDescriptorType()))
2913  };
2914
2915  const char *FieldNames[] = {
2916    "__isa",
2917    "__flags",
2918    "__reserved",
2919    "__FuncPtr",
2920    "__descriptor"
2921  };
2922
2923  for (size_t i = 0; i < 5; ++i) {
2924    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2925                                         &Idents.get(FieldNames[i]),
2926                                         FieldTypes[i], /*DInfo=*/0,
2927                                         /*BitWidth=*/0, /*Mutable=*/false);
2928    T->addDecl(Field);
2929  }
2930
2931  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
2932    const Expr *E = BlockDeclRefDecls[i];
2933    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2934    clang::IdentifierInfo *Name = 0;
2935    if (BDRE) {
2936      const ValueDecl *D = BDRE->getDecl();
2937      Name = &Idents.get(D->getName());
2938    }
2939    QualType FieldType = E->getType();
2940
2941    if (BDRE && BDRE->isByRef())
2942      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
2943                                 FieldType);
2944
2945    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2946                                         Name, FieldType, /*DInfo=*/0,
2947                                         /*BitWidth=*/0, /*Mutable=*/false);
2948    T->addDecl(Field);
2949  }
2950
2951  T->completeDefinition(*this);
2952
2953  return getPointerType(getTagDeclType(T));
2954}
2955
2956void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2957  const RecordType *Rec = T->getAs<RecordType>();
2958  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2959  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2960}
2961
2962// This returns true if a type has been typedefed to BOOL:
2963// typedef <type> BOOL;
2964static bool isTypeTypedefedAsBOOL(QualType T) {
2965  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2966    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2967      return II->isStr("BOOL");
2968
2969  return false;
2970}
2971
2972/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2973/// purpose.
2974int ASTContext::getObjCEncodingTypeSize(QualType type) {
2975  uint64_t sz = getTypeSize(type);
2976
2977  // Make all integer and enum types at least as large as an int
2978  if (sz > 0 && type->isIntegralType())
2979    sz = std::max(sz, getTypeSize(IntTy));
2980  // Treat arrays as pointers, since that's how they're passed in.
2981  else if (type->isArrayType())
2982    sz = getTypeSize(VoidPtrTy);
2983  return sz / getTypeSize(CharTy);
2984}
2985
2986/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2987/// declaration.
2988void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2989                                              std::string& S) {
2990  // FIXME: This is not very efficient.
2991  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2992  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2993  // Encode result type.
2994  getObjCEncodingForType(Decl->getResultType(), S);
2995  // Compute size of all parameters.
2996  // Start with computing size of a pointer in number of bytes.
2997  // FIXME: There might(should) be a better way of doing this computation!
2998  SourceLocation Loc;
2999  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3000  // The first two arguments (self and _cmd) are pointers; account for
3001  // their size.
3002  int ParmOffset = 2 * PtrSize;
3003  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3004       E = Decl->param_end(); PI != E; ++PI) {
3005    QualType PType = (*PI)->getType();
3006    int sz = getObjCEncodingTypeSize(PType);
3007    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
3008    ParmOffset += sz;
3009  }
3010  S += llvm::utostr(ParmOffset);
3011  S += "@0:";
3012  S += llvm::utostr(PtrSize);
3013
3014  // Argument types.
3015  ParmOffset = 2 * PtrSize;
3016  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3017       E = Decl->param_end(); PI != E; ++PI) {
3018    ParmVarDecl *PVDecl = *PI;
3019    QualType PType = PVDecl->getOriginalType();
3020    if (const ArrayType *AT =
3021          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3022      // Use array's original type only if it has known number of
3023      // elements.
3024      if (!isa<ConstantArrayType>(AT))
3025        PType = PVDecl->getType();
3026    } else if (PType->isFunctionType())
3027      PType = PVDecl->getType();
3028    // Process argument qualifiers for user supplied arguments; such as,
3029    // 'in', 'inout', etc.
3030    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3031    getObjCEncodingForType(PType, S);
3032    S += llvm::utostr(ParmOffset);
3033    ParmOffset += getObjCEncodingTypeSize(PType);
3034  }
3035}
3036
3037/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3038/// property declaration. If non-NULL, Container must be either an
3039/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3040/// NULL when getting encodings for protocol properties.
3041/// Property attributes are stored as a comma-delimited C string. The simple
3042/// attributes readonly and bycopy are encoded as single characters. The
3043/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3044/// encoded as single characters, followed by an identifier. Property types
3045/// are also encoded as a parametrized attribute. The characters used to encode
3046/// these attributes are defined by the following enumeration:
3047/// @code
3048/// enum PropertyAttributes {
3049/// kPropertyReadOnly = 'R',   // property is read-only.
3050/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3051/// kPropertyByref = '&',  // property is a reference to the value last assigned
3052/// kPropertyDynamic = 'D',    // property is dynamic
3053/// kPropertyGetter = 'G',     // followed by getter selector name
3054/// kPropertySetter = 'S',     // followed by setter selector name
3055/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3056/// kPropertyType = 't'              // followed by old-style type encoding.
3057/// kPropertyWeak = 'W'              // 'weak' property
3058/// kPropertyStrong = 'P'            // property GC'able
3059/// kPropertyNonAtomic = 'N'         // property non-atomic
3060/// };
3061/// @endcode
3062void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3063                                                const Decl *Container,
3064                                                std::string& S) {
3065  // Collect information from the property implementation decl(s).
3066  bool Dynamic = false;
3067  ObjCPropertyImplDecl *SynthesizePID = 0;
3068
3069  // FIXME: Duplicated code due to poor abstraction.
3070  if (Container) {
3071    if (const ObjCCategoryImplDecl *CID =
3072        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3073      for (ObjCCategoryImplDecl::propimpl_iterator
3074             i = CID->propimpl_begin(), e = CID->propimpl_end();
3075           i != e; ++i) {
3076        ObjCPropertyImplDecl *PID = *i;
3077        if (PID->getPropertyDecl() == PD) {
3078          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3079            Dynamic = true;
3080          } else {
3081            SynthesizePID = PID;
3082          }
3083        }
3084      }
3085    } else {
3086      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3087      for (ObjCCategoryImplDecl::propimpl_iterator
3088             i = OID->propimpl_begin(), e = OID->propimpl_end();
3089           i != e; ++i) {
3090        ObjCPropertyImplDecl *PID = *i;
3091        if (PID->getPropertyDecl() == PD) {
3092          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3093            Dynamic = true;
3094          } else {
3095            SynthesizePID = PID;
3096          }
3097        }
3098      }
3099    }
3100  }
3101
3102  // FIXME: This is not very efficient.
3103  S = "T";
3104
3105  // Encode result type.
3106  // GCC has some special rules regarding encoding of properties which
3107  // closely resembles encoding of ivars.
3108  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3109                             true /* outermost type */,
3110                             true /* encoding for property */);
3111
3112  if (PD->isReadOnly()) {
3113    S += ",R";
3114  } else {
3115    switch (PD->getSetterKind()) {
3116    case ObjCPropertyDecl::Assign: break;
3117    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3118    case ObjCPropertyDecl::Retain: S += ",&"; break;
3119    }
3120  }
3121
3122  // It really isn't clear at all what this means, since properties
3123  // are "dynamic by default".
3124  if (Dynamic)
3125    S += ",D";
3126
3127  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3128    S += ",N";
3129
3130  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3131    S += ",G";
3132    S += PD->getGetterName().getAsString();
3133  }
3134
3135  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3136    S += ",S";
3137    S += PD->getSetterName().getAsString();
3138  }
3139
3140  if (SynthesizePID) {
3141    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3142    S += ",V";
3143    S += OID->getNameAsString();
3144  }
3145
3146  // FIXME: OBJCGC: weak & strong
3147}
3148
3149/// getLegacyIntegralTypeEncoding -
3150/// Another legacy compatibility encoding: 32-bit longs are encoded as
3151/// 'l' or 'L' , but not always.  For typedefs, we need to use
3152/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3153///
3154void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3155  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3156    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3157      if (BT->getKind() == BuiltinType::ULong &&
3158          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3159        PointeeTy = UnsignedIntTy;
3160      else
3161        if (BT->getKind() == BuiltinType::Long &&
3162            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3163          PointeeTy = IntTy;
3164    }
3165  }
3166}
3167
3168void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3169                                        const FieldDecl *Field) {
3170  // We follow the behavior of gcc, expanding structures which are
3171  // directly pointed to, and expanding embedded structures. Note that
3172  // these rules are sufficient to prevent recursive encoding of the
3173  // same type.
3174  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3175                             true /* outermost type */);
3176}
3177
3178static void EncodeBitField(const ASTContext *Context, std::string& S,
3179                           const FieldDecl *FD) {
3180  const Expr *E = FD->getBitWidth();
3181  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3182  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3183  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3184  S += 'b';
3185  S += llvm::utostr(N);
3186}
3187
3188// FIXME: Use SmallString for accumulating string.
3189void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3190                                            bool ExpandPointedToStructures,
3191                                            bool ExpandStructures,
3192                                            const FieldDecl *FD,
3193                                            bool OutermostType,
3194                                            bool EncodingProperty) {
3195  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3196    if (FD && FD->isBitField())
3197      return EncodeBitField(this, S, FD);
3198    char encoding;
3199    switch (BT->getKind()) {
3200    default: assert(0 && "Unhandled builtin type kind");
3201    case BuiltinType::Void:       encoding = 'v'; break;
3202    case BuiltinType::Bool:       encoding = 'B'; break;
3203    case BuiltinType::Char_U:
3204    case BuiltinType::UChar:      encoding = 'C'; break;
3205    case BuiltinType::UShort:     encoding = 'S'; break;
3206    case BuiltinType::UInt:       encoding = 'I'; break;
3207    case BuiltinType::ULong:
3208        encoding =
3209          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3210        break;
3211    case BuiltinType::UInt128:    encoding = 'T'; break;
3212    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3213    case BuiltinType::Char_S:
3214    case BuiltinType::SChar:      encoding = 'c'; break;
3215    case BuiltinType::Short:      encoding = 's'; break;
3216    case BuiltinType::Int:        encoding = 'i'; break;
3217    case BuiltinType::Long:
3218      encoding =
3219        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3220      break;
3221    case BuiltinType::LongLong:   encoding = 'q'; break;
3222    case BuiltinType::Int128:     encoding = 't'; break;
3223    case BuiltinType::Float:      encoding = 'f'; break;
3224    case BuiltinType::Double:     encoding = 'd'; break;
3225    case BuiltinType::LongDouble: encoding = 'd'; break;
3226    }
3227
3228    S += encoding;
3229    return;
3230  }
3231
3232  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3233    S += 'j';
3234    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3235                               false);
3236    return;
3237  }
3238
3239  if (const PointerType *PT = T->getAs<PointerType>()) {
3240    QualType PointeeTy = PT->getPointeeType();
3241    bool isReadOnly = false;
3242    // For historical/compatibility reasons, the read-only qualifier of the
3243    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3244    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3245    // Also, do not emit the 'r' for anything but the outermost type!
3246    if (isa<TypedefType>(T.getTypePtr())) {
3247      if (OutermostType && T.isConstQualified()) {
3248        isReadOnly = true;
3249        S += 'r';
3250      }
3251    } else if (OutermostType) {
3252      QualType P = PointeeTy;
3253      while (P->getAs<PointerType>())
3254        P = P->getAs<PointerType>()->getPointeeType();
3255      if (P.isConstQualified()) {
3256        isReadOnly = true;
3257        S += 'r';
3258      }
3259    }
3260    if (isReadOnly) {
3261      // Another legacy compatibility encoding. Some ObjC qualifier and type
3262      // combinations need to be rearranged.
3263      // Rewrite "in const" from "nr" to "rn"
3264      const char * s = S.c_str();
3265      int len = S.length();
3266      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3267        std::string replace = "rn";
3268        S.replace(S.end()-2, S.end(), replace);
3269      }
3270    }
3271    if (isObjCSelType(PointeeTy)) {
3272      S += ':';
3273      return;
3274    }
3275
3276    if (PointeeTy->isCharType()) {
3277      // char pointer types should be encoded as '*' unless it is a
3278      // type that has been typedef'd to 'BOOL'.
3279      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3280        S += '*';
3281        return;
3282      }
3283    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3284      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3285      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3286        S += '#';
3287        return;
3288      }
3289      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3290      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3291        S += '@';
3292        return;
3293      }
3294      // fall through...
3295    }
3296    S += '^';
3297    getLegacyIntegralTypeEncoding(PointeeTy);
3298
3299    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3300                               NULL);
3301    return;
3302  }
3303
3304  if (const ArrayType *AT =
3305      // Ignore type qualifiers etc.
3306        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3307    if (isa<IncompleteArrayType>(AT)) {
3308      // Incomplete arrays are encoded as a pointer to the array element.
3309      S += '^';
3310
3311      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3312                                 false, ExpandStructures, FD);
3313    } else {
3314      S += '[';
3315
3316      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3317        S += llvm::utostr(CAT->getSize().getZExtValue());
3318      else {
3319        //Variable length arrays are encoded as a regular array with 0 elements.
3320        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3321        S += '0';
3322      }
3323
3324      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3325                                 false, ExpandStructures, FD);
3326      S += ']';
3327    }
3328    return;
3329  }
3330
3331  if (T->getAs<FunctionType>()) {
3332    S += '?';
3333    return;
3334  }
3335
3336  if (const RecordType *RTy = T->getAs<RecordType>()) {
3337    RecordDecl *RDecl = RTy->getDecl();
3338    S += RDecl->isUnion() ? '(' : '{';
3339    // Anonymous structures print as '?'
3340    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3341      S += II->getName();
3342    } else {
3343      S += '?';
3344    }
3345    if (ExpandStructures) {
3346      S += '=';
3347      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3348                                   FieldEnd = RDecl->field_end();
3349           Field != FieldEnd; ++Field) {
3350        if (FD) {
3351          S += '"';
3352          S += Field->getNameAsString();
3353          S += '"';
3354        }
3355
3356        // Special case bit-fields.
3357        if (Field->isBitField()) {
3358          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3359                                     (*Field));
3360        } else {
3361          QualType qt = Field->getType();
3362          getLegacyIntegralTypeEncoding(qt);
3363          getObjCEncodingForTypeImpl(qt, S, false, true,
3364                                     FD);
3365        }
3366      }
3367    }
3368    S += RDecl->isUnion() ? ')' : '}';
3369    return;
3370  }
3371
3372  if (T->isEnumeralType()) {
3373    if (FD && FD->isBitField())
3374      EncodeBitField(this, S, FD);
3375    else
3376      S += 'i';
3377    return;
3378  }
3379
3380  if (T->isBlockPointerType()) {
3381    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3382    return;
3383  }
3384
3385  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3386    // @encode(class_name)
3387    ObjCInterfaceDecl *OI = OIT->getDecl();
3388    S += '{';
3389    const IdentifierInfo *II = OI->getIdentifier();
3390    S += II->getName();
3391    S += '=';
3392    llvm::SmallVector<FieldDecl*, 32> RecFields;
3393    CollectObjCIvars(OI, RecFields);
3394    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3395      if (RecFields[i]->isBitField())
3396        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3397                                   RecFields[i]);
3398      else
3399        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3400                                   FD);
3401    }
3402    S += '}';
3403    return;
3404  }
3405
3406  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3407    if (OPT->isObjCIdType()) {
3408      S += '@';
3409      return;
3410    }
3411
3412    if (OPT->isObjCClassType()) {
3413      S += '#';
3414      return;
3415    }
3416
3417    if (OPT->isObjCQualifiedIdType()) {
3418      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3419                                 ExpandPointedToStructures,
3420                                 ExpandStructures, FD);
3421      if (FD || EncodingProperty) {
3422        // Note that we do extended encoding of protocol qualifer list
3423        // Only when doing ivar or property encoding.
3424        S += '"';
3425        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3426             E = OPT->qual_end(); I != E; ++I) {
3427          S += '<';
3428          S += (*I)->getNameAsString();
3429          S += '>';
3430        }
3431        S += '"';
3432      }
3433      return;
3434    }
3435
3436    QualType PointeeTy = OPT->getPointeeType();
3437    if (!EncodingProperty &&
3438        isa<TypedefType>(PointeeTy.getTypePtr())) {
3439      // Another historical/compatibility reason.
3440      // We encode the underlying type which comes out as
3441      // {...};
3442      S += '^';
3443      getObjCEncodingForTypeImpl(PointeeTy, S,
3444                                 false, ExpandPointedToStructures,
3445                                 NULL);
3446      return;
3447    }
3448
3449    S += '@';
3450    if (FD || EncodingProperty) {
3451      S += '"';
3452      S += OPT->getInterfaceDecl()->getNameAsCString();
3453      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3454           E = OPT->qual_end(); I != E; ++I) {
3455        S += '<';
3456        S += (*I)->getNameAsString();
3457        S += '>';
3458      }
3459      S += '"';
3460    }
3461    return;
3462  }
3463
3464  assert(0 && "@encode for type not implemented!");
3465}
3466
3467void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3468                                                 std::string& S) const {
3469  if (QT & Decl::OBJC_TQ_In)
3470    S += 'n';
3471  if (QT & Decl::OBJC_TQ_Inout)
3472    S += 'N';
3473  if (QT & Decl::OBJC_TQ_Out)
3474    S += 'o';
3475  if (QT & Decl::OBJC_TQ_Bycopy)
3476    S += 'O';
3477  if (QT & Decl::OBJC_TQ_Byref)
3478    S += 'R';
3479  if (QT & Decl::OBJC_TQ_Oneway)
3480    S += 'V';
3481}
3482
3483void ASTContext::setBuiltinVaListType(QualType T) {
3484  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3485
3486  BuiltinVaListType = T;
3487}
3488
3489void ASTContext::setObjCIdType(QualType T) {
3490  ObjCIdTypedefType = T;
3491}
3492
3493void ASTContext::setObjCSelType(QualType T) {
3494  ObjCSelType = T;
3495
3496  const TypedefType *TT = T->getAs<TypedefType>();
3497  if (!TT)
3498    return;
3499  TypedefDecl *TD = TT->getDecl();
3500
3501  // typedef struct objc_selector *SEL;
3502  const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
3503  if (!ptr)
3504    return;
3505  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
3506  if (!rec)
3507    return;
3508  SelStructType = rec;
3509}
3510
3511void ASTContext::setObjCProtoType(QualType QT) {
3512  ObjCProtoType = QT;
3513}
3514
3515void ASTContext::setObjCClassType(QualType T) {
3516  ObjCClassTypedefType = T;
3517}
3518
3519void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3520  assert(ObjCConstantStringType.isNull() &&
3521         "'NSConstantString' type already set!");
3522
3523  ObjCConstantStringType = getObjCInterfaceType(Decl);
3524}
3525
3526/// \brief Retrieve the template name that represents a qualified
3527/// template name such as \c std::vector.
3528TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3529                                                  bool TemplateKeyword,
3530                                                  TemplateDecl *Template) {
3531  llvm::FoldingSetNodeID ID;
3532  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3533
3534  void *InsertPos = 0;
3535  QualifiedTemplateName *QTN =
3536    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3537  if (!QTN) {
3538    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3539    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3540  }
3541
3542  return TemplateName(QTN);
3543}
3544
3545/// \brief Retrieve the template name that represents a qualified
3546/// template name such as \c std::vector.
3547TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3548                                                  bool TemplateKeyword,
3549                                            OverloadedFunctionDecl *Template) {
3550  llvm::FoldingSetNodeID ID;
3551  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3552
3553  void *InsertPos = 0;
3554  QualifiedTemplateName *QTN =
3555  QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3556  if (!QTN) {
3557    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3558    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3559  }
3560
3561  return TemplateName(QTN);
3562}
3563
3564/// \brief Retrieve the template name that represents a dependent
3565/// template name such as \c MetaFun::template apply.
3566TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3567                                                  const IdentifierInfo *Name) {
3568  assert((!NNS || NNS->isDependent()) &&
3569         "Nested name specifier must be dependent");
3570
3571  llvm::FoldingSetNodeID ID;
3572  DependentTemplateName::Profile(ID, NNS, Name);
3573
3574  void *InsertPos = 0;
3575  DependentTemplateName *QTN =
3576    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3577
3578  if (QTN)
3579    return TemplateName(QTN);
3580
3581  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3582  if (CanonNNS == NNS) {
3583    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3584  } else {
3585    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3586    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3587  }
3588
3589  DependentTemplateNames.InsertNode(QTN, InsertPos);
3590  return TemplateName(QTN);
3591}
3592
3593/// getFromTargetType - Given one of the integer types provided by
3594/// TargetInfo, produce the corresponding type. The unsigned @p Type
3595/// is actually a value of type @c TargetInfo::IntType.
3596QualType ASTContext::getFromTargetType(unsigned Type) const {
3597  switch (Type) {
3598  case TargetInfo::NoInt: return QualType();
3599  case TargetInfo::SignedShort: return ShortTy;
3600  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3601  case TargetInfo::SignedInt: return IntTy;
3602  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3603  case TargetInfo::SignedLong: return LongTy;
3604  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3605  case TargetInfo::SignedLongLong: return LongLongTy;
3606  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3607  }
3608
3609  assert(false && "Unhandled TargetInfo::IntType value");
3610  return QualType();
3611}
3612
3613//===----------------------------------------------------------------------===//
3614//                        Type Predicates.
3615//===----------------------------------------------------------------------===//
3616
3617/// isObjCNSObjectType - Return true if this is an NSObject object using
3618/// NSObject attribute on a c-style pointer type.
3619/// FIXME - Make it work directly on types.
3620/// FIXME: Move to Type.
3621///
3622bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3623  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3624    if (TypedefDecl *TD = TDT->getDecl())
3625      if (TD->getAttr<ObjCNSObjectAttr>())
3626        return true;
3627  }
3628  return false;
3629}
3630
3631/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3632/// garbage collection attribute.
3633///
3634Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3635  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3636  if (getLangOptions().ObjC1 &&
3637      getLangOptions().getGCMode() != LangOptions::NonGC) {
3638    GCAttrs = Ty.getObjCGCAttr();
3639    // Default behavious under objective-c's gc is for objective-c pointers
3640    // (or pointers to them) be treated as though they were declared
3641    // as __strong.
3642    if (GCAttrs == Qualifiers::GCNone) {
3643      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3644        GCAttrs = Qualifiers::Strong;
3645      else if (Ty->isPointerType())
3646        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3647    }
3648    // Non-pointers have none gc'able attribute regardless of the attribute
3649    // set on them.
3650    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3651      return Qualifiers::GCNone;
3652  }
3653  return GCAttrs;
3654}
3655
3656//===----------------------------------------------------------------------===//
3657//                        Type Compatibility Testing
3658//===----------------------------------------------------------------------===//
3659
3660/// areCompatVectorTypes - Return true if the two specified vector types are
3661/// compatible.
3662static bool areCompatVectorTypes(const VectorType *LHS,
3663                                 const VectorType *RHS) {
3664  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3665  return LHS->getElementType() == RHS->getElementType() &&
3666         LHS->getNumElements() == RHS->getNumElements();
3667}
3668
3669//===----------------------------------------------------------------------===//
3670// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3671//===----------------------------------------------------------------------===//
3672
3673/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3674/// inheritance hierarchy of 'rProto'.
3675bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3676                                                ObjCProtocolDecl *rProto) {
3677  if (lProto == rProto)
3678    return true;
3679  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3680       E = rProto->protocol_end(); PI != E; ++PI)
3681    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3682      return true;
3683  return false;
3684}
3685
3686/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3687/// return true if lhs's protocols conform to rhs's protocol; false
3688/// otherwise.
3689bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3690  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3691    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3692  return false;
3693}
3694
3695/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3696/// ObjCQualifiedIDType.
3697bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3698                                                   bool compare) {
3699  // Allow id<P..> and an 'id' or void* type in all cases.
3700  if (lhs->isVoidPointerType() ||
3701      lhs->isObjCIdType() || lhs->isObjCClassType())
3702    return true;
3703  else if (rhs->isVoidPointerType() ||
3704           rhs->isObjCIdType() || rhs->isObjCClassType())
3705    return true;
3706
3707  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3708    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
3709
3710    if (!rhsOPT) return false;
3711
3712    if (rhsOPT->qual_empty()) {
3713      // If the RHS is a unqualified interface pointer "NSString*",
3714      // make sure we check the class hierarchy.
3715      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3716        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3717             E = lhsQID->qual_end(); I != E; ++I) {
3718          // when comparing an id<P> on lhs with a static type on rhs,
3719          // see if static class implements all of id's protocols, directly or
3720          // through its super class and categories.
3721          if (!rhsID->ClassImplementsProtocol(*I, true))
3722            return false;
3723        }
3724      }
3725      // If there are no qualifiers and no interface, we have an 'id'.
3726      return true;
3727    }
3728    // Both the right and left sides have qualifiers.
3729    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3730         E = lhsQID->qual_end(); I != E; ++I) {
3731      ObjCProtocolDecl *lhsProto = *I;
3732      bool match = false;
3733
3734      // when comparing an id<P> on lhs with a static type on rhs,
3735      // see if static class implements all of id's protocols, directly or
3736      // through its super class and categories.
3737      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3738           E = rhsOPT->qual_end(); J != E; ++J) {
3739        ObjCProtocolDecl *rhsProto = *J;
3740        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3741            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3742          match = true;
3743          break;
3744        }
3745      }
3746      // If the RHS is a qualified interface pointer "NSString<P>*",
3747      // make sure we check the class hierarchy.
3748      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3749        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3750             E = lhsQID->qual_end(); I != E; ++I) {
3751          // when comparing an id<P> on lhs with a static type on rhs,
3752          // see if static class implements all of id's protocols, directly or
3753          // through its super class and categories.
3754          if (rhsID->ClassImplementsProtocol(*I, true)) {
3755            match = true;
3756            break;
3757          }
3758        }
3759      }
3760      if (!match)
3761        return false;
3762    }
3763
3764    return true;
3765  }
3766
3767  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3768  assert(rhsQID && "One of the LHS/RHS should be id<x>");
3769
3770  if (const ObjCObjectPointerType *lhsOPT =
3771        lhs->getAsObjCInterfacePointerType()) {
3772    if (lhsOPT->qual_empty()) {
3773      bool match = false;
3774      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3775        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3776             E = rhsQID->qual_end(); I != E; ++I) {
3777          // when comparing an id<P> on lhs with a static type on rhs,
3778          // see if static class implements all of id's protocols, directly or
3779          // through its super class and categories.
3780          if (lhsID->ClassImplementsProtocol(*I, true)) {
3781            match = true;
3782            break;
3783          }
3784        }
3785        if (!match)
3786          return false;
3787      }
3788      return true;
3789    }
3790    // Both the right and left sides have qualifiers.
3791    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3792         E = lhsOPT->qual_end(); I != E; ++I) {
3793      ObjCProtocolDecl *lhsProto = *I;
3794      bool match = false;
3795
3796      // when comparing an id<P> on lhs with a static type on rhs,
3797      // see if static class implements all of id's protocols, directly or
3798      // through its super class and categories.
3799      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3800           E = rhsQID->qual_end(); J != E; ++J) {
3801        ObjCProtocolDecl *rhsProto = *J;
3802        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3803            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3804          match = true;
3805          break;
3806        }
3807      }
3808      if (!match)
3809        return false;
3810    }
3811    return true;
3812  }
3813  return false;
3814}
3815
3816/// canAssignObjCInterfaces - Return true if the two interface types are
3817/// compatible for assignment from RHS to LHS.  This handles validation of any
3818/// protocol qualifiers on the LHS or RHS.
3819///
3820bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3821                                         const ObjCObjectPointerType *RHSOPT) {
3822  // If either type represents the built-in 'id' or 'Class' types, return true.
3823  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
3824    return true;
3825
3826  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3827    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3828                                             QualType(RHSOPT,0),
3829                                             false);
3830
3831  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3832  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3833  if (LHS && RHS) // We have 2 user-defined types.
3834    return canAssignObjCInterfaces(LHS, RHS);
3835
3836  return false;
3837}
3838
3839bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3840                                         const ObjCInterfaceType *RHS) {
3841  // Verify that the base decls are compatible: the RHS must be a subclass of
3842  // the LHS.
3843  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3844    return false;
3845
3846  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
3847  // protocol qualified at all, then we are good.
3848  if (LHS->getNumProtocols() == 0)
3849    return true;
3850
3851  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
3852  // isn't a superset.
3853  if (RHS->getNumProtocols() == 0)
3854    return true;  // FIXME: should return false!
3855
3856  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3857                                        LHSPE = LHS->qual_end();
3858       LHSPI != LHSPE; LHSPI++) {
3859    bool RHSImplementsProtocol = false;
3860
3861    // If the RHS doesn't implement the protocol on the left, the types
3862    // are incompatible.
3863    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3864                                          RHSPE = RHS->qual_end();
3865         RHSPI != RHSPE; RHSPI++) {
3866      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
3867        RHSImplementsProtocol = true;
3868        break;
3869      }
3870    }
3871    // FIXME: For better diagnostics, consider passing back the protocol name.
3872    if (!RHSImplementsProtocol)
3873      return false;
3874  }
3875  // The RHS implements all protocols listed on the LHS.
3876  return true;
3877}
3878
3879bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3880  // get the "pointed to" types
3881  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
3882  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
3883
3884  if (!LHSOPT || !RHSOPT)
3885    return false;
3886
3887  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3888         canAssignObjCInterfaces(RHSOPT, LHSOPT);
3889}
3890
3891/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3892/// both shall have the identically qualified version of a compatible type.
3893/// C99 6.2.7p1: Two types have compatible types if their types are the
3894/// same. See 6.7.[2,3,5] for additional rules.
3895bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3896  return !mergeTypes(LHS, RHS).isNull();
3897}
3898
3899QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3900  const FunctionType *lbase = lhs->getAs<FunctionType>();
3901  const FunctionType *rbase = rhs->getAs<FunctionType>();
3902  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3903  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3904  bool allLTypes = true;
3905  bool allRTypes = true;
3906
3907  // Check return type
3908  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3909  if (retType.isNull()) return QualType();
3910  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3911    allLTypes = false;
3912  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3913    allRTypes = false;
3914  // FIXME: double check this
3915  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3916  if (NoReturn != lbase->getNoReturnAttr())
3917    allLTypes = false;
3918  if (NoReturn != rbase->getNoReturnAttr())
3919    allRTypes = false;
3920
3921  if (lproto && rproto) { // two C99 style function prototypes
3922    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3923           "C++ shouldn't be here");
3924    unsigned lproto_nargs = lproto->getNumArgs();
3925    unsigned rproto_nargs = rproto->getNumArgs();
3926
3927    // Compatible functions must have the same number of arguments
3928    if (lproto_nargs != rproto_nargs)
3929      return QualType();
3930
3931    // Variadic and non-variadic functions aren't compatible
3932    if (lproto->isVariadic() != rproto->isVariadic())
3933      return QualType();
3934
3935    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3936      return QualType();
3937
3938    // Check argument compatibility
3939    llvm::SmallVector<QualType, 10> types;
3940    for (unsigned i = 0; i < lproto_nargs; i++) {
3941      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3942      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3943      QualType argtype = mergeTypes(largtype, rargtype);
3944      if (argtype.isNull()) return QualType();
3945      types.push_back(argtype);
3946      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3947        allLTypes = false;
3948      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3949        allRTypes = false;
3950    }
3951    if (allLTypes) return lhs;
3952    if (allRTypes) return rhs;
3953    return getFunctionType(retType, types.begin(), types.size(),
3954                           lproto->isVariadic(), lproto->getTypeQuals(),
3955                           NoReturn);
3956  }
3957
3958  if (lproto) allRTypes = false;
3959  if (rproto) allLTypes = false;
3960
3961  const FunctionProtoType *proto = lproto ? lproto : rproto;
3962  if (proto) {
3963    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3964    if (proto->isVariadic()) return QualType();
3965    // Check that the types are compatible with the types that
3966    // would result from default argument promotions (C99 6.7.5.3p15).
3967    // The only types actually affected are promotable integer
3968    // types and floats, which would be passed as a different
3969    // type depending on whether the prototype is visible.
3970    unsigned proto_nargs = proto->getNumArgs();
3971    for (unsigned i = 0; i < proto_nargs; ++i) {
3972      QualType argTy = proto->getArgType(i);
3973      if (argTy->isPromotableIntegerType() ||
3974          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3975        return QualType();
3976    }
3977
3978    if (allLTypes) return lhs;
3979    if (allRTypes) return rhs;
3980    return getFunctionType(retType, proto->arg_type_begin(),
3981                           proto->getNumArgs(), proto->isVariadic(),
3982                           proto->getTypeQuals(), NoReturn);
3983  }
3984
3985  if (allLTypes) return lhs;
3986  if (allRTypes) return rhs;
3987  return getFunctionNoProtoType(retType, NoReturn);
3988}
3989
3990QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3991  // C++ [expr]: If an expression initially has the type "reference to T", the
3992  // type is adjusted to "T" prior to any further analysis, the expression
3993  // designates the object or function denoted by the reference, and the
3994  // expression is an lvalue unless the reference is an rvalue reference and
3995  // the expression is a function call (possibly inside parentheses).
3996  // FIXME: C++ shouldn't be going through here!  The rules are different
3997  // enough that they should be handled separately.
3998  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3999  // shouldn't be going through here!
4000  if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
4001    LHS = RT->getPointeeType();
4002  if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
4003    RHS = RT->getPointeeType();
4004
4005  QualType LHSCan = getCanonicalType(LHS),
4006           RHSCan = getCanonicalType(RHS);
4007
4008  // If two types are identical, they are compatible.
4009  if (LHSCan == RHSCan)
4010    return LHS;
4011
4012  // If the qualifiers are different, the types aren't compatible... mostly.
4013  Qualifiers LQuals = LHSCan.getQualifiers();
4014  Qualifiers RQuals = RHSCan.getQualifiers();
4015  if (LQuals != RQuals) {
4016    // If any of these qualifiers are different, we have a type
4017    // mismatch.
4018    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4019        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4020      return QualType();
4021
4022    // Exactly one GC qualifier difference is allowed: __strong is
4023    // okay if the other type has no GC qualifier but is an Objective
4024    // C object pointer (i.e. implicitly strong by default).  We fix
4025    // this by pretending that the unqualified type was actually
4026    // qualified __strong.
4027    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4028    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4029    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4030
4031    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4032      return QualType();
4033
4034    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4035      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4036    }
4037    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4038      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4039    }
4040    return QualType();
4041  }
4042
4043  // Okay, qualifiers are equal.
4044
4045  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4046  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4047
4048  // We want to consider the two function types to be the same for these
4049  // comparisons, just force one to the other.
4050  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4051  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4052
4053  // Same as above for arrays
4054  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4055    LHSClass = Type::ConstantArray;
4056  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4057    RHSClass = Type::ConstantArray;
4058
4059  // Canonicalize ExtVector -> Vector.
4060  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4061  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4062
4063  // If the canonical type classes don't match.
4064  if (LHSClass != RHSClass) {
4065    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4066    // a signed integer type, or an unsigned integer type.
4067    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4068      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4069        return RHS;
4070    }
4071    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4072      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4073        return LHS;
4074    }
4075
4076    return QualType();
4077  }
4078
4079  // The canonical type classes match.
4080  switch (LHSClass) {
4081#define TYPE(Class, Base)
4082#define ABSTRACT_TYPE(Class, Base)
4083#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4084#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4085#include "clang/AST/TypeNodes.def"
4086    assert(false && "Non-canonical and dependent types shouldn't get here");
4087    return QualType();
4088
4089  case Type::LValueReference:
4090  case Type::RValueReference:
4091  case Type::MemberPointer:
4092    assert(false && "C++ should never be in mergeTypes");
4093    return QualType();
4094
4095  case Type::IncompleteArray:
4096  case Type::VariableArray:
4097  case Type::FunctionProto:
4098  case Type::ExtVector:
4099    assert(false && "Types are eliminated above");
4100    return QualType();
4101
4102  case Type::Pointer:
4103  {
4104    // Merge two pointer types, while trying to preserve typedef info
4105    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4106    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4107    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4108    if (ResultType.isNull()) return QualType();
4109    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4110      return LHS;
4111    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4112      return RHS;
4113    return getPointerType(ResultType);
4114  }
4115  case Type::BlockPointer:
4116  {
4117    // Merge two block pointer types, while trying to preserve typedef info
4118    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4119    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4120    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4121    if (ResultType.isNull()) return QualType();
4122    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4123      return LHS;
4124    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4125      return RHS;
4126    return getBlockPointerType(ResultType);
4127  }
4128  case Type::ConstantArray:
4129  {
4130    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4131    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4132    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4133      return QualType();
4134
4135    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4136    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4137    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4138    if (ResultType.isNull()) return QualType();
4139    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4140      return LHS;
4141    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4142      return RHS;
4143    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4144                                          ArrayType::ArraySizeModifier(), 0);
4145    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4146                                          ArrayType::ArraySizeModifier(), 0);
4147    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4148    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4149    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4150      return LHS;
4151    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4152      return RHS;
4153    if (LVAT) {
4154      // FIXME: This isn't correct! But tricky to implement because
4155      // the array's size has to be the size of LHS, but the type
4156      // has to be different.
4157      return LHS;
4158    }
4159    if (RVAT) {
4160      // FIXME: This isn't correct! But tricky to implement because
4161      // the array's size has to be the size of RHS, but the type
4162      // has to be different.
4163      return RHS;
4164    }
4165    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4166    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4167    return getIncompleteArrayType(ResultType,
4168                                  ArrayType::ArraySizeModifier(), 0);
4169  }
4170  case Type::FunctionNoProto:
4171    return mergeFunctionTypes(LHS, RHS);
4172  case Type::Record:
4173  case Type::Enum:
4174    return QualType();
4175  case Type::Builtin:
4176    // Only exactly equal builtin types are compatible, which is tested above.
4177    return QualType();
4178  case Type::Complex:
4179    // Distinct complex types are incompatible.
4180    return QualType();
4181  case Type::Vector:
4182    // FIXME: The merged type should be an ExtVector!
4183    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4184      return LHS;
4185    return QualType();
4186  case Type::ObjCInterface: {
4187    // Check if the interfaces are assignment compatible.
4188    // FIXME: This should be type compatibility, e.g. whether
4189    // "LHS x; RHS x;" at global scope is legal.
4190    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4191    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4192    if (LHSIface && RHSIface &&
4193        canAssignObjCInterfaces(LHSIface, RHSIface))
4194      return LHS;
4195
4196    return QualType();
4197  }
4198  case Type::ObjCObjectPointer: {
4199    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4200                                RHS->getAs<ObjCObjectPointerType>()))
4201      return LHS;
4202
4203    return QualType();
4204  }
4205  case Type::FixedWidthInt:
4206    // Distinct fixed-width integers are not compatible.
4207    return QualType();
4208  case Type::TemplateSpecialization:
4209    assert(false && "Dependent types have no size");
4210    break;
4211  }
4212
4213  return QualType();
4214}
4215
4216//===----------------------------------------------------------------------===//
4217//                         Integer Predicates
4218//===----------------------------------------------------------------------===//
4219
4220unsigned ASTContext::getIntWidth(QualType T) {
4221  if (T == BoolTy)
4222    return 1;
4223  if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
4224    return FWIT->getWidth();
4225  }
4226  // For builtin types, just use the standard type sizing method
4227  return (unsigned)getTypeSize(T);
4228}
4229
4230QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4231  assert(T->isSignedIntegerType() && "Unexpected type");
4232
4233  // Turn <4 x signed int> -> <4 x unsigned int>
4234  if (const VectorType *VTy = T->getAs<VectorType>())
4235    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4236                         VTy->getNumElements());
4237
4238  // For enums, we return the unsigned version of the base type.
4239  if (const EnumType *ETy = T->getAs<EnumType>())
4240    T = ETy->getDecl()->getIntegerType();
4241
4242  const BuiltinType *BTy = T->getAs<BuiltinType>();
4243  assert(BTy && "Unexpected signed integer type");
4244  switch (BTy->getKind()) {
4245  case BuiltinType::Char_S:
4246  case BuiltinType::SChar:
4247    return UnsignedCharTy;
4248  case BuiltinType::Short:
4249    return UnsignedShortTy;
4250  case BuiltinType::Int:
4251    return UnsignedIntTy;
4252  case BuiltinType::Long:
4253    return UnsignedLongTy;
4254  case BuiltinType::LongLong:
4255    return UnsignedLongLongTy;
4256  case BuiltinType::Int128:
4257    return UnsignedInt128Ty;
4258  default:
4259    assert(0 && "Unexpected signed integer type");
4260    return QualType();
4261  }
4262}
4263
4264ExternalASTSource::~ExternalASTSource() { }
4265
4266void ExternalASTSource::PrintStats() { }
4267
4268
4269//===----------------------------------------------------------------------===//
4270//                          Builtin Type Computation
4271//===----------------------------------------------------------------------===//
4272
4273/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4274/// pointer over the consumed characters.  This returns the resultant type.
4275static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4276                                  ASTContext::GetBuiltinTypeError &Error,
4277                                  bool AllowTypeModifiers = true) {
4278  // Modifiers.
4279  int HowLong = 0;
4280  bool Signed = false, Unsigned = false;
4281
4282  // Read the modifiers first.
4283  bool Done = false;
4284  while (!Done) {
4285    switch (*Str++) {
4286    default: Done = true; --Str; break;
4287    case 'S':
4288      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4289      assert(!Signed && "Can't use 'S' modifier multiple times!");
4290      Signed = true;
4291      break;
4292    case 'U':
4293      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4294      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4295      Unsigned = true;
4296      break;
4297    case 'L':
4298      assert(HowLong <= 2 && "Can't have LLLL modifier");
4299      ++HowLong;
4300      break;
4301    }
4302  }
4303
4304  QualType Type;
4305
4306  // Read the base type.
4307  switch (*Str++) {
4308  default: assert(0 && "Unknown builtin type letter!");
4309  case 'v':
4310    assert(HowLong == 0 && !Signed && !Unsigned &&
4311           "Bad modifiers used with 'v'!");
4312    Type = Context.VoidTy;
4313    break;
4314  case 'f':
4315    assert(HowLong == 0 && !Signed && !Unsigned &&
4316           "Bad modifiers used with 'f'!");
4317    Type = Context.FloatTy;
4318    break;
4319  case 'd':
4320    assert(HowLong < 2 && !Signed && !Unsigned &&
4321           "Bad modifiers used with 'd'!");
4322    if (HowLong)
4323      Type = Context.LongDoubleTy;
4324    else
4325      Type = Context.DoubleTy;
4326    break;
4327  case 's':
4328    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4329    if (Unsigned)
4330      Type = Context.UnsignedShortTy;
4331    else
4332      Type = Context.ShortTy;
4333    break;
4334  case 'i':
4335    if (HowLong == 3)
4336      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4337    else if (HowLong == 2)
4338      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4339    else if (HowLong == 1)
4340      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4341    else
4342      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4343    break;
4344  case 'c':
4345    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4346    if (Signed)
4347      Type = Context.SignedCharTy;
4348    else if (Unsigned)
4349      Type = Context.UnsignedCharTy;
4350    else
4351      Type = Context.CharTy;
4352    break;
4353  case 'b': // boolean
4354    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4355    Type = Context.BoolTy;
4356    break;
4357  case 'z':  // size_t.
4358    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4359    Type = Context.getSizeType();
4360    break;
4361  case 'F':
4362    Type = Context.getCFConstantStringType();
4363    break;
4364  case 'a':
4365    Type = Context.getBuiltinVaListType();
4366    assert(!Type.isNull() && "builtin va list type not initialized!");
4367    break;
4368  case 'A':
4369    // This is a "reference" to a va_list; however, what exactly
4370    // this means depends on how va_list is defined. There are two
4371    // different kinds of va_list: ones passed by value, and ones
4372    // passed by reference.  An example of a by-value va_list is
4373    // x86, where va_list is a char*. An example of by-ref va_list
4374    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4375    // we want this argument to be a char*&; for x86-64, we want
4376    // it to be a __va_list_tag*.
4377    Type = Context.getBuiltinVaListType();
4378    assert(!Type.isNull() && "builtin va list type not initialized!");
4379    if (Type->isArrayType()) {
4380      Type = Context.getArrayDecayedType(Type);
4381    } else {
4382      Type = Context.getLValueReferenceType(Type);
4383    }
4384    break;
4385  case 'V': {
4386    char *End;
4387    unsigned NumElements = strtoul(Str, &End, 10);
4388    assert(End != Str && "Missing vector size");
4389
4390    Str = End;
4391
4392    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4393    Type = Context.getVectorType(ElementType, NumElements);
4394    break;
4395  }
4396  case 'X': {
4397    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4398    Type = Context.getComplexType(ElementType);
4399    break;
4400  }
4401  case 'P':
4402    Type = Context.getFILEType();
4403    if (Type.isNull()) {
4404      Error = ASTContext::GE_Missing_stdio;
4405      return QualType();
4406    }
4407    break;
4408  case 'J':
4409    if (Signed)
4410      Type = Context.getsigjmp_bufType();
4411    else
4412      Type = Context.getjmp_bufType();
4413
4414    if (Type.isNull()) {
4415      Error = ASTContext::GE_Missing_setjmp;
4416      return QualType();
4417    }
4418    break;
4419  }
4420
4421  if (!AllowTypeModifiers)
4422    return Type;
4423
4424  Done = false;
4425  while (!Done) {
4426    switch (*Str++) {
4427      default: Done = true; --Str; break;
4428      case '*':
4429        Type = Context.getPointerType(Type);
4430        break;
4431      case '&':
4432        Type = Context.getLValueReferenceType(Type);
4433        break;
4434      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4435      case 'C':
4436        Type = Type.withConst();
4437        break;
4438    }
4439  }
4440
4441  return Type;
4442}
4443
4444/// GetBuiltinType - Return the type for the specified builtin.
4445QualType ASTContext::GetBuiltinType(unsigned id,
4446                                    GetBuiltinTypeError &Error) {
4447  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4448
4449  llvm::SmallVector<QualType, 8> ArgTypes;
4450
4451  Error = GE_None;
4452  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4453  if (Error != GE_None)
4454    return QualType();
4455  while (TypeStr[0] && TypeStr[0] != '.') {
4456    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4457    if (Error != GE_None)
4458      return QualType();
4459
4460    // Do array -> pointer decay.  The builtin should use the decayed type.
4461    if (Ty->isArrayType())
4462      Ty = getArrayDecayedType(Ty);
4463
4464    ArgTypes.push_back(Ty);
4465  }
4466
4467  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4468         "'.' should only occur at end of builtin type list!");
4469
4470  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4471  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4472    return getFunctionNoProtoType(ResType);
4473  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4474                         TypeStr[0] == '.', 0);
4475}
4476
4477QualType
4478ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4479  // Perform the usual unary conversions. We do this early so that
4480  // integral promotions to "int" can allow us to exit early, in the
4481  // lhs == rhs check. Also, for conversion purposes, we ignore any
4482  // qualifiers.  For example, "const float" and "float" are
4483  // equivalent.
4484  if (lhs->isPromotableIntegerType())
4485    lhs = getPromotedIntegerType(lhs);
4486  else
4487    lhs = lhs.getUnqualifiedType();
4488  if (rhs->isPromotableIntegerType())
4489    rhs = getPromotedIntegerType(rhs);
4490  else
4491    rhs = rhs.getUnqualifiedType();
4492
4493  // If both types are identical, no conversion is needed.
4494  if (lhs == rhs)
4495    return lhs;
4496
4497  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4498  // The caller can deal with this (e.g. pointer + int).
4499  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4500    return lhs;
4501
4502  // At this point, we have two different arithmetic types.
4503
4504  // Handle complex types first (C99 6.3.1.8p1).
4505  if (lhs->isComplexType() || rhs->isComplexType()) {
4506    // if we have an integer operand, the result is the complex type.
4507    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4508      // convert the rhs to the lhs complex type.
4509      return lhs;
4510    }
4511    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4512      // convert the lhs to the rhs complex type.
4513      return rhs;
4514    }
4515    // This handles complex/complex, complex/float, or float/complex.
4516    // When both operands are complex, the shorter operand is converted to the
4517    // type of the longer, and that is the type of the result. This corresponds
4518    // to what is done when combining two real floating-point operands.
4519    // The fun begins when size promotion occur across type domains.
4520    // From H&S 6.3.4: When one operand is complex and the other is a real
4521    // floating-point type, the less precise type is converted, within it's
4522    // real or complex domain, to the precision of the other type. For example,
4523    // when combining a "long double" with a "double _Complex", the
4524    // "double _Complex" is promoted to "long double _Complex".
4525    int result = getFloatingTypeOrder(lhs, rhs);
4526
4527    if (result > 0) { // The left side is bigger, convert rhs.
4528      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4529    } else if (result < 0) { // The right side is bigger, convert lhs.
4530      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4531    }
4532    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4533    // domains match. This is a requirement for our implementation, C99
4534    // does not require this promotion.
4535    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4536      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4537        return rhs;
4538      } else { // handle "_Complex double, double".
4539        return lhs;
4540      }
4541    }
4542    return lhs; // The domain/size match exactly.
4543  }
4544  // Now handle "real" floating types (i.e. float, double, long double).
4545  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4546    // if we have an integer operand, the result is the real floating type.
4547    if (rhs->isIntegerType()) {
4548      // convert rhs to the lhs floating point type.
4549      return lhs;
4550    }
4551    if (rhs->isComplexIntegerType()) {
4552      // convert rhs to the complex floating point type.
4553      return getComplexType(lhs);
4554    }
4555    if (lhs->isIntegerType()) {
4556      // convert lhs to the rhs floating point type.
4557      return rhs;
4558    }
4559    if (lhs->isComplexIntegerType()) {
4560      // convert lhs to the complex floating point type.
4561      return getComplexType(rhs);
4562    }
4563    // We have two real floating types, float/complex combos were handled above.
4564    // Convert the smaller operand to the bigger result.
4565    int result = getFloatingTypeOrder(lhs, rhs);
4566    if (result > 0) // convert the rhs
4567      return lhs;
4568    assert(result < 0 && "illegal float comparison");
4569    return rhs;   // convert the lhs
4570  }
4571  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4572    // Handle GCC complex int extension.
4573    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4574    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4575
4576    if (lhsComplexInt && rhsComplexInt) {
4577      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4578                              rhsComplexInt->getElementType()) >= 0)
4579        return lhs; // convert the rhs
4580      return rhs;
4581    } else if (lhsComplexInt && rhs->isIntegerType()) {
4582      // convert the rhs to the lhs complex type.
4583      return lhs;
4584    } else if (rhsComplexInt && lhs->isIntegerType()) {
4585      // convert the lhs to the rhs complex type.
4586      return rhs;
4587    }
4588  }
4589  // Finally, we have two differing integer types.
4590  // The rules for this case are in C99 6.3.1.8
4591  int compare = getIntegerTypeOrder(lhs, rhs);
4592  bool lhsSigned = lhs->isSignedIntegerType(),
4593       rhsSigned = rhs->isSignedIntegerType();
4594  QualType destType;
4595  if (lhsSigned == rhsSigned) {
4596    // Same signedness; use the higher-ranked type
4597    destType = compare >= 0 ? lhs : rhs;
4598  } else if (compare != (lhsSigned ? 1 : -1)) {
4599    // The unsigned type has greater than or equal rank to the
4600    // signed type, so use the unsigned type
4601    destType = lhsSigned ? rhs : lhs;
4602  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4603    // The two types are different widths; if we are here, that
4604    // means the signed type is larger than the unsigned type, so
4605    // use the signed type.
4606    destType = lhsSigned ? lhs : rhs;
4607  } else {
4608    // The signed type is higher-ranked than the unsigned type,
4609    // but isn't actually any bigger (like unsigned int and long
4610    // on most 32-bit systems).  Use the unsigned type corresponding
4611    // to the signed type.
4612    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4613  }
4614  return destType;
4615}
4616