ASTContext.cpp revision fb40e3f10ccef93c4f8fb6bd4fe5a108fa6cd369
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/CharUnits.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExternalASTSource.h"
23#include "clang/AST/ASTMutationListener.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Mangle.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/Capacity.h"
34#include "CXXABI.h"
35#include <map>
36
37using namespace clang;
38
39unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
41unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
43unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
45unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
47unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
49unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
52enum FloatingRank {
53  HalfRank, FloatRank, DoubleRank, LongDoubleRank
54};
55
56const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
57  if (!CommentsLoaded && ExternalSource) {
58    ExternalSource->ReadComments();
59    CommentsLoaded = true;
60  }
61
62  assert(D);
63
64  // User can not attach documentation to implicit declarations.
65  if (D->isImplicit())
66    return NULL;
67
68  // TODO: handle comments for function parameters properly.
69  if (isa<ParmVarDecl>(D))
70    return NULL;
71
72  ArrayRef<RawComment> RawComments = Comments.getComments();
73
74  // If there are no comments anywhere, we won't find anything.
75  if (RawComments.empty())
76    return NULL;
77
78  // If the declaration doesn't map directly to a location in a file, we
79  // can't find the comment.
80  SourceLocation DeclLoc = D->getLocation();
81  if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
82    return NULL;
83
84  // Find the comment that occurs just after this declaration.
85  ArrayRef<RawComment>::iterator Comment
86      = std::lower_bound(RawComments.begin(),
87                         RawComments.end(),
88                         RawComment(SourceMgr, SourceRange(DeclLoc)),
89                         BeforeThanCompare<RawComment>(SourceMgr));
90
91  // Decompose the location for the declaration and find the beginning of the
92  // file buffer.
93  std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
94
95  // First check whether we have a trailing comment.
96  if (Comment != RawComments.end() &&
97      Comment->isDocumentation() && Comment->isTrailingComment() &&
98      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
99    std::pair<FileID, unsigned> CommentBeginDecomp
100      = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
101    // Check that Doxygen trailing comment comes after the declaration, starts
102    // on the same line and in the same file as the declaration.
103    if (DeclLocDecomp.first == CommentBeginDecomp.first &&
104        SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
105          == SourceMgr.getLineNumber(CommentBeginDecomp.first,
106                                     CommentBeginDecomp.second)) {
107      return &*Comment;
108    }
109  }
110
111  // The comment just after the declaration was not a trailing comment.
112  // Let's look at the previous comment.
113  if (Comment == RawComments.begin())
114    return NULL;
115  --Comment;
116
117  // Check that we actually have a non-member Doxygen comment.
118  if (!Comment->isDocumentation() || Comment->isTrailingComment())
119    return NULL;
120
121  // Decompose the end of the comment.
122  std::pair<FileID, unsigned> CommentEndDecomp
123    = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
124
125  // If the comment and the declaration aren't in the same file, then they
126  // aren't related.
127  if (DeclLocDecomp.first != CommentEndDecomp.first)
128    return NULL;
129
130  // Get the corresponding buffer.
131  bool Invalid = false;
132  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
133                                               &Invalid).data();
134  if (Invalid)
135    return NULL;
136
137  // Extract text between the comment and declaration.
138  StringRef Text(Buffer + CommentEndDecomp.second,
139                 DeclLocDecomp.second - CommentEndDecomp.second);
140
141  // There should be no other declarations or preprocessor directives between
142  // comment and declaration.
143  if (Text.find_first_of(",;{}#") != StringRef::npos)
144    return NULL;
145
146  return &*Comment;
147}
148
149const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
150  // Check whether we have cached a comment string for this declaration
151  // already.
152  llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
153      = DeclComments.find(D);
154  if (Pos != DeclComments.end())
155      return Pos->second;
156
157  const RawComment *RC = getRawCommentForDeclNoCache(D);
158  // If we found a comment, it should be a documentation comment.
159  assert(!RC || RC->isDocumentation());
160  DeclComments[D] = RC;
161  return RC;
162}
163
164void
165ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
166                                               TemplateTemplateParmDecl *Parm) {
167  ID.AddInteger(Parm->getDepth());
168  ID.AddInteger(Parm->getPosition());
169  ID.AddBoolean(Parm->isParameterPack());
170
171  TemplateParameterList *Params = Parm->getTemplateParameters();
172  ID.AddInteger(Params->size());
173  for (TemplateParameterList::const_iterator P = Params->begin(),
174                                          PEnd = Params->end();
175       P != PEnd; ++P) {
176    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
177      ID.AddInteger(0);
178      ID.AddBoolean(TTP->isParameterPack());
179      continue;
180    }
181
182    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
183      ID.AddInteger(1);
184      ID.AddBoolean(NTTP->isParameterPack());
185      ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
186      if (NTTP->isExpandedParameterPack()) {
187        ID.AddBoolean(true);
188        ID.AddInteger(NTTP->getNumExpansionTypes());
189        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
190          QualType T = NTTP->getExpansionType(I);
191          ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
192        }
193      } else
194        ID.AddBoolean(false);
195      continue;
196    }
197
198    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
199    ID.AddInteger(2);
200    Profile(ID, TTP);
201  }
202}
203
204TemplateTemplateParmDecl *
205ASTContext::getCanonicalTemplateTemplateParmDecl(
206                                          TemplateTemplateParmDecl *TTP) const {
207  // Check if we already have a canonical template template parameter.
208  llvm::FoldingSetNodeID ID;
209  CanonicalTemplateTemplateParm::Profile(ID, TTP);
210  void *InsertPos = 0;
211  CanonicalTemplateTemplateParm *Canonical
212    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
213  if (Canonical)
214    return Canonical->getParam();
215
216  // Build a canonical template parameter list.
217  TemplateParameterList *Params = TTP->getTemplateParameters();
218  SmallVector<NamedDecl *, 4> CanonParams;
219  CanonParams.reserve(Params->size());
220  for (TemplateParameterList::const_iterator P = Params->begin(),
221                                          PEnd = Params->end();
222       P != PEnd; ++P) {
223    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
224      CanonParams.push_back(
225                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
226                                               SourceLocation(),
227                                               SourceLocation(),
228                                               TTP->getDepth(),
229                                               TTP->getIndex(), 0, false,
230                                               TTP->isParameterPack()));
231    else if (NonTypeTemplateParmDecl *NTTP
232             = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
233      QualType T = getCanonicalType(NTTP->getType());
234      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
235      NonTypeTemplateParmDecl *Param;
236      if (NTTP->isExpandedParameterPack()) {
237        SmallVector<QualType, 2> ExpandedTypes;
238        SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
239        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
240          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
241          ExpandedTInfos.push_back(
242                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
243        }
244
245        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
246                                                SourceLocation(),
247                                                SourceLocation(),
248                                                NTTP->getDepth(),
249                                                NTTP->getPosition(), 0,
250                                                T,
251                                                TInfo,
252                                                ExpandedTypes.data(),
253                                                ExpandedTypes.size(),
254                                                ExpandedTInfos.data());
255      } else {
256        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
257                                                SourceLocation(),
258                                                SourceLocation(),
259                                                NTTP->getDepth(),
260                                                NTTP->getPosition(), 0,
261                                                T,
262                                                NTTP->isParameterPack(),
263                                                TInfo);
264      }
265      CanonParams.push_back(Param);
266
267    } else
268      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
269                                           cast<TemplateTemplateParmDecl>(*P)));
270  }
271
272  TemplateTemplateParmDecl *CanonTTP
273    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
274                                       SourceLocation(), TTP->getDepth(),
275                                       TTP->getPosition(),
276                                       TTP->isParameterPack(),
277                                       0,
278                         TemplateParameterList::Create(*this, SourceLocation(),
279                                                       SourceLocation(),
280                                                       CanonParams.data(),
281                                                       CanonParams.size(),
282                                                       SourceLocation()));
283
284  // Get the new insert position for the node we care about.
285  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
286  assert(Canonical == 0 && "Shouldn't be in the map!");
287  (void)Canonical;
288
289  // Create the canonical template template parameter entry.
290  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
291  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
292  return CanonTTP;
293}
294
295CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
296  if (!LangOpts.CPlusPlus) return 0;
297
298  switch (T.getCXXABI()) {
299  case CXXABI_ARM:
300    return CreateARMCXXABI(*this);
301  case CXXABI_Itanium:
302    return CreateItaniumCXXABI(*this);
303  case CXXABI_Microsoft:
304    return CreateMicrosoftCXXABI(*this);
305  }
306  llvm_unreachable("Invalid CXXABI type!");
307}
308
309static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
310                                             const LangOptions &LOpts) {
311  if (LOpts.FakeAddressSpaceMap) {
312    // The fake address space map must have a distinct entry for each
313    // language-specific address space.
314    static const unsigned FakeAddrSpaceMap[] = {
315      1, // opencl_global
316      2, // opencl_local
317      3, // opencl_constant
318      4, // cuda_device
319      5, // cuda_constant
320      6  // cuda_shared
321    };
322    return &FakeAddrSpaceMap;
323  } else {
324    return &T.getAddressSpaceMap();
325  }
326}
327
328ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
329                       const TargetInfo *t,
330                       IdentifierTable &idents, SelectorTable &sels,
331                       Builtin::Context &builtins,
332                       unsigned size_reserve,
333                       bool DelayInitialization)
334  : FunctionProtoTypes(this_()),
335    TemplateSpecializationTypes(this_()),
336    DependentTemplateSpecializationTypes(this_()),
337    SubstTemplateTemplateParmPacks(this_()),
338    GlobalNestedNameSpecifier(0),
339    Int128Decl(0), UInt128Decl(0),
340    BuiltinVaListDecl(0),
341    ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
342    CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
343    FILEDecl(0),
344    jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
345    BlockDescriptorType(0), BlockDescriptorExtendedType(0),
346    cudaConfigureCallDecl(0),
347    NullTypeSourceInfo(QualType()),
348    FirstLocalImport(), LastLocalImport(),
349    SourceMgr(SM), LangOpts(LOpts),
350    AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
351    Idents(idents), Selectors(sels),
352    BuiltinInfo(builtins),
353    DeclarationNames(*this),
354    ExternalSource(0), Listener(0),
355    Comments(SM), CommentsLoaded(false),
356    LastSDM(0, 0),
357    UniqueBlockByRefTypeID(0)
358{
359  if (size_reserve > 0) Types.reserve(size_reserve);
360  TUDecl = TranslationUnitDecl::Create(*this);
361
362  if (!DelayInitialization) {
363    assert(t && "No target supplied for ASTContext initialization");
364    InitBuiltinTypes(*t);
365  }
366}
367
368ASTContext::~ASTContext() {
369  // Release the DenseMaps associated with DeclContext objects.
370  // FIXME: Is this the ideal solution?
371  ReleaseDeclContextMaps();
372
373  // Call all of the deallocation functions.
374  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
375    Deallocations[I].first(Deallocations[I].second);
376
377  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
378  // because they can contain DenseMaps.
379  for (llvm::DenseMap<const ObjCContainerDecl*,
380       const ASTRecordLayout*>::iterator
381       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
382    // Increment in loop to prevent using deallocated memory.
383    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
384      R->Destroy(*this);
385
386  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
387       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
388    // Increment in loop to prevent using deallocated memory.
389    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
390      R->Destroy(*this);
391  }
392
393  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
394                                                    AEnd = DeclAttrs.end();
395       A != AEnd; ++A)
396    A->second->~AttrVec();
397}
398
399void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
400  Deallocations.push_back(std::make_pair(Callback, Data));
401}
402
403void
404ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
405  ExternalSource.reset(Source.take());
406}
407
408void ASTContext::PrintStats() const {
409  llvm::errs() << "\n*** AST Context Stats:\n";
410  llvm::errs() << "  " << Types.size() << " types total.\n";
411
412  unsigned counts[] = {
413#define TYPE(Name, Parent) 0,
414#define ABSTRACT_TYPE(Name, Parent)
415#include "clang/AST/TypeNodes.def"
416    0 // Extra
417  };
418
419  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
420    Type *T = Types[i];
421    counts[(unsigned)T->getTypeClass()]++;
422  }
423
424  unsigned Idx = 0;
425  unsigned TotalBytes = 0;
426#define TYPE(Name, Parent)                                              \
427  if (counts[Idx])                                                      \
428    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
429                 << " types\n";                                         \
430  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
431  ++Idx;
432#define ABSTRACT_TYPE(Name, Parent)
433#include "clang/AST/TypeNodes.def"
434
435  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
436
437  // Implicit special member functions.
438  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
439               << NumImplicitDefaultConstructors
440               << " implicit default constructors created\n";
441  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
442               << NumImplicitCopyConstructors
443               << " implicit copy constructors created\n";
444  if (getLangOpts().CPlusPlus)
445    llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
446                 << NumImplicitMoveConstructors
447                 << " implicit move constructors created\n";
448  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
449               << NumImplicitCopyAssignmentOperators
450               << " implicit copy assignment operators created\n";
451  if (getLangOpts().CPlusPlus)
452    llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
453                 << NumImplicitMoveAssignmentOperators
454                 << " implicit move assignment operators created\n";
455  llvm::errs() << NumImplicitDestructorsDeclared << "/"
456               << NumImplicitDestructors
457               << " implicit destructors created\n";
458
459  if (ExternalSource.get()) {
460    llvm::errs() << "\n";
461    ExternalSource->PrintStats();
462  }
463
464  BumpAlloc.PrintStats();
465}
466
467TypedefDecl *ASTContext::getInt128Decl() const {
468  if (!Int128Decl) {
469    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
470    Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
471                                     getTranslationUnitDecl(),
472                                     SourceLocation(),
473                                     SourceLocation(),
474                                     &Idents.get("__int128_t"),
475                                     TInfo);
476  }
477
478  return Int128Decl;
479}
480
481TypedefDecl *ASTContext::getUInt128Decl() const {
482  if (!UInt128Decl) {
483    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
484    UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
485                                     getTranslationUnitDecl(),
486                                     SourceLocation(),
487                                     SourceLocation(),
488                                     &Idents.get("__uint128_t"),
489                                     TInfo);
490  }
491
492  return UInt128Decl;
493}
494
495void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
496  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
497  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
498  Types.push_back(Ty);
499}
500
501void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
502  assert((!this->Target || this->Target == &Target) &&
503         "Incorrect target reinitialization");
504  assert(VoidTy.isNull() && "Context reinitialized?");
505
506  this->Target = &Target;
507
508  ABI.reset(createCXXABI(Target));
509  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
510
511  // C99 6.2.5p19.
512  InitBuiltinType(VoidTy,              BuiltinType::Void);
513
514  // C99 6.2.5p2.
515  InitBuiltinType(BoolTy,              BuiltinType::Bool);
516  // C99 6.2.5p3.
517  if (LangOpts.CharIsSigned)
518    InitBuiltinType(CharTy,            BuiltinType::Char_S);
519  else
520    InitBuiltinType(CharTy,            BuiltinType::Char_U);
521  // C99 6.2.5p4.
522  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
523  InitBuiltinType(ShortTy,             BuiltinType::Short);
524  InitBuiltinType(IntTy,               BuiltinType::Int);
525  InitBuiltinType(LongTy,              BuiltinType::Long);
526  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
527
528  // C99 6.2.5p6.
529  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
530  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
531  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
532  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
533  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
534
535  // C99 6.2.5p10.
536  InitBuiltinType(FloatTy,             BuiltinType::Float);
537  InitBuiltinType(DoubleTy,            BuiltinType::Double);
538  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
539
540  // GNU extension, 128-bit integers.
541  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
542  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
543
544  if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
545    if (TargetInfo::isTypeSigned(Target.getWCharType()))
546      InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
547    else  // -fshort-wchar makes wchar_t be unsigned.
548      InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
549  } else // C99
550    WCharTy = getFromTargetType(Target.getWCharType());
551
552  WIntTy = getFromTargetType(Target.getWIntType());
553
554  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
555    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
556  else // C99
557    Char16Ty = getFromTargetType(Target.getChar16Type());
558
559  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
560    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
561  else // C99
562    Char32Ty = getFromTargetType(Target.getChar32Type());
563
564  // Placeholder type for type-dependent expressions whose type is
565  // completely unknown. No code should ever check a type against
566  // DependentTy and users should never see it; however, it is here to
567  // help diagnose failures to properly check for type-dependent
568  // expressions.
569  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
570
571  // Placeholder type for functions.
572  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
573
574  // Placeholder type for bound members.
575  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
576
577  // Placeholder type for pseudo-objects.
578  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
579
580  // "any" type; useful for debugger-like clients.
581  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
582
583  // Placeholder type for unbridged ARC casts.
584  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
585
586  // C99 6.2.5p11.
587  FloatComplexTy      = getComplexType(FloatTy);
588  DoubleComplexTy     = getComplexType(DoubleTy);
589  LongDoubleComplexTy = getComplexType(LongDoubleTy);
590
591  // Builtin types for 'id', 'Class', and 'SEL'.
592  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
593  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
594  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
595
596  // Builtin type for __objc_yes and __objc_no
597  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
598                       SignedCharTy : BoolTy);
599
600  ObjCConstantStringType = QualType();
601
602  // void * type
603  VoidPtrTy = getPointerType(VoidTy);
604
605  // nullptr type (C++0x 2.14.7)
606  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
607
608  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
609  InitBuiltinType(HalfTy, BuiltinType::Half);
610
611  // Builtin type used to help define __builtin_va_list.
612  VaListTagTy = QualType();
613}
614
615DiagnosticsEngine &ASTContext::getDiagnostics() const {
616  return SourceMgr.getDiagnostics();
617}
618
619AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
620  AttrVec *&Result = DeclAttrs[D];
621  if (!Result) {
622    void *Mem = Allocate(sizeof(AttrVec));
623    Result = new (Mem) AttrVec;
624  }
625
626  return *Result;
627}
628
629/// \brief Erase the attributes corresponding to the given declaration.
630void ASTContext::eraseDeclAttrs(const Decl *D) {
631  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
632  if (Pos != DeclAttrs.end()) {
633    Pos->second->~AttrVec();
634    DeclAttrs.erase(Pos);
635  }
636}
637
638MemberSpecializationInfo *
639ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
640  assert(Var->isStaticDataMember() && "Not a static data member");
641  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
642    = InstantiatedFromStaticDataMember.find(Var);
643  if (Pos == InstantiatedFromStaticDataMember.end())
644    return 0;
645
646  return Pos->second;
647}
648
649void
650ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
651                                                TemplateSpecializationKind TSK,
652                                          SourceLocation PointOfInstantiation) {
653  assert(Inst->isStaticDataMember() && "Not a static data member");
654  assert(Tmpl->isStaticDataMember() && "Not a static data member");
655  assert(!InstantiatedFromStaticDataMember[Inst] &&
656         "Already noted what static data member was instantiated from");
657  InstantiatedFromStaticDataMember[Inst]
658    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
659}
660
661FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
662                                                     const FunctionDecl *FD){
663  assert(FD && "Specialization is 0");
664  llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
665    = ClassScopeSpecializationPattern.find(FD);
666  if (Pos == ClassScopeSpecializationPattern.end())
667    return 0;
668
669  return Pos->second;
670}
671
672void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
673                                        FunctionDecl *Pattern) {
674  assert(FD && "Specialization is 0");
675  assert(Pattern && "Class scope specialization pattern is 0");
676  ClassScopeSpecializationPattern[FD] = Pattern;
677}
678
679NamedDecl *
680ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
681  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
682    = InstantiatedFromUsingDecl.find(UUD);
683  if (Pos == InstantiatedFromUsingDecl.end())
684    return 0;
685
686  return Pos->second;
687}
688
689void
690ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
691  assert((isa<UsingDecl>(Pattern) ||
692          isa<UnresolvedUsingValueDecl>(Pattern) ||
693          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
694         "pattern decl is not a using decl");
695  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
696  InstantiatedFromUsingDecl[Inst] = Pattern;
697}
698
699UsingShadowDecl *
700ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
701  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
702    = InstantiatedFromUsingShadowDecl.find(Inst);
703  if (Pos == InstantiatedFromUsingShadowDecl.end())
704    return 0;
705
706  return Pos->second;
707}
708
709void
710ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
711                                               UsingShadowDecl *Pattern) {
712  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
713  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
714}
715
716FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
717  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
718    = InstantiatedFromUnnamedFieldDecl.find(Field);
719  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
720    return 0;
721
722  return Pos->second;
723}
724
725void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
726                                                     FieldDecl *Tmpl) {
727  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
728  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
729  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
730         "Already noted what unnamed field was instantiated from");
731
732  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
733}
734
735bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
736                                    const FieldDecl *LastFD) const {
737  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
738          FD->getBitWidthValue(*this) == 0);
739}
740
741bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
742                                             const FieldDecl *LastFD) const {
743  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
744          FD->getBitWidthValue(*this) == 0 &&
745          LastFD->getBitWidthValue(*this) != 0);
746}
747
748bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
749                                         const FieldDecl *LastFD) const {
750  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
751          FD->getBitWidthValue(*this) &&
752          LastFD->getBitWidthValue(*this));
753}
754
755bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
756                                         const FieldDecl *LastFD) const {
757  return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
758          LastFD->getBitWidthValue(*this));
759}
760
761bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
762                                             const FieldDecl *LastFD) const {
763  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
764          FD->getBitWidthValue(*this));
765}
766
767ASTContext::overridden_cxx_method_iterator
768ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
769  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
770    = OverriddenMethods.find(Method);
771  if (Pos == OverriddenMethods.end())
772    return 0;
773
774  return Pos->second.begin();
775}
776
777ASTContext::overridden_cxx_method_iterator
778ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
779  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
780    = OverriddenMethods.find(Method);
781  if (Pos == OverriddenMethods.end())
782    return 0;
783
784  return Pos->second.end();
785}
786
787unsigned
788ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
789  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
790    = OverriddenMethods.find(Method);
791  if (Pos == OverriddenMethods.end())
792    return 0;
793
794  return Pos->second.size();
795}
796
797void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
798                                     const CXXMethodDecl *Overridden) {
799  OverriddenMethods[Method].push_back(Overridden);
800}
801
802void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
803  assert(!Import->NextLocalImport && "Import declaration already in the chain");
804  assert(!Import->isFromASTFile() && "Non-local import declaration");
805  if (!FirstLocalImport) {
806    FirstLocalImport = Import;
807    LastLocalImport = Import;
808    return;
809  }
810
811  LastLocalImport->NextLocalImport = Import;
812  LastLocalImport = Import;
813}
814
815//===----------------------------------------------------------------------===//
816//                         Type Sizing and Analysis
817//===----------------------------------------------------------------------===//
818
819/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
820/// scalar floating point type.
821const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
822  const BuiltinType *BT = T->getAs<BuiltinType>();
823  assert(BT && "Not a floating point type!");
824  switch (BT->getKind()) {
825  default: llvm_unreachable("Not a floating point type!");
826  case BuiltinType::Half:       return Target->getHalfFormat();
827  case BuiltinType::Float:      return Target->getFloatFormat();
828  case BuiltinType::Double:     return Target->getDoubleFormat();
829  case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
830  }
831}
832
833/// getDeclAlign - Return a conservative estimate of the alignment of the
834/// specified decl.  Note that bitfields do not have a valid alignment, so
835/// this method will assert on them.
836/// If @p RefAsPointee, references are treated like their underlying type
837/// (for alignof), else they're treated like pointers (for CodeGen).
838CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
839  unsigned Align = Target->getCharWidth();
840
841  bool UseAlignAttrOnly = false;
842  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
843    Align = AlignFromAttr;
844
845    // __attribute__((aligned)) can increase or decrease alignment
846    // *except* on a struct or struct member, where it only increases
847    // alignment unless 'packed' is also specified.
848    //
849    // It is an error for alignas to decrease alignment, so we can
850    // ignore that possibility;  Sema should diagnose it.
851    if (isa<FieldDecl>(D)) {
852      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
853        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
854    } else {
855      UseAlignAttrOnly = true;
856    }
857  }
858  else if (isa<FieldDecl>(D))
859      UseAlignAttrOnly =
860        D->hasAttr<PackedAttr>() ||
861        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
862
863  // If we're using the align attribute only, just ignore everything
864  // else about the declaration and its type.
865  if (UseAlignAttrOnly) {
866    // do nothing
867
868  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
869    QualType T = VD->getType();
870    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
871      if (RefAsPointee)
872        T = RT->getPointeeType();
873      else
874        T = getPointerType(RT->getPointeeType());
875    }
876    if (!T->isIncompleteType() && !T->isFunctionType()) {
877      // Adjust alignments of declarations with array type by the
878      // large-array alignment on the target.
879      unsigned MinWidth = Target->getLargeArrayMinWidth();
880      const ArrayType *arrayType;
881      if (MinWidth && (arrayType = getAsArrayType(T))) {
882        if (isa<VariableArrayType>(arrayType))
883          Align = std::max(Align, Target->getLargeArrayAlign());
884        else if (isa<ConstantArrayType>(arrayType) &&
885                 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
886          Align = std::max(Align, Target->getLargeArrayAlign());
887
888        // Walk through any array types while we're at it.
889        T = getBaseElementType(arrayType);
890      }
891      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
892    }
893
894    // Fields can be subject to extra alignment constraints, like if
895    // the field is packed, the struct is packed, or the struct has a
896    // a max-field-alignment constraint (#pragma pack).  So calculate
897    // the actual alignment of the field within the struct, and then
898    // (as we're expected to) constrain that by the alignment of the type.
899    if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
900      // So calculate the alignment of the field.
901      const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
902
903      // Start with the record's overall alignment.
904      unsigned fieldAlign = toBits(layout.getAlignment());
905
906      // Use the GCD of that and the offset within the record.
907      uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
908      if (offset > 0) {
909        // Alignment is always a power of 2, so the GCD will be a power of 2,
910        // which means we get to do this crazy thing instead of Euclid's.
911        uint64_t lowBitOfOffset = offset & (~offset + 1);
912        if (lowBitOfOffset < fieldAlign)
913          fieldAlign = static_cast<unsigned>(lowBitOfOffset);
914      }
915
916      Align = std::min(Align, fieldAlign);
917    }
918  }
919
920  return toCharUnitsFromBits(Align);
921}
922
923std::pair<CharUnits, CharUnits>
924ASTContext::getTypeInfoInChars(const Type *T) const {
925  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
926  return std::make_pair(toCharUnitsFromBits(Info.first),
927                        toCharUnitsFromBits(Info.second));
928}
929
930std::pair<CharUnits, CharUnits>
931ASTContext::getTypeInfoInChars(QualType T) const {
932  return getTypeInfoInChars(T.getTypePtr());
933}
934
935std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
936  TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
937  if (it != MemoizedTypeInfo.end())
938    return it->second;
939
940  std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
941  MemoizedTypeInfo.insert(std::make_pair(T, Info));
942  return Info;
943}
944
945/// getTypeInfoImpl - Return the size of the specified type, in bits.  This
946/// method does not work on incomplete types.
947///
948/// FIXME: Pointers into different addr spaces could have different sizes and
949/// alignment requirements: getPointerInfo should take an AddrSpace, this
950/// should take a QualType, &c.
951std::pair<uint64_t, unsigned>
952ASTContext::getTypeInfoImpl(const Type *T) const {
953  uint64_t Width=0;
954  unsigned Align=8;
955  switch (T->getTypeClass()) {
956#define TYPE(Class, Base)
957#define ABSTRACT_TYPE(Class, Base)
958#define NON_CANONICAL_TYPE(Class, Base)
959#define DEPENDENT_TYPE(Class, Base) case Type::Class:
960#include "clang/AST/TypeNodes.def"
961    llvm_unreachable("Should not see dependent types");
962
963  case Type::FunctionNoProto:
964  case Type::FunctionProto:
965    // GCC extension: alignof(function) = 32 bits
966    Width = 0;
967    Align = 32;
968    break;
969
970  case Type::IncompleteArray:
971  case Type::VariableArray:
972    Width = 0;
973    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
974    break;
975
976  case Type::ConstantArray: {
977    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
978
979    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
980    uint64_t Size = CAT->getSize().getZExtValue();
981    assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
982           "Overflow in array type bit size evaluation");
983    Width = EltInfo.first*Size;
984    Align = EltInfo.second;
985    Width = llvm::RoundUpToAlignment(Width, Align);
986    break;
987  }
988  case Type::ExtVector:
989  case Type::Vector: {
990    const VectorType *VT = cast<VectorType>(T);
991    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
992    Width = EltInfo.first*VT->getNumElements();
993    Align = Width;
994    // If the alignment is not a power of 2, round up to the next power of 2.
995    // This happens for non-power-of-2 length vectors.
996    if (Align & (Align-1)) {
997      Align = llvm::NextPowerOf2(Align);
998      Width = llvm::RoundUpToAlignment(Width, Align);
999    }
1000    break;
1001  }
1002
1003  case Type::Builtin:
1004    switch (cast<BuiltinType>(T)->getKind()) {
1005    default: llvm_unreachable("Unknown builtin type!");
1006    case BuiltinType::Void:
1007      // GCC extension: alignof(void) = 8 bits.
1008      Width = 0;
1009      Align = 8;
1010      break;
1011
1012    case BuiltinType::Bool:
1013      Width = Target->getBoolWidth();
1014      Align = Target->getBoolAlign();
1015      break;
1016    case BuiltinType::Char_S:
1017    case BuiltinType::Char_U:
1018    case BuiltinType::UChar:
1019    case BuiltinType::SChar:
1020      Width = Target->getCharWidth();
1021      Align = Target->getCharAlign();
1022      break;
1023    case BuiltinType::WChar_S:
1024    case BuiltinType::WChar_U:
1025      Width = Target->getWCharWidth();
1026      Align = Target->getWCharAlign();
1027      break;
1028    case BuiltinType::Char16:
1029      Width = Target->getChar16Width();
1030      Align = Target->getChar16Align();
1031      break;
1032    case BuiltinType::Char32:
1033      Width = Target->getChar32Width();
1034      Align = Target->getChar32Align();
1035      break;
1036    case BuiltinType::UShort:
1037    case BuiltinType::Short:
1038      Width = Target->getShortWidth();
1039      Align = Target->getShortAlign();
1040      break;
1041    case BuiltinType::UInt:
1042    case BuiltinType::Int:
1043      Width = Target->getIntWidth();
1044      Align = Target->getIntAlign();
1045      break;
1046    case BuiltinType::ULong:
1047    case BuiltinType::Long:
1048      Width = Target->getLongWidth();
1049      Align = Target->getLongAlign();
1050      break;
1051    case BuiltinType::ULongLong:
1052    case BuiltinType::LongLong:
1053      Width = Target->getLongLongWidth();
1054      Align = Target->getLongLongAlign();
1055      break;
1056    case BuiltinType::Int128:
1057    case BuiltinType::UInt128:
1058      Width = 128;
1059      Align = 128; // int128_t is 128-bit aligned on all targets.
1060      break;
1061    case BuiltinType::Half:
1062      Width = Target->getHalfWidth();
1063      Align = Target->getHalfAlign();
1064      break;
1065    case BuiltinType::Float:
1066      Width = Target->getFloatWidth();
1067      Align = Target->getFloatAlign();
1068      break;
1069    case BuiltinType::Double:
1070      Width = Target->getDoubleWidth();
1071      Align = Target->getDoubleAlign();
1072      break;
1073    case BuiltinType::LongDouble:
1074      Width = Target->getLongDoubleWidth();
1075      Align = Target->getLongDoubleAlign();
1076      break;
1077    case BuiltinType::NullPtr:
1078      Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1079      Align = Target->getPointerAlign(0); //   == sizeof(void*)
1080      break;
1081    case BuiltinType::ObjCId:
1082    case BuiltinType::ObjCClass:
1083    case BuiltinType::ObjCSel:
1084      Width = Target->getPointerWidth(0);
1085      Align = Target->getPointerAlign(0);
1086      break;
1087    }
1088    break;
1089  case Type::ObjCObjectPointer:
1090    Width = Target->getPointerWidth(0);
1091    Align = Target->getPointerAlign(0);
1092    break;
1093  case Type::BlockPointer: {
1094    unsigned AS = getTargetAddressSpace(
1095        cast<BlockPointerType>(T)->getPointeeType());
1096    Width = Target->getPointerWidth(AS);
1097    Align = Target->getPointerAlign(AS);
1098    break;
1099  }
1100  case Type::LValueReference:
1101  case Type::RValueReference: {
1102    // alignof and sizeof should never enter this code path here, so we go
1103    // the pointer route.
1104    unsigned AS = getTargetAddressSpace(
1105        cast<ReferenceType>(T)->getPointeeType());
1106    Width = Target->getPointerWidth(AS);
1107    Align = Target->getPointerAlign(AS);
1108    break;
1109  }
1110  case Type::Pointer: {
1111    unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1112    Width = Target->getPointerWidth(AS);
1113    Align = Target->getPointerAlign(AS);
1114    break;
1115  }
1116  case Type::MemberPointer: {
1117    const MemberPointerType *MPT = cast<MemberPointerType>(T);
1118    std::pair<uint64_t, unsigned> PtrDiffInfo =
1119      getTypeInfo(getPointerDiffType());
1120    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
1121    Align = PtrDiffInfo.second;
1122    break;
1123  }
1124  case Type::Complex: {
1125    // Complex types have the same alignment as their elements, but twice the
1126    // size.
1127    std::pair<uint64_t, unsigned> EltInfo =
1128      getTypeInfo(cast<ComplexType>(T)->getElementType());
1129    Width = EltInfo.first*2;
1130    Align = EltInfo.second;
1131    break;
1132  }
1133  case Type::ObjCObject:
1134    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1135  case Type::ObjCInterface: {
1136    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1137    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1138    Width = toBits(Layout.getSize());
1139    Align = toBits(Layout.getAlignment());
1140    break;
1141  }
1142  case Type::Record:
1143  case Type::Enum: {
1144    const TagType *TT = cast<TagType>(T);
1145
1146    if (TT->getDecl()->isInvalidDecl()) {
1147      Width = 8;
1148      Align = 8;
1149      break;
1150    }
1151
1152    if (const EnumType *ET = dyn_cast<EnumType>(TT))
1153      return getTypeInfo(ET->getDecl()->getIntegerType());
1154
1155    const RecordType *RT = cast<RecordType>(TT);
1156    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1157    Width = toBits(Layout.getSize());
1158    Align = toBits(Layout.getAlignment());
1159    break;
1160  }
1161
1162  case Type::SubstTemplateTypeParm:
1163    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1164                       getReplacementType().getTypePtr());
1165
1166  case Type::Auto: {
1167    const AutoType *A = cast<AutoType>(T);
1168    assert(A->isDeduced() && "Cannot request the size of a dependent type");
1169    return getTypeInfo(A->getDeducedType().getTypePtr());
1170  }
1171
1172  case Type::Paren:
1173    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1174
1175  case Type::Typedef: {
1176    const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1177    std::pair<uint64_t, unsigned> Info
1178      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1179    // If the typedef has an aligned attribute on it, it overrides any computed
1180    // alignment we have.  This violates the GCC documentation (which says that
1181    // attribute(aligned) can only round up) but matches its implementation.
1182    if (unsigned AttrAlign = Typedef->getMaxAlignment())
1183      Align = AttrAlign;
1184    else
1185      Align = Info.second;
1186    Width = Info.first;
1187    break;
1188  }
1189
1190  case Type::TypeOfExpr:
1191    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1192                         .getTypePtr());
1193
1194  case Type::TypeOf:
1195    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1196
1197  case Type::Decltype:
1198    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1199                        .getTypePtr());
1200
1201  case Type::UnaryTransform:
1202    return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1203
1204  case Type::Elaborated:
1205    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1206
1207  case Type::Attributed:
1208    return getTypeInfo(
1209                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1210
1211  case Type::TemplateSpecialization: {
1212    assert(getCanonicalType(T) != T &&
1213           "Cannot request the size of a dependent type");
1214    const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1215    // A type alias template specialization may refer to a typedef with the
1216    // aligned attribute on it.
1217    if (TST->isTypeAlias())
1218      return getTypeInfo(TST->getAliasedType().getTypePtr());
1219    else
1220      return getTypeInfo(getCanonicalType(T));
1221  }
1222
1223  case Type::Atomic: {
1224    std::pair<uint64_t, unsigned> Info
1225      = getTypeInfo(cast<AtomicType>(T)->getValueType());
1226    Width = Info.first;
1227    Align = Info.second;
1228    if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1229        llvm::isPowerOf2_64(Width)) {
1230      // We can potentially perform lock-free atomic operations for this
1231      // type; promote the alignment appropriately.
1232      // FIXME: We could potentially promote the width here as well...
1233      // is that worthwhile?  (Non-struct atomic types generally have
1234      // power-of-two size anyway, but structs might not.  Requires a bit
1235      // of implementation work to make sure we zero out the extra bits.)
1236      Align = static_cast<unsigned>(Width);
1237    }
1238  }
1239
1240  }
1241
1242  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1243  return std::make_pair(Width, Align);
1244}
1245
1246/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1247CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1248  return CharUnits::fromQuantity(BitSize / getCharWidth());
1249}
1250
1251/// toBits - Convert a size in characters to a size in characters.
1252int64_t ASTContext::toBits(CharUnits CharSize) const {
1253  return CharSize.getQuantity() * getCharWidth();
1254}
1255
1256/// getTypeSizeInChars - Return the size of the specified type, in characters.
1257/// This method does not work on incomplete types.
1258CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1259  return toCharUnitsFromBits(getTypeSize(T));
1260}
1261CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1262  return toCharUnitsFromBits(getTypeSize(T));
1263}
1264
1265/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1266/// characters. This method does not work on incomplete types.
1267CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1268  return toCharUnitsFromBits(getTypeAlign(T));
1269}
1270CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1271  return toCharUnitsFromBits(getTypeAlign(T));
1272}
1273
1274/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1275/// type for the current target in bits.  This can be different than the ABI
1276/// alignment in cases where it is beneficial for performance to overalign
1277/// a data type.
1278unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1279  unsigned ABIAlign = getTypeAlign(T);
1280
1281  // Double and long long should be naturally aligned if possible.
1282  if (const ComplexType* CT = T->getAs<ComplexType>())
1283    T = CT->getElementType().getTypePtr();
1284  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1285      T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1286      T->isSpecificBuiltinType(BuiltinType::ULongLong))
1287    return std::max(ABIAlign, (unsigned)getTypeSize(T));
1288
1289  return ABIAlign;
1290}
1291
1292/// DeepCollectObjCIvars -
1293/// This routine first collects all declared, but not synthesized, ivars in
1294/// super class and then collects all ivars, including those synthesized for
1295/// current class. This routine is used for implementation of current class
1296/// when all ivars, declared and synthesized are known.
1297///
1298void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1299                                      bool leafClass,
1300                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1301  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1302    DeepCollectObjCIvars(SuperClass, false, Ivars);
1303  if (!leafClass) {
1304    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1305         E = OI->ivar_end(); I != E; ++I)
1306      Ivars.push_back(*I);
1307  } else {
1308    ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1309    for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1310         Iv= Iv->getNextIvar())
1311      Ivars.push_back(Iv);
1312  }
1313}
1314
1315/// CollectInheritedProtocols - Collect all protocols in current class and
1316/// those inherited by it.
1317void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1318                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1319  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1320    // We can use protocol_iterator here instead of
1321    // all_referenced_protocol_iterator since we are walking all categories.
1322    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1323         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1324      ObjCProtocolDecl *Proto = (*P);
1325      Protocols.insert(Proto->getCanonicalDecl());
1326      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1327           PE = Proto->protocol_end(); P != PE; ++P) {
1328        Protocols.insert((*P)->getCanonicalDecl());
1329        CollectInheritedProtocols(*P, Protocols);
1330      }
1331    }
1332
1333    // Categories of this Interface.
1334    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1335         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1336      CollectInheritedProtocols(CDeclChain, Protocols);
1337    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1338      while (SD) {
1339        CollectInheritedProtocols(SD, Protocols);
1340        SD = SD->getSuperClass();
1341      }
1342  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1343    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1344         PE = OC->protocol_end(); P != PE; ++P) {
1345      ObjCProtocolDecl *Proto = (*P);
1346      Protocols.insert(Proto->getCanonicalDecl());
1347      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1348           PE = Proto->protocol_end(); P != PE; ++P)
1349        CollectInheritedProtocols(*P, Protocols);
1350    }
1351  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1352    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1353         PE = OP->protocol_end(); P != PE; ++P) {
1354      ObjCProtocolDecl *Proto = (*P);
1355      Protocols.insert(Proto->getCanonicalDecl());
1356      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1357           PE = Proto->protocol_end(); P != PE; ++P)
1358        CollectInheritedProtocols(*P, Protocols);
1359    }
1360  }
1361}
1362
1363unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1364  unsigned count = 0;
1365  // Count ivars declared in class extension.
1366  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1367       CDecl = CDecl->getNextClassExtension())
1368    count += CDecl->ivar_size();
1369
1370  // Count ivar defined in this class's implementation.  This
1371  // includes synthesized ivars.
1372  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1373    count += ImplDecl->ivar_size();
1374
1375  return count;
1376}
1377
1378bool ASTContext::isSentinelNullExpr(const Expr *E) {
1379  if (!E)
1380    return false;
1381
1382  // nullptr_t is always treated as null.
1383  if (E->getType()->isNullPtrType()) return true;
1384
1385  if (E->getType()->isAnyPointerType() &&
1386      E->IgnoreParenCasts()->isNullPointerConstant(*this,
1387                                                Expr::NPC_ValueDependentIsNull))
1388    return true;
1389
1390  // Unfortunately, __null has type 'int'.
1391  if (isa<GNUNullExpr>(E)) return true;
1392
1393  return false;
1394}
1395
1396/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1397ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1398  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1399    I = ObjCImpls.find(D);
1400  if (I != ObjCImpls.end())
1401    return cast<ObjCImplementationDecl>(I->second);
1402  return 0;
1403}
1404/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1405ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1406  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1407    I = ObjCImpls.find(D);
1408  if (I != ObjCImpls.end())
1409    return cast<ObjCCategoryImplDecl>(I->second);
1410  return 0;
1411}
1412
1413/// \brief Set the implementation of ObjCInterfaceDecl.
1414void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1415                           ObjCImplementationDecl *ImplD) {
1416  assert(IFaceD && ImplD && "Passed null params");
1417  ObjCImpls[IFaceD] = ImplD;
1418}
1419/// \brief Set the implementation of ObjCCategoryDecl.
1420void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1421                           ObjCCategoryImplDecl *ImplD) {
1422  assert(CatD && ImplD && "Passed null params");
1423  ObjCImpls[CatD] = ImplD;
1424}
1425
1426ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1427  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1428    return ID;
1429  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1430    return CD->getClassInterface();
1431  if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1432    return IMD->getClassInterface();
1433
1434  return 0;
1435}
1436
1437/// \brief Get the copy initialization expression of VarDecl,or NULL if
1438/// none exists.
1439Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1440  assert(VD && "Passed null params");
1441  assert(VD->hasAttr<BlocksAttr>() &&
1442         "getBlockVarCopyInits - not __block var");
1443  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1444    I = BlockVarCopyInits.find(VD);
1445  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1446}
1447
1448/// \brief Set the copy inialization expression of a block var decl.
1449void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1450  assert(VD && Init && "Passed null params");
1451  assert(VD->hasAttr<BlocksAttr>() &&
1452         "setBlockVarCopyInits - not __block var");
1453  BlockVarCopyInits[VD] = Init;
1454}
1455
1456TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1457                                                 unsigned DataSize) const {
1458  if (!DataSize)
1459    DataSize = TypeLoc::getFullDataSizeForType(T);
1460  else
1461    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1462           "incorrect data size provided to CreateTypeSourceInfo!");
1463
1464  TypeSourceInfo *TInfo =
1465    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1466  new (TInfo) TypeSourceInfo(T);
1467  return TInfo;
1468}
1469
1470TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1471                                                     SourceLocation L) const {
1472  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1473  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1474  return DI;
1475}
1476
1477const ASTRecordLayout &
1478ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1479  return getObjCLayout(D, 0);
1480}
1481
1482const ASTRecordLayout &
1483ASTContext::getASTObjCImplementationLayout(
1484                                        const ObjCImplementationDecl *D) const {
1485  return getObjCLayout(D->getClassInterface(), D);
1486}
1487
1488//===----------------------------------------------------------------------===//
1489//                   Type creation/memoization methods
1490//===----------------------------------------------------------------------===//
1491
1492QualType
1493ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1494  unsigned fastQuals = quals.getFastQualifiers();
1495  quals.removeFastQualifiers();
1496
1497  // Check if we've already instantiated this type.
1498  llvm::FoldingSetNodeID ID;
1499  ExtQuals::Profile(ID, baseType, quals);
1500  void *insertPos = 0;
1501  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1502    assert(eq->getQualifiers() == quals);
1503    return QualType(eq, fastQuals);
1504  }
1505
1506  // If the base type is not canonical, make the appropriate canonical type.
1507  QualType canon;
1508  if (!baseType->isCanonicalUnqualified()) {
1509    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1510    canonSplit.Quals.addConsistentQualifiers(quals);
1511    canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
1512
1513    // Re-find the insert position.
1514    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1515  }
1516
1517  ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1518  ExtQualNodes.InsertNode(eq, insertPos);
1519  return QualType(eq, fastQuals);
1520}
1521
1522QualType
1523ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1524  QualType CanT = getCanonicalType(T);
1525  if (CanT.getAddressSpace() == AddressSpace)
1526    return T;
1527
1528  // If we are composing extended qualifiers together, merge together
1529  // into one ExtQuals node.
1530  QualifierCollector Quals;
1531  const Type *TypeNode = Quals.strip(T);
1532
1533  // If this type already has an address space specified, it cannot get
1534  // another one.
1535  assert(!Quals.hasAddressSpace() &&
1536         "Type cannot be in multiple addr spaces!");
1537  Quals.addAddressSpace(AddressSpace);
1538
1539  return getExtQualType(TypeNode, Quals);
1540}
1541
1542QualType ASTContext::getObjCGCQualType(QualType T,
1543                                       Qualifiers::GC GCAttr) const {
1544  QualType CanT = getCanonicalType(T);
1545  if (CanT.getObjCGCAttr() == GCAttr)
1546    return T;
1547
1548  if (const PointerType *ptr = T->getAs<PointerType>()) {
1549    QualType Pointee = ptr->getPointeeType();
1550    if (Pointee->isAnyPointerType()) {
1551      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1552      return getPointerType(ResultType);
1553    }
1554  }
1555
1556  // If we are composing extended qualifiers together, merge together
1557  // into one ExtQuals node.
1558  QualifierCollector Quals;
1559  const Type *TypeNode = Quals.strip(T);
1560
1561  // If this type already has an ObjCGC specified, it cannot get
1562  // another one.
1563  assert(!Quals.hasObjCGCAttr() &&
1564         "Type cannot have multiple ObjCGCs!");
1565  Quals.addObjCGCAttr(GCAttr);
1566
1567  return getExtQualType(TypeNode, Quals);
1568}
1569
1570const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1571                                                   FunctionType::ExtInfo Info) {
1572  if (T->getExtInfo() == Info)
1573    return T;
1574
1575  QualType Result;
1576  if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1577    Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1578  } else {
1579    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1580    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1581    EPI.ExtInfo = Info;
1582    Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1583                             FPT->getNumArgs(), EPI);
1584  }
1585
1586  return cast<FunctionType>(Result.getTypePtr());
1587}
1588
1589/// getComplexType - Return the uniqued reference to the type for a complex
1590/// number with the specified element type.
1591QualType ASTContext::getComplexType(QualType T) const {
1592  // Unique pointers, to guarantee there is only one pointer of a particular
1593  // structure.
1594  llvm::FoldingSetNodeID ID;
1595  ComplexType::Profile(ID, T);
1596
1597  void *InsertPos = 0;
1598  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1599    return QualType(CT, 0);
1600
1601  // If the pointee type isn't canonical, this won't be a canonical type either,
1602  // so fill in the canonical type field.
1603  QualType Canonical;
1604  if (!T.isCanonical()) {
1605    Canonical = getComplexType(getCanonicalType(T));
1606
1607    // Get the new insert position for the node we care about.
1608    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1609    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1610  }
1611  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1612  Types.push_back(New);
1613  ComplexTypes.InsertNode(New, InsertPos);
1614  return QualType(New, 0);
1615}
1616
1617/// getPointerType - Return the uniqued reference to the type for a pointer to
1618/// the specified type.
1619QualType ASTContext::getPointerType(QualType T) const {
1620  // Unique pointers, to guarantee there is only one pointer of a particular
1621  // structure.
1622  llvm::FoldingSetNodeID ID;
1623  PointerType::Profile(ID, T);
1624
1625  void *InsertPos = 0;
1626  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1627    return QualType(PT, 0);
1628
1629  // If the pointee type isn't canonical, this won't be a canonical type either,
1630  // so fill in the canonical type field.
1631  QualType Canonical;
1632  if (!T.isCanonical()) {
1633    Canonical = getPointerType(getCanonicalType(T));
1634
1635    // Get the new insert position for the node we care about.
1636    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1637    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1638  }
1639  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1640  Types.push_back(New);
1641  PointerTypes.InsertNode(New, InsertPos);
1642  return QualType(New, 0);
1643}
1644
1645/// getBlockPointerType - Return the uniqued reference to the type for
1646/// a pointer to the specified block.
1647QualType ASTContext::getBlockPointerType(QualType T) const {
1648  assert(T->isFunctionType() && "block of function types only");
1649  // Unique pointers, to guarantee there is only one block of a particular
1650  // structure.
1651  llvm::FoldingSetNodeID ID;
1652  BlockPointerType::Profile(ID, T);
1653
1654  void *InsertPos = 0;
1655  if (BlockPointerType *PT =
1656        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1657    return QualType(PT, 0);
1658
1659  // If the block pointee type isn't canonical, this won't be a canonical
1660  // type either so fill in the canonical type field.
1661  QualType Canonical;
1662  if (!T.isCanonical()) {
1663    Canonical = getBlockPointerType(getCanonicalType(T));
1664
1665    // Get the new insert position for the node we care about.
1666    BlockPointerType *NewIP =
1667      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1668    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1669  }
1670  BlockPointerType *New
1671    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1672  Types.push_back(New);
1673  BlockPointerTypes.InsertNode(New, InsertPos);
1674  return QualType(New, 0);
1675}
1676
1677/// getLValueReferenceType - Return the uniqued reference to the type for an
1678/// lvalue reference to the specified type.
1679QualType
1680ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1681  assert(getCanonicalType(T) != OverloadTy &&
1682         "Unresolved overloaded function type");
1683
1684  // Unique pointers, to guarantee there is only one pointer of a particular
1685  // structure.
1686  llvm::FoldingSetNodeID ID;
1687  ReferenceType::Profile(ID, T, SpelledAsLValue);
1688
1689  void *InsertPos = 0;
1690  if (LValueReferenceType *RT =
1691        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1692    return QualType(RT, 0);
1693
1694  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1695
1696  // If the referencee type isn't canonical, this won't be a canonical type
1697  // either, so fill in the canonical type field.
1698  QualType Canonical;
1699  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1700    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1701    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1702
1703    // Get the new insert position for the node we care about.
1704    LValueReferenceType *NewIP =
1705      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1706    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1707  }
1708
1709  LValueReferenceType *New
1710    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1711                                                     SpelledAsLValue);
1712  Types.push_back(New);
1713  LValueReferenceTypes.InsertNode(New, InsertPos);
1714
1715  return QualType(New, 0);
1716}
1717
1718/// getRValueReferenceType - Return the uniqued reference to the type for an
1719/// rvalue reference to the specified type.
1720QualType ASTContext::getRValueReferenceType(QualType T) const {
1721  // Unique pointers, to guarantee there is only one pointer of a particular
1722  // structure.
1723  llvm::FoldingSetNodeID ID;
1724  ReferenceType::Profile(ID, T, false);
1725
1726  void *InsertPos = 0;
1727  if (RValueReferenceType *RT =
1728        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1729    return QualType(RT, 0);
1730
1731  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1732
1733  // If the referencee type isn't canonical, this won't be a canonical type
1734  // either, so fill in the canonical type field.
1735  QualType Canonical;
1736  if (InnerRef || !T.isCanonical()) {
1737    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1738    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1739
1740    // Get the new insert position for the node we care about.
1741    RValueReferenceType *NewIP =
1742      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1743    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1744  }
1745
1746  RValueReferenceType *New
1747    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1748  Types.push_back(New);
1749  RValueReferenceTypes.InsertNode(New, InsertPos);
1750  return QualType(New, 0);
1751}
1752
1753/// getMemberPointerType - Return the uniqued reference to the type for a
1754/// member pointer to the specified type, in the specified class.
1755QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1756  // Unique pointers, to guarantee there is only one pointer of a particular
1757  // structure.
1758  llvm::FoldingSetNodeID ID;
1759  MemberPointerType::Profile(ID, T, Cls);
1760
1761  void *InsertPos = 0;
1762  if (MemberPointerType *PT =
1763      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1764    return QualType(PT, 0);
1765
1766  // If the pointee or class type isn't canonical, this won't be a canonical
1767  // type either, so fill in the canonical type field.
1768  QualType Canonical;
1769  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1770    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1771
1772    // Get the new insert position for the node we care about.
1773    MemberPointerType *NewIP =
1774      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1775    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1776  }
1777  MemberPointerType *New
1778    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1779  Types.push_back(New);
1780  MemberPointerTypes.InsertNode(New, InsertPos);
1781  return QualType(New, 0);
1782}
1783
1784/// getConstantArrayType - Return the unique reference to the type for an
1785/// array of the specified element type.
1786QualType ASTContext::getConstantArrayType(QualType EltTy,
1787                                          const llvm::APInt &ArySizeIn,
1788                                          ArrayType::ArraySizeModifier ASM,
1789                                          unsigned IndexTypeQuals) const {
1790  assert((EltTy->isDependentType() ||
1791          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1792         "Constant array of VLAs is illegal!");
1793
1794  // Convert the array size into a canonical width matching the pointer size for
1795  // the target.
1796  llvm::APInt ArySize(ArySizeIn);
1797  ArySize =
1798    ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
1799
1800  llvm::FoldingSetNodeID ID;
1801  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1802
1803  void *InsertPos = 0;
1804  if (ConstantArrayType *ATP =
1805      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1806    return QualType(ATP, 0);
1807
1808  // If the element type isn't canonical or has qualifiers, this won't
1809  // be a canonical type either, so fill in the canonical type field.
1810  QualType Canon;
1811  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1812    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1813    Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
1814                                 ASM, IndexTypeQuals);
1815    Canon = getQualifiedType(Canon, canonSplit.Quals);
1816
1817    // Get the new insert position for the node we care about.
1818    ConstantArrayType *NewIP =
1819      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1820    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1821  }
1822
1823  ConstantArrayType *New = new(*this,TypeAlignment)
1824    ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1825  ConstantArrayTypes.InsertNode(New, InsertPos);
1826  Types.push_back(New);
1827  return QualType(New, 0);
1828}
1829
1830/// getVariableArrayDecayedType - Turns the given type, which may be
1831/// variably-modified, into the corresponding type with all the known
1832/// sizes replaced with [*].
1833QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1834  // Vastly most common case.
1835  if (!type->isVariablyModifiedType()) return type;
1836
1837  QualType result;
1838
1839  SplitQualType split = type.getSplitDesugaredType();
1840  const Type *ty = split.Ty;
1841  switch (ty->getTypeClass()) {
1842#define TYPE(Class, Base)
1843#define ABSTRACT_TYPE(Class, Base)
1844#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1845#include "clang/AST/TypeNodes.def"
1846    llvm_unreachable("didn't desugar past all non-canonical types?");
1847
1848  // These types should never be variably-modified.
1849  case Type::Builtin:
1850  case Type::Complex:
1851  case Type::Vector:
1852  case Type::ExtVector:
1853  case Type::DependentSizedExtVector:
1854  case Type::ObjCObject:
1855  case Type::ObjCInterface:
1856  case Type::ObjCObjectPointer:
1857  case Type::Record:
1858  case Type::Enum:
1859  case Type::UnresolvedUsing:
1860  case Type::TypeOfExpr:
1861  case Type::TypeOf:
1862  case Type::Decltype:
1863  case Type::UnaryTransform:
1864  case Type::DependentName:
1865  case Type::InjectedClassName:
1866  case Type::TemplateSpecialization:
1867  case Type::DependentTemplateSpecialization:
1868  case Type::TemplateTypeParm:
1869  case Type::SubstTemplateTypeParmPack:
1870  case Type::Auto:
1871  case Type::PackExpansion:
1872    llvm_unreachable("type should never be variably-modified");
1873
1874  // These types can be variably-modified but should never need to
1875  // further decay.
1876  case Type::FunctionNoProto:
1877  case Type::FunctionProto:
1878  case Type::BlockPointer:
1879  case Type::MemberPointer:
1880    return type;
1881
1882  // These types can be variably-modified.  All these modifications
1883  // preserve structure except as noted by comments.
1884  // TODO: if we ever care about optimizing VLAs, there are no-op
1885  // optimizations available here.
1886  case Type::Pointer:
1887    result = getPointerType(getVariableArrayDecayedType(
1888                              cast<PointerType>(ty)->getPointeeType()));
1889    break;
1890
1891  case Type::LValueReference: {
1892    const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1893    result = getLValueReferenceType(
1894                 getVariableArrayDecayedType(lv->getPointeeType()),
1895                                    lv->isSpelledAsLValue());
1896    break;
1897  }
1898
1899  case Type::RValueReference: {
1900    const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1901    result = getRValueReferenceType(
1902                 getVariableArrayDecayedType(lv->getPointeeType()));
1903    break;
1904  }
1905
1906  case Type::Atomic: {
1907    const AtomicType *at = cast<AtomicType>(ty);
1908    result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1909    break;
1910  }
1911
1912  case Type::ConstantArray: {
1913    const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1914    result = getConstantArrayType(
1915                 getVariableArrayDecayedType(cat->getElementType()),
1916                                  cat->getSize(),
1917                                  cat->getSizeModifier(),
1918                                  cat->getIndexTypeCVRQualifiers());
1919    break;
1920  }
1921
1922  case Type::DependentSizedArray: {
1923    const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1924    result = getDependentSizedArrayType(
1925                 getVariableArrayDecayedType(dat->getElementType()),
1926                                        dat->getSizeExpr(),
1927                                        dat->getSizeModifier(),
1928                                        dat->getIndexTypeCVRQualifiers(),
1929                                        dat->getBracketsRange());
1930    break;
1931  }
1932
1933  // Turn incomplete types into [*] types.
1934  case Type::IncompleteArray: {
1935    const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1936    result = getVariableArrayType(
1937                 getVariableArrayDecayedType(iat->getElementType()),
1938                                  /*size*/ 0,
1939                                  ArrayType::Normal,
1940                                  iat->getIndexTypeCVRQualifiers(),
1941                                  SourceRange());
1942    break;
1943  }
1944
1945  // Turn VLA types into [*] types.
1946  case Type::VariableArray: {
1947    const VariableArrayType *vat = cast<VariableArrayType>(ty);
1948    result = getVariableArrayType(
1949                 getVariableArrayDecayedType(vat->getElementType()),
1950                                  /*size*/ 0,
1951                                  ArrayType::Star,
1952                                  vat->getIndexTypeCVRQualifiers(),
1953                                  vat->getBracketsRange());
1954    break;
1955  }
1956  }
1957
1958  // Apply the top-level qualifiers from the original.
1959  return getQualifiedType(result, split.Quals);
1960}
1961
1962/// getVariableArrayType - Returns a non-unique reference to the type for a
1963/// variable array of the specified element type.
1964QualType ASTContext::getVariableArrayType(QualType EltTy,
1965                                          Expr *NumElts,
1966                                          ArrayType::ArraySizeModifier ASM,
1967                                          unsigned IndexTypeQuals,
1968                                          SourceRange Brackets) const {
1969  // Since we don't unique expressions, it isn't possible to unique VLA's
1970  // that have an expression provided for their size.
1971  QualType Canon;
1972
1973  // Be sure to pull qualifiers off the element type.
1974  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1975    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1976    Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
1977                                 IndexTypeQuals, Brackets);
1978    Canon = getQualifiedType(Canon, canonSplit.Quals);
1979  }
1980
1981  VariableArrayType *New = new(*this, TypeAlignment)
1982    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1983
1984  VariableArrayTypes.push_back(New);
1985  Types.push_back(New);
1986  return QualType(New, 0);
1987}
1988
1989/// getDependentSizedArrayType - Returns a non-unique reference to
1990/// the type for a dependently-sized array of the specified element
1991/// type.
1992QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1993                                                Expr *numElements,
1994                                                ArrayType::ArraySizeModifier ASM,
1995                                                unsigned elementTypeQuals,
1996                                                SourceRange brackets) const {
1997  assert((!numElements || numElements->isTypeDependent() ||
1998          numElements->isValueDependent()) &&
1999         "Size must be type- or value-dependent!");
2000
2001  // Dependently-sized array types that do not have a specified number
2002  // of elements will have their sizes deduced from a dependent
2003  // initializer.  We do no canonicalization here at all, which is okay
2004  // because they can't be used in most locations.
2005  if (!numElements) {
2006    DependentSizedArrayType *newType
2007      = new (*this, TypeAlignment)
2008          DependentSizedArrayType(*this, elementType, QualType(),
2009                                  numElements, ASM, elementTypeQuals,
2010                                  brackets);
2011    Types.push_back(newType);
2012    return QualType(newType, 0);
2013  }
2014
2015  // Otherwise, we actually build a new type every time, but we
2016  // also build a canonical type.
2017
2018  SplitQualType canonElementType = getCanonicalType(elementType).split();
2019
2020  void *insertPos = 0;
2021  llvm::FoldingSetNodeID ID;
2022  DependentSizedArrayType::Profile(ID, *this,
2023                                   QualType(canonElementType.Ty, 0),
2024                                   ASM, elementTypeQuals, numElements);
2025
2026  // Look for an existing type with these properties.
2027  DependentSizedArrayType *canonTy =
2028    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2029
2030  // If we don't have one, build one.
2031  if (!canonTy) {
2032    canonTy = new (*this, TypeAlignment)
2033      DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2034                              QualType(), numElements, ASM, elementTypeQuals,
2035                              brackets);
2036    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2037    Types.push_back(canonTy);
2038  }
2039
2040  // Apply qualifiers from the element type to the array.
2041  QualType canon = getQualifiedType(QualType(canonTy,0),
2042                                    canonElementType.Quals);
2043
2044  // If we didn't need extra canonicalization for the element type,
2045  // then just use that as our result.
2046  if (QualType(canonElementType.Ty, 0) == elementType)
2047    return canon;
2048
2049  // Otherwise, we need to build a type which follows the spelling
2050  // of the element type.
2051  DependentSizedArrayType *sugaredType
2052    = new (*this, TypeAlignment)
2053        DependentSizedArrayType(*this, elementType, canon, numElements,
2054                                ASM, elementTypeQuals, brackets);
2055  Types.push_back(sugaredType);
2056  return QualType(sugaredType, 0);
2057}
2058
2059QualType ASTContext::getIncompleteArrayType(QualType elementType,
2060                                            ArrayType::ArraySizeModifier ASM,
2061                                            unsigned elementTypeQuals) const {
2062  llvm::FoldingSetNodeID ID;
2063  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2064
2065  void *insertPos = 0;
2066  if (IncompleteArrayType *iat =
2067       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2068    return QualType(iat, 0);
2069
2070  // If the element type isn't canonical, this won't be a canonical type
2071  // either, so fill in the canonical type field.  We also have to pull
2072  // qualifiers off the element type.
2073  QualType canon;
2074
2075  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2076    SplitQualType canonSplit = getCanonicalType(elementType).split();
2077    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2078                                   ASM, elementTypeQuals);
2079    canon = getQualifiedType(canon, canonSplit.Quals);
2080
2081    // Get the new insert position for the node we care about.
2082    IncompleteArrayType *existing =
2083      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2084    assert(!existing && "Shouldn't be in the map!"); (void) existing;
2085  }
2086
2087  IncompleteArrayType *newType = new (*this, TypeAlignment)
2088    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2089
2090  IncompleteArrayTypes.InsertNode(newType, insertPos);
2091  Types.push_back(newType);
2092  return QualType(newType, 0);
2093}
2094
2095/// getVectorType - Return the unique reference to a vector type of
2096/// the specified element type and size. VectorType must be a built-in type.
2097QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2098                                   VectorType::VectorKind VecKind) const {
2099  assert(vecType->isBuiltinType());
2100
2101  // Check if we've already instantiated a vector of this type.
2102  llvm::FoldingSetNodeID ID;
2103  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2104
2105  void *InsertPos = 0;
2106  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2107    return QualType(VTP, 0);
2108
2109  // If the element type isn't canonical, this won't be a canonical type either,
2110  // so fill in the canonical type field.
2111  QualType Canonical;
2112  if (!vecType.isCanonical()) {
2113    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2114
2115    // Get the new insert position for the node we care about.
2116    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2117    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2118  }
2119  VectorType *New = new (*this, TypeAlignment)
2120    VectorType(vecType, NumElts, Canonical, VecKind);
2121  VectorTypes.InsertNode(New, InsertPos);
2122  Types.push_back(New);
2123  return QualType(New, 0);
2124}
2125
2126/// getExtVectorType - Return the unique reference to an extended vector type of
2127/// the specified element type and size. VectorType must be a built-in type.
2128QualType
2129ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2130  assert(vecType->isBuiltinType() || vecType->isDependentType());
2131
2132  // Check if we've already instantiated a vector of this type.
2133  llvm::FoldingSetNodeID ID;
2134  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2135                      VectorType::GenericVector);
2136  void *InsertPos = 0;
2137  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2138    return QualType(VTP, 0);
2139
2140  // If the element type isn't canonical, this won't be a canonical type either,
2141  // so fill in the canonical type field.
2142  QualType Canonical;
2143  if (!vecType.isCanonical()) {
2144    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2145
2146    // Get the new insert position for the node we care about.
2147    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2148    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2149  }
2150  ExtVectorType *New = new (*this, TypeAlignment)
2151    ExtVectorType(vecType, NumElts, Canonical);
2152  VectorTypes.InsertNode(New, InsertPos);
2153  Types.push_back(New);
2154  return QualType(New, 0);
2155}
2156
2157QualType
2158ASTContext::getDependentSizedExtVectorType(QualType vecType,
2159                                           Expr *SizeExpr,
2160                                           SourceLocation AttrLoc) const {
2161  llvm::FoldingSetNodeID ID;
2162  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2163                                       SizeExpr);
2164
2165  void *InsertPos = 0;
2166  DependentSizedExtVectorType *Canon
2167    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2168  DependentSizedExtVectorType *New;
2169  if (Canon) {
2170    // We already have a canonical version of this array type; use it as
2171    // the canonical type for a newly-built type.
2172    New = new (*this, TypeAlignment)
2173      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2174                                  SizeExpr, AttrLoc);
2175  } else {
2176    QualType CanonVecTy = getCanonicalType(vecType);
2177    if (CanonVecTy == vecType) {
2178      New = new (*this, TypeAlignment)
2179        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2180                                    AttrLoc);
2181
2182      DependentSizedExtVectorType *CanonCheck
2183        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2184      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2185      (void)CanonCheck;
2186      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2187    } else {
2188      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2189                                                      SourceLocation());
2190      New = new (*this, TypeAlignment)
2191        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2192    }
2193  }
2194
2195  Types.push_back(New);
2196  return QualType(New, 0);
2197}
2198
2199/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2200///
2201QualType
2202ASTContext::getFunctionNoProtoType(QualType ResultTy,
2203                                   const FunctionType::ExtInfo &Info) const {
2204  const CallingConv DefaultCC = Info.getCC();
2205  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2206                               CC_X86StdCall : DefaultCC;
2207  // Unique functions, to guarantee there is only one function of a particular
2208  // structure.
2209  llvm::FoldingSetNodeID ID;
2210  FunctionNoProtoType::Profile(ID, ResultTy, Info);
2211
2212  void *InsertPos = 0;
2213  if (FunctionNoProtoType *FT =
2214        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2215    return QualType(FT, 0);
2216
2217  QualType Canonical;
2218  if (!ResultTy.isCanonical() ||
2219      getCanonicalCallConv(CallConv) != CallConv) {
2220    Canonical =
2221      getFunctionNoProtoType(getCanonicalType(ResultTy),
2222                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
2223
2224    // Get the new insert position for the node we care about.
2225    FunctionNoProtoType *NewIP =
2226      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2227    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2228  }
2229
2230  FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2231  FunctionNoProtoType *New = new (*this, TypeAlignment)
2232    FunctionNoProtoType(ResultTy, Canonical, newInfo);
2233  Types.push_back(New);
2234  FunctionNoProtoTypes.InsertNode(New, InsertPos);
2235  return QualType(New, 0);
2236}
2237
2238/// getFunctionType - Return a normal function type with a typed argument
2239/// list.  isVariadic indicates whether the argument list includes '...'.
2240QualType
2241ASTContext::getFunctionType(QualType ResultTy,
2242                            const QualType *ArgArray, unsigned NumArgs,
2243                            const FunctionProtoType::ExtProtoInfo &EPI) const {
2244  // Unique functions, to guarantee there is only one function of a particular
2245  // structure.
2246  llvm::FoldingSetNodeID ID;
2247  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2248
2249  void *InsertPos = 0;
2250  if (FunctionProtoType *FTP =
2251        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2252    return QualType(FTP, 0);
2253
2254  // Determine whether the type being created is already canonical or not.
2255  bool isCanonical =
2256    EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2257    !EPI.HasTrailingReturn;
2258  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2259    if (!ArgArray[i].isCanonicalAsParam())
2260      isCanonical = false;
2261
2262  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2263  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2264                               CC_X86StdCall : DefaultCC;
2265
2266  // If this type isn't canonical, get the canonical version of it.
2267  // The exception spec is not part of the canonical type.
2268  QualType Canonical;
2269  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2270    SmallVector<QualType, 16> CanonicalArgs;
2271    CanonicalArgs.reserve(NumArgs);
2272    for (unsigned i = 0; i != NumArgs; ++i)
2273      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2274
2275    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2276    CanonicalEPI.HasTrailingReturn = false;
2277    CanonicalEPI.ExceptionSpecType = EST_None;
2278    CanonicalEPI.NumExceptions = 0;
2279    CanonicalEPI.ExtInfo
2280      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2281
2282    Canonical = getFunctionType(getCanonicalType(ResultTy),
2283                                CanonicalArgs.data(), NumArgs,
2284                                CanonicalEPI);
2285
2286    // Get the new insert position for the node we care about.
2287    FunctionProtoType *NewIP =
2288      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2289    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2290  }
2291
2292  // FunctionProtoType objects are allocated with extra bytes after
2293  // them for three variable size arrays at the end:
2294  //  - parameter types
2295  //  - exception types
2296  //  - consumed-arguments flags
2297  // Instead of the exception types, there could be a noexcept
2298  // expression.
2299  size_t Size = sizeof(FunctionProtoType) +
2300                NumArgs * sizeof(QualType);
2301  if (EPI.ExceptionSpecType == EST_Dynamic)
2302    Size += EPI.NumExceptions * sizeof(QualType);
2303  else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2304    Size += sizeof(Expr*);
2305  } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2306    Size += 2 * sizeof(FunctionDecl*);
2307  }
2308  if (EPI.ConsumedArguments)
2309    Size += NumArgs * sizeof(bool);
2310
2311  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2312  FunctionProtoType::ExtProtoInfo newEPI = EPI;
2313  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2314  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2315  Types.push_back(FTP);
2316  FunctionProtoTypes.InsertNode(FTP, InsertPos);
2317  return QualType(FTP, 0);
2318}
2319
2320#ifndef NDEBUG
2321static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2322  if (!isa<CXXRecordDecl>(D)) return false;
2323  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2324  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2325    return true;
2326  if (RD->getDescribedClassTemplate() &&
2327      !isa<ClassTemplateSpecializationDecl>(RD))
2328    return true;
2329  return false;
2330}
2331#endif
2332
2333/// getInjectedClassNameType - Return the unique reference to the
2334/// injected class name type for the specified templated declaration.
2335QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2336                                              QualType TST) const {
2337  assert(NeedsInjectedClassNameType(Decl));
2338  if (Decl->TypeForDecl) {
2339    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2340  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2341    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2342    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2343    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2344  } else {
2345    Type *newType =
2346      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2347    Decl->TypeForDecl = newType;
2348    Types.push_back(newType);
2349  }
2350  return QualType(Decl->TypeForDecl, 0);
2351}
2352
2353/// getTypeDeclType - Return the unique reference to the type for the
2354/// specified type declaration.
2355QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2356  assert(Decl && "Passed null for Decl param");
2357  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2358
2359  if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2360    return getTypedefType(Typedef);
2361
2362  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2363         "Template type parameter types are always available.");
2364
2365  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2366    assert(!Record->getPreviousDecl() &&
2367           "struct/union has previous declaration");
2368    assert(!NeedsInjectedClassNameType(Record));
2369    return getRecordType(Record);
2370  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2371    assert(!Enum->getPreviousDecl() &&
2372           "enum has previous declaration");
2373    return getEnumType(Enum);
2374  } else if (const UnresolvedUsingTypenameDecl *Using =
2375               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2376    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2377    Decl->TypeForDecl = newType;
2378    Types.push_back(newType);
2379  } else
2380    llvm_unreachable("TypeDecl without a type?");
2381
2382  return QualType(Decl->TypeForDecl, 0);
2383}
2384
2385/// getTypedefType - Return the unique reference to the type for the
2386/// specified typedef name decl.
2387QualType
2388ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2389                           QualType Canonical) const {
2390  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2391
2392  if (Canonical.isNull())
2393    Canonical = getCanonicalType(Decl->getUnderlyingType());
2394  TypedefType *newType = new(*this, TypeAlignment)
2395    TypedefType(Type::Typedef, Decl, Canonical);
2396  Decl->TypeForDecl = newType;
2397  Types.push_back(newType);
2398  return QualType(newType, 0);
2399}
2400
2401QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2402  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2403
2404  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2405    if (PrevDecl->TypeForDecl)
2406      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2407
2408  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2409  Decl->TypeForDecl = newType;
2410  Types.push_back(newType);
2411  return QualType(newType, 0);
2412}
2413
2414QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2415  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2416
2417  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2418    if (PrevDecl->TypeForDecl)
2419      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2420
2421  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2422  Decl->TypeForDecl = newType;
2423  Types.push_back(newType);
2424  return QualType(newType, 0);
2425}
2426
2427QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2428                                       QualType modifiedType,
2429                                       QualType equivalentType) {
2430  llvm::FoldingSetNodeID id;
2431  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2432
2433  void *insertPos = 0;
2434  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2435  if (type) return QualType(type, 0);
2436
2437  QualType canon = getCanonicalType(equivalentType);
2438  type = new (*this, TypeAlignment)
2439           AttributedType(canon, attrKind, modifiedType, equivalentType);
2440
2441  Types.push_back(type);
2442  AttributedTypes.InsertNode(type, insertPos);
2443
2444  return QualType(type, 0);
2445}
2446
2447
2448/// \brief Retrieve a substitution-result type.
2449QualType
2450ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2451                                         QualType Replacement) const {
2452  assert(Replacement.isCanonical()
2453         && "replacement types must always be canonical");
2454
2455  llvm::FoldingSetNodeID ID;
2456  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2457  void *InsertPos = 0;
2458  SubstTemplateTypeParmType *SubstParm
2459    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2460
2461  if (!SubstParm) {
2462    SubstParm = new (*this, TypeAlignment)
2463      SubstTemplateTypeParmType(Parm, Replacement);
2464    Types.push_back(SubstParm);
2465    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2466  }
2467
2468  return QualType(SubstParm, 0);
2469}
2470
2471/// \brief Retrieve a
2472QualType ASTContext::getSubstTemplateTypeParmPackType(
2473                                          const TemplateTypeParmType *Parm,
2474                                              const TemplateArgument &ArgPack) {
2475#ifndef NDEBUG
2476  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2477                                    PEnd = ArgPack.pack_end();
2478       P != PEnd; ++P) {
2479    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2480    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2481  }
2482#endif
2483
2484  llvm::FoldingSetNodeID ID;
2485  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2486  void *InsertPos = 0;
2487  if (SubstTemplateTypeParmPackType *SubstParm
2488        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2489    return QualType(SubstParm, 0);
2490
2491  QualType Canon;
2492  if (!Parm->isCanonicalUnqualified()) {
2493    Canon = getCanonicalType(QualType(Parm, 0));
2494    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2495                                             ArgPack);
2496    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2497  }
2498
2499  SubstTemplateTypeParmPackType *SubstParm
2500    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2501                                                               ArgPack);
2502  Types.push_back(SubstParm);
2503  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2504  return QualType(SubstParm, 0);
2505}
2506
2507/// \brief Retrieve the template type parameter type for a template
2508/// parameter or parameter pack with the given depth, index, and (optionally)
2509/// name.
2510QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2511                                             bool ParameterPack,
2512                                             TemplateTypeParmDecl *TTPDecl) const {
2513  llvm::FoldingSetNodeID ID;
2514  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2515  void *InsertPos = 0;
2516  TemplateTypeParmType *TypeParm
2517    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2518
2519  if (TypeParm)
2520    return QualType(TypeParm, 0);
2521
2522  if (TTPDecl) {
2523    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2524    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2525
2526    TemplateTypeParmType *TypeCheck
2527      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2528    assert(!TypeCheck && "Template type parameter canonical type broken");
2529    (void)TypeCheck;
2530  } else
2531    TypeParm = new (*this, TypeAlignment)
2532      TemplateTypeParmType(Depth, Index, ParameterPack);
2533
2534  Types.push_back(TypeParm);
2535  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2536
2537  return QualType(TypeParm, 0);
2538}
2539
2540TypeSourceInfo *
2541ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2542                                              SourceLocation NameLoc,
2543                                        const TemplateArgumentListInfo &Args,
2544                                              QualType Underlying) const {
2545  assert(!Name.getAsDependentTemplateName() &&
2546         "No dependent template names here!");
2547  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2548
2549  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2550  TemplateSpecializationTypeLoc TL
2551    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2552  TL.setTemplateKeywordLoc(SourceLocation());
2553  TL.setTemplateNameLoc(NameLoc);
2554  TL.setLAngleLoc(Args.getLAngleLoc());
2555  TL.setRAngleLoc(Args.getRAngleLoc());
2556  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2557    TL.setArgLocInfo(i, Args[i].getLocInfo());
2558  return DI;
2559}
2560
2561QualType
2562ASTContext::getTemplateSpecializationType(TemplateName Template,
2563                                          const TemplateArgumentListInfo &Args,
2564                                          QualType Underlying) const {
2565  assert(!Template.getAsDependentTemplateName() &&
2566         "No dependent template names here!");
2567
2568  unsigned NumArgs = Args.size();
2569
2570  SmallVector<TemplateArgument, 4> ArgVec;
2571  ArgVec.reserve(NumArgs);
2572  for (unsigned i = 0; i != NumArgs; ++i)
2573    ArgVec.push_back(Args[i].getArgument());
2574
2575  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2576                                       Underlying);
2577}
2578
2579#ifndef NDEBUG
2580static bool hasAnyPackExpansions(const TemplateArgument *Args,
2581                                 unsigned NumArgs) {
2582  for (unsigned I = 0; I != NumArgs; ++I)
2583    if (Args[I].isPackExpansion())
2584      return true;
2585
2586  return true;
2587}
2588#endif
2589
2590QualType
2591ASTContext::getTemplateSpecializationType(TemplateName Template,
2592                                          const TemplateArgument *Args,
2593                                          unsigned NumArgs,
2594                                          QualType Underlying) const {
2595  assert(!Template.getAsDependentTemplateName() &&
2596         "No dependent template names here!");
2597  // Look through qualified template names.
2598  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2599    Template = TemplateName(QTN->getTemplateDecl());
2600
2601  bool IsTypeAlias =
2602    Template.getAsTemplateDecl() &&
2603    isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2604  QualType CanonType;
2605  if (!Underlying.isNull())
2606    CanonType = getCanonicalType(Underlying);
2607  else {
2608    // We can get here with an alias template when the specialization contains
2609    // a pack expansion that does not match up with a parameter pack.
2610    assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2611           "Caller must compute aliased type");
2612    IsTypeAlias = false;
2613    CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2614                                                       NumArgs);
2615  }
2616
2617  // Allocate the (non-canonical) template specialization type, but don't
2618  // try to unique it: these types typically have location information that
2619  // we don't unique and don't want to lose.
2620  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2621                       sizeof(TemplateArgument) * NumArgs +
2622                       (IsTypeAlias? sizeof(QualType) : 0),
2623                       TypeAlignment);
2624  TemplateSpecializationType *Spec
2625    = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2626                                         IsTypeAlias ? Underlying : QualType());
2627
2628  Types.push_back(Spec);
2629  return QualType(Spec, 0);
2630}
2631
2632QualType
2633ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2634                                                   const TemplateArgument *Args,
2635                                                   unsigned NumArgs) const {
2636  assert(!Template.getAsDependentTemplateName() &&
2637         "No dependent template names here!");
2638
2639  // Look through qualified template names.
2640  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2641    Template = TemplateName(QTN->getTemplateDecl());
2642
2643  // Build the canonical template specialization type.
2644  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2645  SmallVector<TemplateArgument, 4> CanonArgs;
2646  CanonArgs.reserve(NumArgs);
2647  for (unsigned I = 0; I != NumArgs; ++I)
2648    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2649
2650  // Determine whether this canonical template specialization type already
2651  // exists.
2652  llvm::FoldingSetNodeID ID;
2653  TemplateSpecializationType::Profile(ID, CanonTemplate,
2654                                      CanonArgs.data(), NumArgs, *this);
2655
2656  void *InsertPos = 0;
2657  TemplateSpecializationType *Spec
2658    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2659
2660  if (!Spec) {
2661    // Allocate a new canonical template specialization type.
2662    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2663                          sizeof(TemplateArgument) * NumArgs),
2664                         TypeAlignment);
2665    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2666                                                CanonArgs.data(), NumArgs,
2667                                                QualType(), QualType());
2668    Types.push_back(Spec);
2669    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2670  }
2671
2672  assert(Spec->isDependentType() &&
2673         "Non-dependent template-id type must have a canonical type");
2674  return QualType(Spec, 0);
2675}
2676
2677QualType
2678ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2679                              NestedNameSpecifier *NNS,
2680                              QualType NamedType) const {
2681  llvm::FoldingSetNodeID ID;
2682  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2683
2684  void *InsertPos = 0;
2685  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2686  if (T)
2687    return QualType(T, 0);
2688
2689  QualType Canon = NamedType;
2690  if (!Canon.isCanonical()) {
2691    Canon = getCanonicalType(NamedType);
2692    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2693    assert(!CheckT && "Elaborated canonical type broken");
2694    (void)CheckT;
2695  }
2696
2697  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2698  Types.push_back(T);
2699  ElaboratedTypes.InsertNode(T, InsertPos);
2700  return QualType(T, 0);
2701}
2702
2703QualType
2704ASTContext::getParenType(QualType InnerType) const {
2705  llvm::FoldingSetNodeID ID;
2706  ParenType::Profile(ID, InnerType);
2707
2708  void *InsertPos = 0;
2709  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2710  if (T)
2711    return QualType(T, 0);
2712
2713  QualType Canon = InnerType;
2714  if (!Canon.isCanonical()) {
2715    Canon = getCanonicalType(InnerType);
2716    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2717    assert(!CheckT && "Paren canonical type broken");
2718    (void)CheckT;
2719  }
2720
2721  T = new (*this) ParenType(InnerType, Canon);
2722  Types.push_back(T);
2723  ParenTypes.InsertNode(T, InsertPos);
2724  return QualType(T, 0);
2725}
2726
2727QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2728                                          NestedNameSpecifier *NNS,
2729                                          const IdentifierInfo *Name,
2730                                          QualType Canon) const {
2731  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2732
2733  if (Canon.isNull()) {
2734    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2735    ElaboratedTypeKeyword CanonKeyword = Keyword;
2736    if (Keyword == ETK_None)
2737      CanonKeyword = ETK_Typename;
2738
2739    if (CanonNNS != NNS || CanonKeyword != Keyword)
2740      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2741  }
2742
2743  llvm::FoldingSetNodeID ID;
2744  DependentNameType::Profile(ID, Keyword, NNS, Name);
2745
2746  void *InsertPos = 0;
2747  DependentNameType *T
2748    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2749  if (T)
2750    return QualType(T, 0);
2751
2752  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2753  Types.push_back(T);
2754  DependentNameTypes.InsertNode(T, InsertPos);
2755  return QualType(T, 0);
2756}
2757
2758QualType
2759ASTContext::getDependentTemplateSpecializationType(
2760                                 ElaboratedTypeKeyword Keyword,
2761                                 NestedNameSpecifier *NNS,
2762                                 const IdentifierInfo *Name,
2763                                 const TemplateArgumentListInfo &Args) const {
2764  // TODO: avoid this copy
2765  SmallVector<TemplateArgument, 16> ArgCopy;
2766  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2767    ArgCopy.push_back(Args[I].getArgument());
2768  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2769                                                ArgCopy.size(),
2770                                                ArgCopy.data());
2771}
2772
2773QualType
2774ASTContext::getDependentTemplateSpecializationType(
2775                                 ElaboratedTypeKeyword Keyword,
2776                                 NestedNameSpecifier *NNS,
2777                                 const IdentifierInfo *Name,
2778                                 unsigned NumArgs,
2779                                 const TemplateArgument *Args) const {
2780  assert((!NNS || NNS->isDependent()) &&
2781         "nested-name-specifier must be dependent");
2782
2783  llvm::FoldingSetNodeID ID;
2784  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2785                                               Name, NumArgs, Args);
2786
2787  void *InsertPos = 0;
2788  DependentTemplateSpecializationType *T
2789    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2790  if (T)
2791    return QualType(T, 0);
2792
2793  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2794
2795  ElaboratedTypeKeyword CanonKeyword = Keyword;
2796  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2797
2798  bool AnyNonCanonArgs = false;
2799  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2800  for (unsigned I = 0; I != NumArgs; ++I) {
2801    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2802    if (!CanonArgs[I].structurallyEquals(Args[I]))
2803      AnyNonCanonArgs = true;
2804  }
2805
2806  QualType Canon;
2807  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2808    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2809                                                   Name, NumArgs,
2810                                                   CanonArgs.data());
2811
2812    // Find the insert position again.
2813    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2814  }
2815
2816  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2817                        sizeof(TemplateArgument) * NumArgs),
2818                       TypeAlignment);
2819  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2820                                                    Name, NumArgs, Args, Canon);
2821  Types.push_back(T);
2822  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2823  return QualType(T, 0);
2824}
2825
2826QualType ASTContext::getPackExpansionType(QualType Pattern,
2827                                      llvm::Optional<unsigned> NumExpansions) {
2828  llvm::FoldingSetNodeID ID;
2829  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2830
2831  assert(Pattern->containsUnexpandedParameterPack() &&
2832         "Pack expansions must expand one or more parameter packs");
2833  void *InsertPos = 0;
2834  PackExpansionType *T
2835    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2836  if (T)
2837    return QualType(T, 0);
2838
2839  QualType Canon;
2840  if (!Pattern.isCanonical()) {
2841    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2842
2843    // Find the insert position again.
2844    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2845  }
2846
2847  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2848  Types.push_back(T);
2849  PackExpansionTypes.InsertNode(T, InsertPos);
2850  return QualType(T, 0);
2851}
2852
2853/// CmpProtocolNames - Comparison predicate for sorting protocols
2854/// alphabetically.
2855static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2856                            const ObjCProtocolDecl *RHS) {
2857  return LHS->getDeclName() < RHS->getDeclName();
2858}
2859
2860static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2861                                unsigned NumProtocols) {
2862  if (NumProtocols == 0) return true;
2863
2864  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2865    return false;
2866
2867  for (unsigned i = 1; i != NumProtocols; ++i)
2868    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2869        Protocols[i]->getCanonicalDecl() != Protocols[i])
2870      return false;
2871  return true;
2872}
2873
2874static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2875                                   unsigned &NumProtocols) {
2876  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2877
2878  // Sort protocols, keyed by name.
2879  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2880
2881  // Canonicalize.
2882  for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2883    Protocols[I] = Protocols[I]->getCanonicalDecl();
2884
2885  // Remove duplicates.
2886  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2887  NumProtocols = ProtocolsEnd-Protocols;
2888}
2889
2890QualType ASTContext::getObjCObjectType(QualType BaseType,
2891                                       ObjCProtocolDecl * const *Protocols,
2892                                       unsigned NumProtocols) const {
2893  // If the base type is an interface and there aren't any protocols
2894  // to add, then the interface type will do just fine.
2895  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2896    return BaseType;
2897
2898  // Look in the folding set for an existing type.
2899  llvm::FoldingSetNodeID ID;
2900  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2901  void *InsertPos = 0;
2902  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2903    return QualType(QT, 0);
2904
2905  // Build the canonical type, which has the canonical base type and
2906  // a sorted-and-uniqued list of protocols.
2907  QualType Canonical;
2908  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2909  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2910    if (!ProtocolsSorted) {
2911      SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2912                                                     Protocols + NumProtocols);
2913      unsigned UniqueCount = NumProtocols;
2914
2915      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2916      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2917                                    &Sorted[0], UniqueCount);
2918    } else {
2919      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2920                                    Protocols, NumProtocols);
2921    }
2922
2923    // Regenerate InsertPos.
2924    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2925  }
2926
2927  unsigned Size = sizeof(ObjCObjectTypeImpl);
2928  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2929  void *Mem = Allocate(Size, TypeAlignment);
2930  ObjCObjectTypeImpl *T =
2931    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2932
2933  Types.push_back(T);
2934  ObjCObjectTypes.InsertNode(T, InsertPos);
2935  return QualType(T, 0);
2936}
2937
2938/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2939/// the given object type.
2940QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2941  llvm::FoldingSetNodeID ID;
2942  ObjCObjectPointerType::Profile(ID, ObjectT);
2943
2944  void *InsertPos = 0;
2945  if (ObjCObjectPointerType *QT =
2946              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2947    return QualType(QT, 0);
2948
2949  // Find the canonical object type.
2950  QualType Canonical;
2951  if (!ObjectT.isCanonical()) {
2952    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2953
2954    // Regenerate InsertPos.
2955    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2956  }
2957
2958  // No match.
2959  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2960  ObjCObjectPointerType *QType =
2961    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2962
2963  Types.push_back(QType);
2964  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2965  return QualType(QType, 0);
2966}
2967
2968/// getObjCInterfaceType - Return the unique reference to the type for the
2969/// specified ObjC interface decl. The list of protocols is optional.
2970QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2971                                          ObjCInterfaceDecl *PrevDecl) const {
2972  if (Decl->TypeForDecl)
2973    return QualType(Decl->TypeForDecl, 0);
2974
2975  if (PrevDecl) {
2976    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2977    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2978    return QualType(PrevDecl->TypeForDecl, 0);
2979  }
2980
2981  // Prefer the definition, if there is one.
2982  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2983    Decl = Def;
2984
2985  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2986  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2987  Decl->TypeForDecl = T;
2988  Types.push_back(T);
2989  return QualType(T, 0);
2990}
2991
2992/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2993/// TypeOfExprType AST's (since expression's are never shared). For example,
2994/// multiple declarations that refer to "typeof(x)" all contain different
2995/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2996/// on canonical type's (which are always unique).
2997QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2998  TypeOfExprType *toe;
2999  if (tofExpr->isTypeDependent()) {
3000    llvm::FoldingSetNodeID ID;
3001    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3002
3003    void *InsertPos = 0;
3004    DependentTypeOfExprType *Canon
3005      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3006    if (Canon) {
3007      // We already have a "canonical" version of an identical, dependent
3008      // typeof(expr) type. Use that as our canonical type.
3009      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3010                                          QualType((TypeOfExprType*)Canon, 0));
3011    } else {
3012      // Build a new, canonical typeof(expr) type.
3013      Canon
3014        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3015      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3016      toe = Canon;
3017    }
3018  } else {
3019    QualType Canonical = getCanonicalType(tofExpr->getType());
3020    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3021  }
3022  Types.push_back(toe);
3023  return QualType(toe, 0);
3024}
3025
3026/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3027/// TypeOfType AST's. The only motivation to unique these nodes would be
3028/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3029/// an issue. This doesn't effect the type checker, since it operates
3030/// on canonical type's (which are always unique).
3031QualType ASTContext::getTypeOfType(QualType tofType) const {
3032  QualType Canonical = getCanonicalType(tofType);
3033  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3034  Types.push_back(tot);
3035  return QualType(tot, 0);
3036}
3037
3038
3039/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
3040/// DecltypeType AST's. The only motivation to unique these nodes would be
3041/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3042/// an issue. This doesn't effect the type checker, since it operates
3043/// on canonical types (which are always unique).
3044QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3045  DecltypeType *dt;
3046
3047  // C++0x [temp.type]p2:
3048  //   If an expression e involves a template parameter, decltype(e) denotes a
3049  //   unique dependent type. Two such decltype-specifiers refer to the same
3050  //   type only if their expressions are equivalent (14.5.6.1).
3051  if (e->isInstantiationDependent()) {
3052    llvm::FoldingSetNodeID ID;
3053    DependentDecltypeType::Profile(ID, *this, e);
3054
3055    void *InsertPos = 0;
3056    DependentDecltypeType *Canon
3057      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3058    if (Canon) {
3059      // We already have a "canonical" version of an equivalent, dependent
3060      // decltype type. Use that as our canonical type.
3061      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
3062                                       QualType((DecltypeType*)Canon, 0));
3063    } else {
3064      // Build a new, canonical typeof(expr) type.
3065      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3066      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3067      dt = Canon;
3068    }
3069  } else {
3070    dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3071                                      getCanonicalType(UnderlyingType));
3072  }
3073  Types.push_back(dt);
3074  return QualType(dt, 0);
3075}
3076
3077/// getUnaryTransformationType - We don't unique these, since the memory
3078/// savings are minimal and these are rare.
3079QualType ASTContext::getUnaryTransformType(QualType BaseType,
3080                                           QualType UnderlyingType,
3081                                           UnaryTransformType::UTTKind Kind)
3082    const {
3083  UnaryTransformType *Ty =
3084    new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3085                                                   Kind,
3086                                 UnderlyingType->isDependentType() ?
3087                                 QualType() : getCanonicalType(UnderlyingType));
3088  Types.push_back(Ty);
3089  return QualType(Ty, 0);
3090}
3091
3092/// getAutoType - We only unique auto types after they've been deduced.
3093QualType ASTContext::getAutoType(QualType DeducedType) const {
3094  void *InsertPos = 0;
3095  if (!DeducedType.isNull()) {
3096    // Look in the folding set for an existing type.
3097    llvm::FoldingSetNodeID ID;
3098    AutoType::Profile(ID, DeducedType);
3099    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3100      return QualType(AT, 0);
3101  }
3102
3103  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3104  Types.push_back(AT);
3105  if (InsertPos)
3106    AutoTypes.InsertNode(AT, InsertPos);
3107  return QualType(AT, 0);
3108}
3109
3110/// getAtomicType - Return the uniqued reference to the atomic type for
3111/// the given value type.
3112QualType ASTContext::getAtomicType(QualType T) const {
3113  // Unique pointers, to guarantee there is only one pointer of a particular
3114  // structure.
3115  llvm::FoldingSetNodeID ID;
3116  AtomicType::Profile(ID, T);
3117
3118  void *InsertPos = 0;
3119  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3120    return QualType(AT, 0);
3121
3122  // If the atomic value type isn't canonical, this won't be a canonical type
3123  // either, so fill in the canonical type field.
3124  QualType Canonical;
3125  if (!T.isCanonical()) {
3126    Canonical = getAtomicType(getCanonicalType(T));
3127
3128    // Get the new insert position for the node we care about.
3129    AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3130    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3131  }
3132  AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3133  Types.push_back(New);
3134  AtomicTypes.InsertNode(New, InsertPos);
3135  return QualType(New, 0);
3136}
3137
3138/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3139QualType ASTContext::getAutoDeductType() const {
3140  if (AutoDeductTy.isNull())
3141    AutoDeductTy = getAutoType(QualType());
3142  assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3143  return AutoDeductTy;
3144}
3145
3146/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3147QualType ASTContext::getAutoRRefDeductType() const {
3148  if (AutoRRefDeductTy.isNull())
3149    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3150  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3151  return AutoRRefDeductTy;
3152}
3153
3154/// getTagDeclType - Return the unique reference to the type for the
3155/// specified TagDecl (struct/union/class/enum) decl.
3156QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3157  assert (Decl);
3158  // FIXME: What is the design on getTagDeclType when it requires casting
3159  // away const?  mutable?
3160  return getTypeDeclType(const_cast<TagDecl*>(Decl));
3161}
3162
3163/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3164/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3165/// needs to agree with the definition in <stddef.h>.
3166CanQualType ASTContext::getSizeType() const {
3167  return getFromTargetType(Target->getSizeType());
3168}
3169
3170/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3171CanQualType ASTContext::getIntMaxType() const {
3172  return getFromTargetType(Target->getIntMaxType());
3173}
3174
3175/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3176CanQualType ASTContext::getUIntMaxType() const {
3177  return getFromTargetType(Target->getUIntMaxType());
3178}
3179
3180/// getSignedWCharType - Return the type of "signed wchar_t".
3181/// Used when in C++, as a GCC extension.
3182QualType ASTContext::getSignedWCharType() const {
3183  // FIXME: derive from "Target" ?
3184  return WCharTy;
3185}
3186
3187/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3188/// Used when in C++, as a GCC extension.
3189QualType ASTContext::getUnsignedWCharType() const {
3190  // FIXME: derive from "Target" ?
3191  return UnsignedIntTy;
3192}
3193
3194/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3195/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3196QualType ASTContext::getPointerDiffType() const {
3197  return getFromTargetType(Target->getPtrDiffType(0));
3198}
3199
3200//===----------------------------------------------------------------------===//
3201//                              Type Operators
3202//===----------------------------------------------------------------------===//
3203
3204CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3205  // Push qualifiers into arrays, and then discard any remaining
3206  // qualifiers.
3207  T = getCanonicalType(T);
3208  T = getVariableArrayDecayedType(T);
3209  const Type *Ty = T.getTypePtr();
3210  QualType Result;
3211  if (isa<ArrayType>(Ty)) {
3212    Result = getArrayDecayedType(QualType(Ty,0));
3213  } else if (isa<FunctionType>(Ty)) {
3214    Result = getPointerType(QualType(Ty, 0));
3215  } else {
3216    Result = QualType(Ty, 0);
3217  }
3218
3219  return CanQualType::CreateUnsafe(Result);
3220}
3221
3222QualType ASTContext::getUnqualifiedArrayType(QualType type,
3223                                             Qualifiers &quals) {
3224  SplitQualType splitType = type.getSplitUnqualifiedType();
3225
3226  // FIXME: getSplitUnqualifiedType() actually walks all the way to
3227  // the unqualified desugared type and then drops it on the floor.
3228  // We then have to strip that sugar back off with
3229  // getUnqualifiedDesugaredType(), which is silly.
3230  const ArrayType *AT =
3231    dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3232
3233  // If we don't have an array, just use the results in splitType.
3234  if (!AT) {
3235    quals = splitType.Quals;
3236    return QualType(splitType.Ty, 0);
3237  }
3238
3239  // Otherwise, recurse on the array's element type.
3240  QualType elementType = AT->getElementType();
3241  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3242
3243  // If that didn't change the element type, AT has no qualifiers, so we
3244  // can just use the results in splitType.
3245  if (elementType == unqualElementType) {
3246    assert(quals.empty()); // from the recursive call
3247    quals = splitType.Quals;
3248    return QualType(splitType.Ty, 0);
3249  }
3250
3251  // Otherwise, add in the qualifiers from the outermost type, then
3252  // build the type back up.
3253  quals.addConsistentQualifiers(splitType.Quals);
3254
3255  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3256    return getConstantArrayType(unqualElementType, CAT->getSize(),
3257                                CAT->getSizeModifier(), 0);
3258  }
3259
3260  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3261    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3262  }
3263
3264  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3265    return getVariableArrayType(unqualElementType,
3266                                VAT->getSizeExpr(),
3267                                VAT->getSizeModifier(),
3268                                VAT->getIndexTypeCVRQualifiers(),
3269                                VAT->getBracketsRange());
3270  }
3271
3272  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3273  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3274                                    DSAT->getSizeModifier(), 0,
3275                                    SourceRange());
3276}
3277
3278/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3279/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3280/// they point to and return true. If T1 and T2 aren't pointer types
3281/// or pointer-to-member types, or if they are not similar at this
3282/// level, returns false and leaves T1 and T2 unchanged. Top-level
3283/// qualifiers on T1 and T2 are ignored. This function will typically
3284/// be called in a loop that successively "unwraps" pointer and
3285/// pointer-to-member types to compare them at each level.
3286bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3287  const PointerType *T1PtrType = T1->getAs<PointerType>(),
3288                    *T2PtrType = T2->getAs<PointerType>();
3289  if (T1PtrType && T2PtrType) {
3290    T1 = T1PtrType->getPointeeType();
3291    T2 = T2PtrType->getPointeeType();
3292    return true;
3293  }
3294
3295  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3296                          *T2MPType = T2->getAs<MemberPointerType>();
3297  if (T1MPType && T2MPType &&
3298      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3299                             QualType(T2MPType->getClass(), 0))) {
3300    T1 = T1MPType->getPointeeType();
3301    T2 = T2MPType->getPointeeType();
3302    return true;
3303  }
3304
3305  if (getLangOpts().ObjC1) {
3306    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3307                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
3308    if (T1OPType && T2OPType) {
3309      T1 = T1OPType->getPointeeType();
3310      T2 = T2OPType->getPointeeType();
3311      return true;
3312    }
3313  }
3314
3315  // FIXME: Block pointers, too?
3316
3317  return false;
3318}
3319
3320DeclarationNameInfo
3321ASTContext::getNameForTemplate(TemplateName Name,
3322                               SourceLocation NameLoc) const {
3323  switch (Name.getKind()) {
3324  case TemplateName::QualifiedTemplate:
3325  case TemplateName::Template:
3326    // DNInfo work in progress: CHECKME: what about DNLoc?
3327    return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3328                               NameLoc);
3329
3330  case TemplateName::OverloadedTemplate: {
3331    OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3332    // DNInfo work in progress: CHECKME: what about DNLoc?
3333    return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3334  }
3335
3336  case TemplateName::DependentTemplate: {
3337    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3338    DeclarationName DName;
3339    if (DTN->isIdentifier()) {
3340      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3341      return DeclarationNameInfo(DName, NameLoc);
3342    } else {
3343      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3344      // DNInfo work in progress: FIXME: source locations?
3345      DeclarationNameLoc DNLoc;
3346      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3347      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3348      return DeclarationNameInfo(DName, NameLoc, DNLoc);
3349    }
3350  }
3351
3352  case TemplateName::SubstTemplateTemplateParm: {
3353    SubstTemplateTemplateParmStorage *subst
3354      = Name.getAsSubstTemplateTemplateParm();
3355    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3356                               NameLoc);
3357  }
3358
3359  case TemplateName::SubstTemplateTemplateParmPack: {
3360    SubstTemplateTemplateParmPackStorage *subst
3361      = Name.getAsSubstTemplateTemplateParmPack();
3362    return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3363                               NameLoc);
3364  }
3365  }
3366
3367  llvm_unreachable("bad template name kind!");
3368}
3369
3370TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3371  switch (Name.getKind()) {
3372  case TemplateName::QualifiedTemplate:
3373  case TemplateName::Template: {
3374    TemplateDecl *Template = Name.getAsTemplateDecl();
3375    if (TemplateTemplateParmDecl *TTP
3376          = dyn_cast<TemplateTemplateParmDecl>(Template))
3377      Template = getCanonicalTemplateTemplateParmDecl(TTP);
3378
3379    // The canonical template name is the canonical template declaration.
3380    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3381  }
3382
3383  case TemplateName::OverloadedTemplate:
3384    llvm_unreachable("cannot canonicalize overloaded template");
3385
3386  case TemplateName::DependentTemplate: {
3387    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3388    assert(DTN && "Non-dependent template names must refer to template decls.");
3389    return DTN->CanonicalTemplateName;
3390  }
3391
3392  case TemplateName::SubstTemplateTemplateParm: {
3393    SubstTemplateTemplateParmStorage *subst
3394      = Name.getAsSubstTemplateTemplateParm();
3395    return getCanonicalTemplateName(subst->getReplacement());
3396  }
3397
3398  case TemplateName::SubstTemplateTemplateParmPack: {
3399    SubstTemplateTemplateParmPackStorage *subst
3400                                  = Name.getAsSubstTemplateTemplateParmPack();
3401    TemplateTemplateParmDecl *canonParameter
3402      = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3403    TemplateArgument canonArgPack
3404      = getCanonicalTemplateArgument(subst->getArgumentPack());
3405    return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3406  }
3407  }
3408
3409  llvm_unreachable("bad template name!");
3410}
3411
3412bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3413  X = getCanonicalTemplateName(X);
3414  Y = getCanonicalTemplateName(Y);
3415  return X.getAsVoidPointer() == Y.getAsVoidPointer();
3416}
3417
3418TemplateArgument
3419ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3420  switch (Arg.getKind()) {
3421    case TemplateArgument::Null:
3422      return Arg;
3423
3424    case TemplateArgument::Expression:
3425      return Arg;
3426
3427    case TemplateArgument::Declaration: {
3428      if (Decl *D = Arg.getAsDecl())
3429          return TemplateArgument(D->getCanonicalDecl());
3430      return TemplateArgument((Decl*)0);
3431    }
3432
3433    case TemplateArgument::Template:
3434      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3435
3436    case TemplateArgument::TemplateExpansion:
3437      return TemplateArgument(getCanonicalTemplateName(
3438                                         Arg.getAsTemplateOrTemplatePattern()),
3439                              Arg.getNumTemplateExpansions());
3440
3441    case TemplateArgument::Integral:
3442      return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
3443
3444    case TemplateArgument::Type:
3445      return TemplateArgument(getCanonicalType(Arg.getAsType()));
3446
3447    case TemplateArgument::Pack: {
3448      if (Arg.pack_size() == 0)
3449        return Arg;
3450
3451      TemplateArgument *CanonArgs
3452        = new (*this) TemplateArgument[Arg.pack_size()];
3453      unsigned Idx = 0;
3454      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3455                                        AEnd = Arg.pack_end();
3456           A != AEnd; (void)++A, ++Idx)
3457        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3458
3459      return TemplateArgument(CanonArgs, Arg.pack_size());
3460    }
3461  }
3462
3463  // Silence GCC warning
3464  llvm_unreachable("Unhandled template argument kind");
3465}
3466
3467NestedNameSpecifier *
3468ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3469  if (!NNS)
3470    return 0;
3471
3472  switch (NNS->getKind()) {
3473  case NestedNameSpecifier::Identifier:
3474    // Canonicalize the prefix but keep the identifier the same.
3475    return NestedNameSpecifier::Create(*this,
3476                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3477                                       NNS->getAsIdentifier());
3478
3479  case NestedNameSpecifier::Namespace:
3480    // A namespace is canonical; build a nested-name-specifier with
3481    // this namespace and no prefix.
3482    return NestedNameSpecifier::Create(*this, 0,
3483                                 NNS->getAsNamespace()->getOriginalNamespace());
3484
3485  case NestedNameSpecifier::NamespaceAlias:
3486    // A namespace is canonical; build a nested-name-specifier with
3487    // this namespace and no prefix.
3488    return NestedNameSpecifier::Create(*this, 0,
3489                                    NNS->getAsNamespaceAlias()->getNamespace()
3490                                                      ->getOriginalNamespace());
3491
3492  case NestedNameSpecifier::TypeSpec:
3493  case NestedNameSpecifier::TypeSpecWithTemplate: {
3494    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3495
3496    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3497    // break it apart into its prefix and identifier, then reconsititute those
3498    // as the canonical nested-name-specifier. This is required to canonicalize
3499    // a dependent nested-name-specifier involving typedefs of dependent-name
3500    // types, e.g.,
3501    //   typedef typename T::type T1;
3502    //   typedef typename T1::type T2;
3503    if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3504      return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
3505                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3506
3507    // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3508    // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3509    // first place?
3510    return NestedNameSpecifier::Create(*this, 0, false,
3511                                       const_cast<Type*>(T.getTypePtr()));
3512  }
3513
3514  case NestedNameSpecifier::Global:
3515    // The global specifier is canonical and unique.
3516    return NNS;
3517  }
3518
3519  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3520}
3521
3522
3523const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3524  // Handle the non-qualified case efficiently.
3525  if (!T.hasLocalQualifiers()) {
3526    // Handle the common positive case fast.
3527    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3528      return AT;
3529  }
3530
3531  // Handle the common negative case fast.
3532  if (!isa<ArrayType>(T.getCanonicalType()))
3533    return 0;
3534
3535  // Apply any qualifiers from the array type to the element type.  This
3536  // implements C99 6.7.3p8: "If the specification of an array type includes
3537  // any type qualifiers, the element type is so qualified, not the array type."
3538
3539  // If we get here, we either have type qualifiers on the type, or we have
3540  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3541  // we must propagate them down into the element type.
3542
3543  SplitQualType split = T.getSplitDesugaredType();
3544  Qualifiers qs = split.Quals;
3545
3546  // If we have a simple case, just return now.
3547  const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
3548  if (ATy == 0 || qs.empty())
3549    return ATy;
3550
3551  // Otherwise, we have an array and we have qualifiers on it.  Push the
3552  // qualifiers into the array element type and return a new array type.
3553  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3554
3555  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3556    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3557                                                CAT->getSizeModifier(),
3558                                           CAT->getIndexTypeCVRQualifiers()));
3559  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3560    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3561                                                  IAT->getSizeModifier(),
3562                                           IAT->getIndexTypeCVRQualifiers()));
3563
3564  if (const DependentSizedArrayType *DSAT
3565        = dyn_cast<DependentSizedArrayType>(ATy))
3566    return cast<ArrayType>(
3567                     getDependentSizedArrayType(NewEltTy,
3568                                                DSAT->getSizeExpr(),
3569                                                DSAT->getSizeModifier(),
3570                                              DSAT->getIndexTypeCVRQualifiers(),
3571                                                DSAT->getBracketsRange()));
3572
3573  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3574  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3575                                              VAT->getSizeExpr(),
3576                                              VAT->getSizeModifier(),
3577                                              VAT->getIndexTypeCVRQualifiers(),
3578                                              VAT->getBracketsRange()));
3579}
3580
3581QualType ASTContext::getAdjustedParameterType(QualType T) const {
3582  // C99 6.7.5.3p7:
3583  //   A declaration of a parameter as "array of type" shall be
3584  //   adjusted to "qualified pointer to type", where the type
3585  //   qualifiers (if any) are those specified within the [ and ] of
3586  //   the array type derivation.
3587  if (T->isArrayType())
3588    return getArrayDecayedType(T);
3589
3590  // C99 6.7.5.3p8:
3591  //   A declaration of a parameter as "function returning type"
3592  //   shall be adjusted to "pointer to function returning type", as
3593  //   in 6.3.2.1.
3594  if (T->isFunctionType())
3595    return getPointerType(T);
3596
3597  return T;
3598}
3599
3600QualType ASTContext::getSignatureParameterType(QualType T) const {
3601  T = getVariableArrayDecayedType(T);
3602  T = getAdjustedParameterType(T);
3603  return T.getUnqualifiedType();
3604}
3605
3606/// getArrayDecayedType - Return the properly qualified result of decaying the
3607/// specified array type to a pointer.  This operation is non-trivial when
3608/// handling typedefs etc.  The canonical type of "T" must be an array type,
3609/// this returns a pointer to a properly qualified element of the array.
3610///
3611/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3612QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3613  // Get the element type with 'getAsArrayType' so that we don't lose any
3614  // typedefs in the element type of the array.  This also handles propagation
3615  // of type qualifiers from the array type into the element type if present
3616  // (C99 6.7.3p8).
3617  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3618  assert(PrettyArrayType && "Not an array type!");
3619
3620  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3621
3622  // int x[restrict 4] ->  int *restrict
3623  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3624}
3625
3626QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3627  return getBaseElementType(array->getElementType());
3628}
3629
3630QualType ASTContext::getBaseElementType(QualType type) const {
3631  Qualifiers qs;
3632  while (true) {
3633    SplitQualType split = type.getSplitDesugaredType();
3634    const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
3635    if (!array) break;
3636
3637    type = array->getElementType();
3638    qs.addConsistentQualifiers(split.Quals);
3639  }
3640
3641  return getQualifiedType(type, qs);
3642}
3643
3644/// getConstantArrayElementCount - Returns number of constant array elements.
3645uint64_t
3646ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3647  uint64_t ElementCount = 1;
3648  do {
3649    ElementCount *= CA->getSize().getZExtValue();
3650    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3651  } while (CA);
3652  return ElementCount;
3653}
3654
3655/// getFloatingRank - Return a relative rank for floating point types.
3656/// This routine will assert if passed a built-in type that isn't a float.
3657static FloatingRank getFloatingRank(QualType T) {
3658  if (const ComplexType *CT = T->getAs<ComplexType>())
3659    return getFloatingRank(CT->getElementType());
3660
3661  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3662  switch (T->getAs<BuiltinType>()->getKind()) {
3663  default: llvm_unreachable("getFloatingRank(): not a floating type");
3664  case BuiltinType::Half:       return HalfRank;
3665  case BuiltinType::Float:      return FloatRank;
3666  case BuiltinType::Double:     return DoubleRank;
3667  case BuiltinType::LongDouble: return LongDoubleRank;
3668  }
3669}
3670
3671/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3672/// point or a complex type (based on typeDomain/typeSize).
3673/// 'typeDomain' is a real floating point or complex type.
3674/// 'typeSize' is a real floating point or complex type.
3675QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3676                                                       QualType Domain) const {
3677  FloatingRank EltRank = getFloatingRank(Size);
3678  if (Domain->isComplexType()) {
3679    switch (EltRank) {
3680    case HalfRank: llvm_unreachable("Complex half is not supported");
3681    case FloatRank:      return FloatComplexTy;
3682    case DoubleRank:     return DoubleComplexTy;
3683    case LongDoubleRank: return LongDoubleComplexTy;
3684    }
3685  }
3686
3687  assert(Domain->isRealFloatingType() && "Unknown domain!");
3688  switch (EltRank) {
3689  case HalfRank: llvm_unreachable("Half ranks are not valid here");
3690  case FloatRank:      return FloatTy;
3691  case DoubleRank:     return DoubleTy;
3692  case LongDoubleRank: return LongDoubleTy;
3693  }
3694  llvm_unreachable("getFloatingRank(): illegal value for rank");
3695}
3696
3697/// getFloatingTypeOrder - Compare the rank of the two specified floating
3698/// point types, ignoring the domain of the type (i.e. 'double' ==
3699/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3700/// LHS < RHS, return -1.
3701int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3702  FloatingRank LHSR = getFloatingRank(LHS);
3703  FloatingRank RHSR = getFloatingRank(RHS);
3704
3705  if (LHSR == RHSR)
3706    return 0;
3707  if (LHSR > RHSR)
3708    return 1;
3709  return -1;
3710}
3711
3712/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3713/// routine will assert if passed a built-in type that isn't an integer or enum,
3714/// or if it is not canonicalized.
3715unsigned ASTContext::getIntegerRank(const Type *T) const {
3716  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3717
3718  switch (cast<BuiltinType>(T)->getKind()) {
3719  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3720  case BuiltinType::Bool:
3721    return 1 + (getIntWidth(BoolTy) << 3);
3722  case BuiltinType::Char_S:
3723  case BuiltinType::Char_U:
3724  case BuiltinType::SChar:
3725  case BuiltinType::UChar:
3726    return 2 + (getIntWidth(CharTy) << 3);
3727  case BuiltinType::Short:
3728  case BuiltinType::UShort:
3729    return 3 + (getIntWidth(ShortTy) << 3);
3730  case BuiltinType::Int:
3731  case BuiltinType::UInt:
3732    return 4 + (getIntWidth(IntTy) << 3);
3733  case BuiltinType::Long:
3734  case BuiltinType::ULong:
3735    return 5 + (getIntWidth(LongTy) << 3);
3736  case BuiltinType::LongLong:
3737  case BuiltinType::ULongLong:
3738    return 6 + (getIntWidth(LongLongTy) << 3);
3739  case BuiltinType::Int128:
3740  case BuiltinType::UInt128:
3741    return 7 + (getIntWidth(Int128Ty) << 3);
3742  }
3743}
3744
3745/// \brief Whether this is a promotable bitfield reference according
3746/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3747///
3748/// \returns the type this bit-field will promote to, or NULL if no
3749/// promotion occurs.
3750QualType ASTContext::isPromotableBitField(Expr *E) const {
3751  if (E->isTypeDependent() || E->isValueDependent())
3752    return QualType();
3753
3754  FieldDecl *Field = E->getBitField();
3755  if (!Field)
3756    return QualType();
3757
3758  QualType FT = Field->getType();
3759
3760  uint64_t BitWidth = Field->getBitWidthValue(*this);
3761  uint64_t IntSize = getTypeSize(IntTy);
3762  // GCC extension compatibility: if the bit-field size is less than or equal
3763  // to the size of int, it gets promoted no matter what its type is.
3764  // For instance, unsigned long bf : 4 gets promoted to signed int.
3765  if (BitWidth < IntSize)
3766    return IntTy;
3767
3768  if (BitWidth == IntSize)
3769    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3770
3771  // Types bigger than int are not subject to promotions, and therefore act
3772  // like the base type.
3773  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3774  // is ridiculous.
3775  return QualType();
3776}
3777
3778/// getPromotedIntegerType - Returns the type that Promotable will
3779/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3780/// integer type.
3781QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3782  assert(!Promotable.isNull());
3783  assert(Promotable->isPromotableIntegerType());
3784  if (const EnumType *ET = Promotable->getAs<EnumType>())
3785    return ET->getDecl()->getPromotionType();
3786
3787  if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3788    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3789    // (3.9.1) can be converted to a prvalue of the first of the following
3790    // types that can represent all the values of its underlying type:
3791    // int, unsigned int, long int, unsigned long int, long long int, or
3792    // unsigned long long int [...]
3793    // FIXME: Is there some better way to compute this?
3794    if (BT->getKind() == BuiltinType::WChar_S ||
3795        BT->getKind() == BuiltinType::WChar_U ||
3796        BT->getKind() == BuiltinType::Char16 ||
3797        BT->getKind() == BuiltinType::Char32) {
3798      bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3799      uint64_t FromSize = getTypeSize(BT);
3800      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3801                                  LongLongTy, UnsignedLongLongTy };
3802      for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3803        uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3804        if (FromSize < ToSize ||
3805            (FromSize == ToSize &&
3806             FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3807          return PromoteTypes[Idx];
3808      }
3809      llvm_unreachable("char type should fit into long long");
3810    }
3811  }
3812
3813  // At this point, we should have a signed or unsigned integer type.
3814  if (Promotable->isSignedIntegerType())
3815    return IntTy;
3816  uint64_t PromotableSize = getTypeSize(Promotable);
3817  uint64_t IntSize = getTypeSize(IntTy);
3818  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3819  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3820}
3821
3822/// \brief Recurses in pointer/array types until it finds an objc retainable
3823/// type and returns its ownership.
3824Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3825  while (!T.isNull()) {
3826    if (T.getObjCLifetime() != Qualifiers::OCL_None)
3827      return T.getObjCLifetime();
3828    if (T->isArrayType())
3829      T = getBaseElementType(T);
3830    else if (const PointerType *PT = T->getAs<PointerType>())
3831      T = PT->getPointeeType();
3832    else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3833      T = RT->getPointeeType();
3834    else
3835      break;
3836  }
3837
3838  return Qualifiers::OCL_None;
3839}
3840
3841/// getIntegerTypeOrder - Returns the highest ranked integer type:
3842/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3843/// LHS < RHS, return -1.
3844int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3845  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3846  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3847  if (LHSC == RHSC) return 0;
3848
3849  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3850  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3851
3852  unsigned LHSRank = getIntegerRank(LHSC);
3853  unsigned RHSRank = getIntegerRank(RHSC);
3854
3855  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3856    if (LHSRank == RHSRank) return 0;
3857    return LHSRank > RHSRank ? 1 : -1;
3858  }
3859
3860  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3861  if (LHSUnsigned) {
3862    // If the unsigned [LHS] type is larger, return it.
3863    if (LHSRank >= RHSRank)
3864      return 1;
3865
3866    // If the signed type can represent all values of the unsigned type, it
3867    // wins.  Because we are dealing with 2's complement and types that are
3868    // powers of two larger than each other, this is always safe.
3869    return -1;
3870  }
3871
3872  // If the unsigned [RHS] type is larger, return it.
3873  if (RHSRank >= LHSRank)
3874    return -1;
3875
3876  // If the signed type can represent all values of the unsigned type, it
3877  // wins.  Because we are dealing with 2's complement and types that are
3878  // powers of two larger than each other, this is always safe.
3879  return 1;
3880}
3881
3882static RecordDecl *
3883CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3884                 DeclContext *DC, IdentifierInfo *Id) {
3885  SourceLocation Loc;
3886  if (Ctx.getLangOpts().CPlusPlus)
3887    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3888  else
3889    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3890}
3891
3892// getCFConstantStringType - Return the type used for constant CFStrings.
3893QualType ASTContext::getCFConstantStringType() const {
3894  if (!CFConstantStringTypeDecl) {
3895    CFConstantStringTypeDecl =
3896      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3897                       &Idents.get("NSConstantString"));
3898    CFConstantStringTypeDecl->startDefinition();
3899
3900    QualType FieldTypes[4];
3901
3902    // const int *isa;
3903    FieldTypes[0] = getPointerType(IntTy.withConst());
3904    // int flags;
3905    FieldTypes[1] = IntTy;
3906    // const char *str;
3907    FieldTypes[2] = getPointerType(CharTy.withConst());
3908    // long length;
3909    FieldTypes[3] = LongTy;
3910
3911    // Create fields
3912    for (unsigned i = 0; i < 4; ++i) {
3913      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3914                                           SourceLocation(),
3915                                           SourceLocation(), 0,
3916                                           FieldTypes[i], /*TInfo=*/0,
3917                                           /*BitWidth=*/0,
3918                                           /*Mutable=*/false,
3919                                           ICIS_NoInit);
3920      Field->setAccess(AS_public);
3921      CFConstantStringTypeDecl->addDecl(Field);
3922    }
3923
3924    CFConstantStringTypeDecl->completeDefinition();
3925  }
3926
3927  return getTagDeclType(CFConstantStringTypeDecl);
3928}
3929
3930void ASTContext::setCFConstantStringType(QualType T) {
3931  const RecordType *Rec = T->getAs<RecordType>();
3932  assert(Rec && "Invalid CFConstantStringType");
3933  CFConstantStringTypeDecl = Rec->getDecl();
3934}
3935
3936QualType ASTContext::getBlockDescriptorType() const {
3937  if (BlockDescriptorType)
3938    return getTagDeclType(BlockDescriptorType);
3939
3940  RecordDecl *T;
3941  // FIXME: Needs the FlagAppleBlock bit.
3942  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3943                       &Idents.get("__block_descriptor"));
3944  T->startDefinition();
3945
3946  QualType FieldTypes[] = {
3947    UnsignedLongTy,
3948    UnsignedLongTy,
3949  };
3950
3951  const char *FieldNames[] = {
3952    "reserved",
3953    "Size"
3954  };
3955
3956  for (size_t i = 0; i < 2; ++i) {
3957    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3958                                         SourceLocation(),
3959                                         &Idents.get(FieldNames[i]),
3960                                         FieldTypes[i], /*TInfo=*/0,
3961                                         /*BitWidth=*/0,
3962                                         /*Mutable=*/false,
3963                                         ICIS_NoInit);
3964    Field->setAccess(AS_public);
3965    T->addDecl(Field);
3966  }
3967
3968  T->completeDefinition();
3969
3970  BlockDescriptorType = T;
3971
3972  return getTagDeclType(BlockDescriptorType);
3973}
3974
3975QualType ASTContext::getBlockDescriptorExtendedType() const {
3976  if (BlockDescriptorExtendedType)
3977    return getTagDeclType(BlockDescriptorExtendedType);
3978
3979  RecordDecl *T;
3980  // FIXME: Needs the FlagAppleBlock bit.
3981  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3982                       &Idents.get("__block_descriptor_withcopydispose"));
3983  T->startDefinition();
3984
3985  QualType FieldTypes[] = {
3986    UnsignedLongTy,
3987    UnsignedLongTy,
3988    getPointerType(VoidPtrTy),
3989    getPointerType(VoidPtrTy)
3990  };
3991
3992  const char *FieldNames[] = {
3993    "reserved",
3994    "Size",
3995    "CopyFuncPtr",
3996    "DestroyFuncPtr"
3997  };
3998
3999  for (size_t i = 0; i < 4; ++i) {
4000    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4001                                         SourceLocation(),
4002                                         &Idents.get(FieldNames[i]),
4003                                         FieldTypes[i], /*TInfo=*/0,
4004                                         /*BitWidth=*/0,
4005                                         /*Mutable=*/false,
4006                                         ICIS_NoInit);
4007    Field->setAccess(AS_public);
4008    T->addDecl(Field);
4009  }
4010
4011  T->completeDefinition();
4012
4013  BlockDescriptorExtendedType = T;
4014
4015  return getTagDeclType(BlockDescriptorExtendedType);
4016}
4017
4018bool ASTContext::BlockRequiresCopying(QualType Ty) const {
4019  if (Ty->isObjCRetainableType())
4020    return true;
4021  if (getLangOpts().CPlusPlus) {
4022    if (const RecordType *RT = Ty->getAs<RecordType>()) {
4023      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4024      return RD->hasConstCopyConstructor();
4025
4026    }
4027  }
4028  return false;
4029}
4030
4031QualType
4032ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
4033  //  type = struct __Block_byref_1_X {
4034  //    void *__isa;
4035  //    struct __Block_byref_1_X *__forwarding;
4036  //    unsigned int __flags;
4037  //    unsigned int __size;
4038  //    void *__copy_helper;            // as needed
4039  //    void *__destroy_help            // as needed
4040  //    int X;
4041  //  } *
4042
4043  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4044
4045  // FIXME: Move up
4046  SmallString<36> Name;
4047  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4048                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
4049  RecordDecl *T;
4050  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
4051  T->startDefinition();
4052  QualType Int32Ty = IntTy;
4053  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4054  QualType FieldTypes[] = {
4055    getPointerType(VoidPtrTy),
4056    getPointerType(getTagDeclType(T)),
4057    Int32Ty,
4058    Int32Ty,
4059    getPointerType(VoidPtrTy),
4060    getPointerType(VoidPtrTy),
4061    Ty
4062  };
4063
4064  StringRef FieldNames[] = {
4065    "__isa",
4066    "__forwarding",
4067    "__flags",
4068    "__size",
4069    "__copy_helper",
4070    "__destroy_helper",
4071    DeclName,
4072  };
4073
4074  for (size_t i = 0; i < 7; ++i) {
4075    if (!HasCopyAndDispose && i >=4 && i <= 5)
4076      continue;
4077    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4078                                         SourceLocation(),
4079                                         &Idents.get(FieldNames[i]),
4080                                         FieldTypes[i], /*TInfo=*/0,
4081                                         /*BitWidth=*/0, /*Mutable=*/false,
4082                                         ICIS_NoInit);
4083    Field->setAccess(AS_public);
4084    T->addDecl(Field);
4085  }
4086
4087  T->completeDefinition();
4088
4089  return getPointerType(getTagDeclType(T));
4090}
4091
4092TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4093  if (!ObjCInstanceTypeDecl)
4094    ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4095                                               getTranslationUnitDecl(),
4096                                               SourceLocation(),
4097                                               SourceLocation(),
4098                                               &Idents.get("instancetype"),
4099                                     getTrivialTypeSourceInfo(getObjCIdType()));
4100  return ObjCInstanceTypeDecl;
4101}
4102
4103// This returns true if a type has been typedefed to BOOL:
4104// typedef <type> BOOL;
4105static bool isTypeTypedefedAsBOOL(QualType T) {
4106  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4107    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4108      return II->isStr("BOOL");
4109
4110  return false;
4111}
4112
4113/// getObjCEncodingTypeSize returns size of type for objective-c encoding
4114/// purpose.
4115CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4116  if (!type->isIncompleteArrayType() && type->isIncompleteType())
4117    return CharUnits::Zero();
4118
4119  CharUnits sz = getTypeSizeInChars(type);
4120
4121  // Make all integer and enum types at least as large as an int
4122  if (sz.isPositive() && type->isIntegralOrEnumerationType())
4123    sz = std::max(sz, getTypeSizeInChars(IntTy));
4124  // Treat arrays as pointers, since that's how they're passed in.
4125  else if (type->isArrayType())
4126    sz = getTypeSizeInChars(VoidPtrTy);
4127  return sz;
4128}
4129
4130static inline
4131std::string charUnitsToString(const CharUnits &CU) {
4132  return llvm::itostr(CU.getQuantity());
4133}
4134
4135/// getObjCEncodingForBlock - Return the encoded type for this block
4136/// declaration.
4137std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4138  std::string S;
4139
4140  const BlockDecl *Decl = Expr->getBlockDecl();
4141  QualType BlockTy =
4142      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4143  // Encode result type.
4144  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
4145  // Compute size of all parameters.
4146  // Start with computing size of a pointer in number of bytes.
4147  // FIXME: There might(should) be a better way of doing this computation!
4148  SourceLocation Loc;
4149  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4150  CharUnits ParmOffset = PtrSize;
4151  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4152       E = Decl->param_end(); PI != E; ++PI) {
4153    QualType PType = (*PI)->getType();
4154    CharUnits sz = getObjCEncodingTypeSize(PType);
4155    if (sz.isZero())
4156      continue;
4157    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4158    ParmOffset += sz;
4159  }
4160  // Size of the argument frame
4161  S += charUnitsToString(ParmOffset);
4162  // Block pointer and offset.
4163  S += "@?0";
4164
4165  // Argument types.
4166  ParmOffset = PtrSize;
4167  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4168       Decl->param_end(); PI != E; ++PI) {
4169    ParmVarDecl *PVDecl = *PI;
4170    QualType PType = PVDecl->getOriginalType();
4171    if (const ArrayType *AT =
4172          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4173      // Use array's original type only if it has known number of
4174      // elements.
4175      if (!isa<ConstantArrayType>(AT))
4176        PType = PVDecl->getType();
4177    } else if (PType->isFunctionType())
4178      PType = PVDecl->getType();
4179    getObjCEncodingForType(PType, S);
4180    S += charUnitsToString(ParmOffset);
4181    ParmOffset += getObjCEncodingTypeSize(PType);
4182  }
4183
4184  return S;
4185}
4186
4187bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4188                                                std::string& S) {
4189  // Encode result type.
4190  getObjCEncodingForType(Decl->getResultType(), S);
4191  CharUnits ParmOffset;
4192  // Compute size of all parameters.
4193  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4194       E = Decl->param_end(); PI != E; ++PI) {
4195    QualType PType = (*PI)->getType();
4196    CharUnits sz = getObjCEncodingTypeSize(PType);
4197    if (sz.isZero())
4198      continue;
4199
4200    assert (sz.isPositive() &&
4201        "getObjCEncodingForFunctionDecl - Incomplete param type");
4202    ParmOffset += sz;
4203  }
4204  S += charUnitsToString(ParmOffset);
4205  ParmOffset = CharUnits::Zero();
4206
4207  // Argument types.
4208  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4209       E = Decl->param_end(); PI != E; ++PI) {
4210    ParmVarDecl *PVDecl = *PI;
4211    QualType PType = PVDecl->getOriginalType();
4212    if (const ArrayType *AT =
4213          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4214      // Use array's original type only if it has known number of
4215      // elements.
4216      if (!isa<ConstantArrayType>(AT))
4217        PType = PVDecl->getType();
4218    } else if (PType->isFunctionType())
4219      PType = PVDecl->getType();
4220    getObjCEncodingForType(PType, S);
4221    S += charUnitsToString(ParmOffset);
4222    ParmOffset += getObjCEncodingTypeSize(PType);
4223  }
4224
4225  return false;
4226}
4227
4228/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4229/// method parameter or return type. If Extended, include class names and
4230/// block object types.
4231void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4232                                                   QualType T, std::string& S,
4233                                                   bool Extended) const {
4234  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4235  getObjCEncodingForTypeQualifier(QT, S);
4236  // Encode parameter type.
4237  getObjCEncodingForTypeImpl(T, S, true, true, 0,
4238                             true     /*OutermostType*/,
4239                             false    /*EncodingProperty*/,
4240                             false    /*StructField*/,
4241                             Extended /*EncodeBlockParameters*/,
4242                             Extended /*EncodeClassNames*/);
4243}
4244
4245/// getObjCEncodingForMethodDecl - Return the encoded type for this method
4246/// declaration.
4247bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4248                                              std::string& S,
4249                                              bool Extended) const {
4250  // FIXME: This is not very efficient.
4251  // Encode return type.
4252  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4253                                    Decl->getResultType(), S, Extended);
4254  // Compute size of all parameters.
4255  // Start with computing size of a pointer in number of bytes.
4256  // FIXME: There might(should) be a better way of doing this computation!
4257  SourceLocation Loc;
4258  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4259  // The first two arguments (self and _cmd) are pointers; account for
4260  // their size.
4261  CharUnits ParmOffset = 2 * PtrSize;
4262  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4263       E = Decl->sel_param_end(); PI != E; ++PI) {
4264    QualType PType = (*PI)->getType();
4265    CharUnits sz = getObjCEncodingTypeSize(PType);
4266    if (sz.isZero())
4267      continue;
4268
4269    assert (sz.isPositive() &&
4270        "getObjCEncodingForMethodDecl - Incomplete param type");
4271    ParmOffset += sz;
4272  }
4273  S += charUnitsToString(ParmOffset);
4274  S += "@0:";
4275  S += charUnitsToString(PtrSize);
4276
4277  // Argument types.
4278  ParmOffset = 2 * PtrSize;
4279  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4280       E = Decl->sel_param_end(); PI != E; ++PI) {
4281    const ParmVarDecl *PVDecl = *PI;
4282    QualType PType = PVDecl->getOriginalType();
4283    if (const ArrayType *AT =
4284          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4285      // Use array's original type only if it has known number of
4286      // elements.
4287      if (!isa<ConstantArrayType>(AT))
4288        PType = PVDecl->getType();
4289    } else if (PType->isFunctionType())
4290      PType = PVDecl->getType();
4291    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4292                                      PType, S, Extended);
4293    S += charUnitsToString(ParmOffset);
4294    ParmOffset += getObjCEncodingTypeSize(PType);
4295  }
4296
4297  return false;
4298}
4299
4300/// getObjCEncodingForPropertyDecl - Return the encoded type for this
4301/// property declaration. If non-NULL, Container must be either an
4302/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4303/// NULL when getting encodings for protocol properties.
4304/// Property attributes are stored as a comma-delimited C string. The simple
4305/// attributes readonly and bycopy are encoded as single characters. The
4306/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4307/// encoded as single characters, followed by an identifier. Property types
4308/// are also encoded as a parametrized attribute. The characters used to encode
4309/// these attributes are defined by the following enumeration:
4310/// @code
4311/// enum PropertyAttributes {
4312/// kPropertyReadOnly = 'R',   // property is read-only.
4313/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
4314/// kPropertyByref = '&',  // property is a reference to the value last assigned
4315/// kPropertyDynamic = 'D',    // property is dynamic
4316/// kPropertyGetter = 'G',     // followed by getter selector name
4317/// kPropertySetter = 'S',     // followed by setter selector name
4318/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
4319/// kPropertyType = 'T'              // followed by old-style type encoding.
4320/// kPropertyWeak = 'W'              // 'weak' property
4321/// kPropertyStrong = 'P'            // property GC'able
4322/// kPropertyNonAtomic = 'N'         // property non-atomic
4323/// };
4324/// @endcode
4325void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4326                                                const Decl *Container,
4327                                                std::string& S) const {
4328  // Collect information from the property implementation decl(s).
4329  bool Dynamic = false;
4330  ObjCPropertyImplDecl *SynthesizePID = 0;
4331
4332  // FIXME: Duplicated code due to poor abstraction.
4333  if (Container) {
4334    if (const ObjCCategoryImplDecl *CID =
4335        dyn_cast<ObjCCategoryImplDecl>(Container)) {
4336      for (ObjCCategoryImplDecl::propimpl_iterator
4337             i = CID->propimpl_begin(), e = CID->propimpl_end();
4338           i != e; ++i) {
4339        ObjCPropertyImplDecl *PID = *i;
4340        if (PID->getPropertyDecl() == PD) {
4341          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4342            Dynamic = true;
4343          } else {
4344            SynthesizePID = PID;
4345          }
4346        }
4347      }
4348    } else {
4349      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4350      for (ObjCCategoryImplDecl::propimpl_iterator
4351             i = OID->propimpl_begin(), e = OID->propimpl_end();
4352           i != e; ++i) {
4353        ObjCPropertyImplDecl *PID = *i;
4354        if (PID->getPropertyDecl() == PD) {
4355          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4356            Dynamic = true;
4357          } else {
4358            SynthesizePID = PID;
4359          }
4360        }
4361      }
4362    }
4363  }
4364
4365  // FIXME: This is not very efficient.
4366  S = "T";
4367
4368  // Encode result type.
4369  // GCC has some special rules regarding encoding of properties which
4370  // closely resembles encoding of ivars.
4371  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4372                             true /* outermost type */,
4373                             true /* encoding for property */);
4374
4375  if (PD->isReadOnly()) {
4376    S += ",R";
4377  } else {
4378    switch (PD->getSetterKind()) {
4379    case ObjCPropertyDecl::Assign: break;
4380    case ObjCPropertyDecl::Copy:   S += ",C"; break;
4381    case ObjCPropertyDecl::Retain: S += ",&"; break;
4382    case ObjCPropertyDecl::Weak:   S += ",W"; break;
4383    }
4384  }
4385
4386  // It really isn't clear at all what this means, since properties
4387  // are "dynamic by default".
4388  if (Dynamic)
4389    S += ",D";
4390
4391  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4392    S += ",N";
4393
4394  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4395    S += ",G";
4396    S += PD->getGetterName().getAsString();
4397  }
4398
4399  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4400    S += ",S";
4401    S += PD->getSetterName().getAsString();
4402  }
4403
4404  if (SynthesizePID) {
4405    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4406    S += ",V";
4407    S += OID->getNameAsString();
4408  }
4409
4410  // FIXME: OBJCGC: weak & strong
4411}
4412
4413/// getLegacyIntegralTypeEncoding -
4414/// Another legacy compatibility encoding: 32-bit longs are encoded as
4415/// 'l' or 'L' , but not always.  For typedefs, we need to use
4416/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4417///
4418void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4419  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4420    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4421      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4422        PointeeTy = UnsignedIntTy;
4423      else
4424        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4425          PointeeTy = IntTy;
4426    }
4427  }
4428}
4429
4430void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4431                                        const FieldDecl *Field) const {
4432  // We follow the behavior of gcc, expanding structures which are
4433  // directly pointed to, and expanding embedded structures. Note that
4434  // these rules are sufficient to prevent recursive encoding of the
4435  // same type.
4436  getObjCEncodingForTypeImpl(T, S, true, true, Field,
4437                             true /* outermost type */);
4438}
4439
4440static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4441    switch (T->getAs<BuiltinType>()->getKind()) {
4442    default: llvm_unreachable("Unhandled builtin type kind");
4443    case BuiltinType::Void:       return 'v';
4444    case BuiltinType::Bool:       return 'B';
4445    case BuiltinType::Char_U:
4446    case BuiltinType::UChar:      return 'C';
4447    case BuiltinType::UShort:     return 'S';
4448    case BuiltinType::UInt:       return 'I';
4449    case BuiltinType::ULong:
4450        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4451    case BuiltinType::UInt128:    return 'T';
4452    case BuiltinType::ULongLong:  return 'Q';
4453    case BuiltinType::Char_S:
4454    case BuiltinType::SChar:      return 'c';
4455    case BuiltinType::Short:      return 's';
4456    case BuiltinType::WChar_S:
4457    case BuiltinType::WChar_U:
4458    case BuiltinType::Int:        return 'i';
4459    case BuiltinType::Long:
4460      return C->getIntWidth(T) == 32 ? 'l' : 'q';
4461    case BuiltinType::LongLong:   return 'q';
4462    case BuiltinType::Int128:     return 't';
4463    case BuiltinType::Float:      return 'f';
4464    case BuiltinType::Double:     return 'd';
4465    case BuiltinType::LongDouble: return 'D';
4466    }
4467}
4468
4469static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4470  EnumDecl *Enum = ET->getDecl();
4471
4472  // The encoding of an non-fixed enum type is always 'i', regardless of size.
4473  if (!Enum->isFixed())
4474    return 'i';
4475
4476  // The encoding of a fixed enum type matches its fixed underlying type.
4477  return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4478}
4479
4480static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4481                           QualType T, const FieldDecl *FD) {
4482  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4483  S += 'b';
4484  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4485  // The GNU runtime requires more information; bitfields are encoded as b,
4486  // then the offset (in bits) of the first element, then the type of the
4487  // bitfield, then the size in bits.  For example, in this structure:
4488  //
4489  // struct
4490  // {
4491  //    int integer;
4492  //    int flags:2;
4493  // };
4494  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4495  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4496  // information is not especially sensible, but we're stuck with it for
4497  // compatibility with GCC, although providing it breaks anything that
4498  // actually uses runtime introspection and wants to work on both runtimes...
4499  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
4500    const RecordDecl *RD = FD->getParent();
4501    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4502    S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4503    if (const EnumType *ET = T->getAs<EnumType>())
4504      S += ObjCEncodingForEnumType(Ctx, ET);
4505    else
4506      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4507  }
4508  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4509}
4510
4511// FIXME: Use SmallString for accumulating string.
4512void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4513                                            bool ExpandPointedToStructures,
4514                                            bool ExpandStructures,
4515                                            const FieldDecl *FD,
4516                                            bool OutermostType,
4517                                            bool EncodingProperty,
4518                                            bool StructField,
4519                                            bool EncodeBlockParameters,
4520                                            bool EncodeClassNames) const {
4521  if (T->getAs<BuiltinType>()) {
4522    if (FD && FD->isBitField())
4523      return EncodeBitField(this, S, T, FD);
4524    S += ObjCEncodingForPrimitiveKind(this, T);
4525    return;
4526  }
4527
4528  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4529    S += 'j';
4530    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4531                               false);
4532    return;
4533  }
4534
4535  // encoding for pointer or r3eference types.
4536  QualType PointeeTy;
4537  if (const PointerType *PT = T->getAs<PointerType>()) {
4538    if (PT->isObjCSelType()) {
4539      S += ':';
4540      return;
4541    }
4542    PointeeTy = PT->getPointeeType();
4543  }
4544  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4545    PointeeTy = RT->getPointeeType();
4546  if (!PointeeTy.isNull()) {
4547    bool isReadOnly = false;
4548    // For historical/compatibility reasons, the read-only qualifier of the
4549    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4550    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4551    // Also, do not emit the 'r' for anything but the outermost type!
4552    if (isa<TypedefType>(T.getTypePtr())) {
4553      if (OutermostType && T.isConstQualified()) {
4554        isReadOnly = true;
4555        S += 'r';
4556      }
4557    } else if (OutermostType) {
4558      QualType P = PointeeTy;
4559      while (P->getAs<PointerType>())
4560        P = P->getAs<PointerType>()->getPointeeType();
4561      if (P.isConstQualified()) {
4562        isReadOnly = true;
4563        S += 'r';
4564      }
4565    }
4566    if (isReadOnly) {
4567      // Another legacy compatibility encoding. Some ObjC qualifier and type
4568      // combinations need to be rearranged.
4569      // Rewrite "in const" from "nr" to "rn"
4570      if (StringRef(S).endswith("nr"))
4571        S.replace(S.end()-2, S.end(), "rn");
4572    }
4573
4574    if (PointeeTy->isCharType()) {
4575      // char pointer types should be encoded as '*' unless it is a
4576      // type that has been typedef'd to 'BOOL'.
4577      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4578        S += '*';
4579        return;
4580      }
4581    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4582      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4583      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4584        S += '#';
4585        return;
4586      }
4587      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4588      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4589        S += '@';
4590        return;
4591      }
4592      // fall through...
4593    }
4594    S += '^';
4595    getLegacyIntegralTypeEncoding(PointeeTy);
4596
4597    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4598                               NULL);
4599    return;
4600  }
4601
4602  if (const ArrayType *AT =
4603      // Ignore type qualifiers etc.
4604        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4605    if (isa<IncompleteArrayType>(AT) && !StructField) {
4606      // Incomplete arrays are encoded as a pointer to the array element.
4607      S += '^';
4608
4609      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4610                                 false, ExpandStructures, FD);
4611    } else {
4612      S += '[';
4613
4614      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4615        if (getTypeSize(CAT->getElementType()) == 0)
4616          S += '0';
4617        else
4618          S += llvm::utostr(CAT->getSize().getZExtValue());
4619      } else {
4620        //Variable length arrays are encoded as a regular array with 0 elements.
4621        assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4622               "Unknown array type!");
4623        S += '0';
4624      }
4625
4626      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4627                                 false, ExpandStructures, FD);
4628      S += ']';
4629    }
4630    return;
4631  }
4632
4633  if (T->getAs<FunctionType>()) {
4634    S += '?';
4635    return;
4636  }
4637
4638  if (const RecordType *RTy = T->getAs<RecordType>()) {
4639    RecordDecl *RDecl = RTy->getDecl();
4640    S += RDecl->isUnion() ? '(' : '{';
4641    // Anonymous structures print as '?'
4642    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4643      S += II->getName();
4644      if (ClassTemplateSpecializationDecl *Spec
4645          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4646        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4647        std::string TemplateArgsStr
4648          = TemplateSpecializationType::PrintTemplateArgumentList(
4649                                            TemplateArgs.data(),
4650                                            TemplateArgs.size(),
4651                                            (*this).getPrintingPolicy());
4652
4653        S += TemplateArgsStr;
4654      }
4655    } else {
4656      S += '?';
4657    }
4658    if (ExpandStructures) {
4659      S += '=';
4660      if (!RDecl->isUnion()) {
4661        getObjCEncodingForStructureImpl(RDecl, S, FD);
4662      } else {
4663        for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4664                                     FieldEnd = RDecl->field_end();
4665             Field != FieldEnd; ++Field) {
4666          if (FD) {
4667            S += '"';
4668            S += Field->getNameAsString();
4669            S += '"';
4670          }
4671
4672          // Special case bit-fields.
4673          if (Field->isBitField()) {
4674            getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4675                                       *Field);
4676          } else {
4677            QualType qt = Field->getType();
4678            getLegacyIntegralTypeEncoding(qt);
4679            getObjCEncodingForTypeImpl(qt, S, false, true,
4680                                       FD, /*OutermostType*/false,
4681                                       /*EncodingProperty*/false,
4682                                       /*StructField*/true);
4683          }
4684        }
4685      }
4686    }
4687    S += RDecl->isUnion() ? ')' : '}';
4688    return;
4689  }
4690
4691  if (const EnumType *ET = T->getAs<EnumType>()) {
4692    if (FD && FD->isBitField())
4693      EncodeBitField(this, S, T, FD);
4694    else
4695      S += ObjCEncodingForEnumType(this, ET);
4696    return;
4697  }
4698
4699  if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
4700    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4701    if (EncodeBlockParameters) {
4702      const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4703
4704      S += '<';
4705      // Block return type
4706      getObjCEncodingForTypeImpl(FT->getResultType(), S,
4707                                 ExpandPointedToStructures, ExpandStructures,
4708                                 FD,
4709                                 false /* OutermostType */,
4710                                 EncodingProperty,
4711                                 false /* StructField */,
4712                                 EncodeBlockParameters,
4713                                 EncodeClassNames);
4714      // Block self
4715      S += "@?";
4716      // Block parameters
4717      if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4718        for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4719               E = FPT->arg_type_end(); I && (I != E); ++I) {
4720          getObjCEncodingForTypeImpl(*I, S,
4721                                     ExpandPointedToStructures,
4722                                     ExpandStructures,
4723                                     FD,
4724                                     false /* OutermostType */,
4725                                     EncodingProperty,
4726                                     false /* StructField */,
4727                                     EncodeBlockParameters,
4728                                     EncodeClassNames);
4729        }
4730      }
4731      S += '>';
4732    }
4733    return;
4734  }
4735
4736  // Ignore protocol qualifiers when mangling at this level.
4737  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4738    T = OT->getBaseType();
4739
4740  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4741    // @encode(class_name)
4742    ObjCInterfaceDecl *OI = OIT->getDecl();
4743    S += '{';
4744    const IdentifierInfo *II = OI->getIdentifier();
4745    S += II->getName();
4746    S += '=';
4747    SmallVector<const ObjCIvarDecl*, 32> Ivars;
4748    DeepCollectObjCIvars(OI, true, Ivars);
4749    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4750      const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4751      if (Field->isBitField())
4752        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4753      else
4754        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4755    }
4756    S += '}';
4757    return;
4758  }
4759
4760  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4761    if (OPT->isObjCIdType()) {
4762      S += '@';
4763      return;
4764    }
4765
4766    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4767      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4768      // Since this is a binary compatibility issue, need to consult with runtime
4769      // folks. Fortunately, this is a *very* obsure construct.
4770      S += '#';
4771      return;
4772    }
4773
4774    if (OPT->isObjCQualifiedIdType()) {
4775      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4776                                 ExpandPointedToStructures,
4777                                 ExpandStructures, FD);
4778      if (FD || EncodingProperty || EncodeClassNames) {
4779        // Note that we do extended encoding of protocol qualifer list
4780        // Only when doing ivar or property encoding.
4781        S += '"';
4782        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4783             E = OPT->qual_end(); I != E; ++I) {
4784          S += '<';
4785          S += (*I)->getNameAsString();
4786          S += '>';
4787        }
4788        S += '"';
4789      }
4790      return;
4791    }
4792
4793    QualType PointeeTy = OPT->getPointeeType();
4794    if (!EncodingProperty &&
4795        isa<TypedefType>(PointeeTy.getTypePtr())) {
4796      // Another historical/compatibility reason.
4797      // We encode the underlying type which comes out as
4798      // {...};
4799      S += '^';
4800      getObjCEncodingForTypeImpl(PointeeTy, S,
4801                                 false, ExpandPointedToStructures,
4802                                 NULL);
4803      return;
4804    }
4805
4806    S += '@';
4807    if (OPT->getInterfaceDecl() &&
4808        (FD || EncodingProperty || EncodeClassNames)) {
4809      S += '"';
4810      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4811      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4812           E = OPT->qual_end(); I != E; ++I) {
4813        S += '<';
4814        S += (*I)->getNameAsString();
4815        S += '>';
4816      }
4817      S += '"';
4818    }
4819    return;
4820  }
4821
4822  // gcc just blithely ignores member pointers.
4823  // TODO: maybe there should be a mangling for these
4824  if (T->getAs<MemberPointerType>())
4825    return;
4826
4827  if (T->isVectorType()) {
4828    // This matches gcc's encoding, even though technically it is
4829    // insufficient.
4830    // FIXME. We should do a better job than gcc.
4831    return;
4832  }
4833
4834  llvm_unreachable("@encode for type not implemented!");
4835}
4836
4837void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4838                                                 std::string &S,
4839                                                 const FieldDecl *FD,
4840                                                 bool includeVBases) const {
4841  assert(RDecl && "Expected non-null RecordDecl");
4842  assert(!RDecl->isUnion() && "Should not be called for unions");
4843  if (!RDecl->getDefinition())
4844    return;
4845
4846  CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4847  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4848  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4849
4850  if (CXXRec) {
4851    for (CXXRecordDecl::base_class_iterator
4852           BI = CXXRec->bases_begin(),
4853           BE = CXXRec->bases_end(); BI != BE; ++BI) {
4854      if (!BI->isVirtual()) {
4855        CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4856        if (base->isEmpty())
4857          continue;
4858        uint64_t offs = layout.getBaseClassOffsetInBits(base);
4859        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4860                                  std::make_pair(offs, base));
4861      }
4862    }
4863  }
4864
4865  unsigned i = 0;
4866  for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4867                               FieldEnd = RDecl->field_end();
4868       Field != FieldEnd; ++Field, ++i) {
4869    uint64_t offs = layout.getFieldOffset(i);
4870    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4871                              std::make_pair(offs, *Field));
4872  }
4873
4874  if (CXXRec && includeVBases) {
4875    for (CXXRecordDecl::base_class_iterator
4876           BI = CXXRec->vbases_begin(),
4877           BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4878      CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4879      if (base->isEmpty())
4880        continue;
4881      uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4882      if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4883        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4884                                  std::make_pair(offs, base));
4885    }
4886  }
4887
4888  CharUnits size;
4889  if (CXXRec) {
4890    size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4891  } else {
4892    size = layout.getSize();
4893  }
4894
4895  uint64_t CurOffs = 0;
4896  std::multimap<uint64_t, NamedDecl *>::iterator
4897    CurLayObj = FieldOrBaseOffsets.begin();
4898
4899  if (CXXRec && CXXRec->isDynamicClass() &&
4900      (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
4901    if (FD) {
4902      S += "\"_vptr$";
4903      std::string recname = CXXRec->getNameAsString();
4904      if (recname.empty()) recname = "?";
4905      S += recname;
4906      S += '"';
4907    }
4908    S += "^^?";
4909    CurOffs += getTypeSize(VoidPtrTy);
4910  }
4911
4912  if (!RDecl->hasFlexibleArrayMember()) {
4913    // Mark the end of the structure.
4914    uint64_t offs = toBits(size);
4915    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4916                              std::make_pair(offs, (NamedDecl*)0));
4917  }
4918
4919  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4920    assert(CurOffs <= CurLayObj->first);
4921
4922    if (CurOffs < CurLayObj->first) {
4923      uint64_t padding = CurLayObj->first - CurOffs;
4924      // FIXME: There doesn't seem to be a way to indicate in the encoding that
4925      // packing/alignment of members is different that normal, in which case
4926      // the encoding will be out-of-sync with the real layout.
4927      // If the runtime switches to just consider the size of types without
4928      // taking into account alignment, we could make padding explicit in the
4929      // encoding (e.g. using arrays of chars). The encoding strings would be
4930      // longer then though.
4931      CurOffs += padding;
4932    }
4933
4934    NamedDecl *dcl = CurLayObj->second;
4935    if (dcl == 0)
4936      break; // reached end of structure.
4937
4938    if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4939      // We expand the bases without their virtual bases since those are going
4940      // in the initial structure. Note that this differs from gcc which
4941      // expands virtual bases each time one is encountered in the hierarchy,
4942      // making the encoding type bigger than it really is.
4943      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4944      assert(!base->isEmpty());
4945      CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4946    } else {
4947      FieldDecl *field = cast<FieldDecl>(dcl);
4948      if (FD) {
4949        S += '"';
4950        S += field->getNameAsString();
4951        S += '"';
4952      }
4953
4954      if (field->isBitField()) {
4955        EncodeBitField(this, S, field->getType(), field);
4956        CurOffs += field->getBitWidthValue(*this);
4957      } else {
4958        QualType qt = field->getType();
4959        getLegacyIntegralTypeEncoding(qt);
4960        getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4961                                   /*OutermostType*/false,
4962                                   /*EncodingProperty*/false,
4963                                   /*StructField*/true);
4964        CurOffs += getTypeSize(field->getType());
4965      }
4966    }
4967  }
4968}
4969
4970void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4971                                                 std::string& S) const {
4972  if (QT & Decl::OBJC_TQ_In)
4973    S += 'n';
4974  if (QT & Decl::OBJC_TQ_Inout)
4975    S += 'N';
4976  if (QT & Decl::OBJC_TQ_Out)
4977    S += 'o';
4978  if (QT & Decl::OBJC_TQ_Bycopy)
4979    S += 'O';
4980  if (QT & Decl::OBJC_TQ_Byref)
4981    S += 'R';
4982  if (QT & Decl::OBJC_TQ_Oneway)
4983    S += 'V';
4984}
4985
4986TypedefDecl *ASTContext::getObjCIdDecl() const {
4987  if (!ObjCIdDecl) {
4988    QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4989    T = getObjCObjectPointerType(T);
4990    TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4991    ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4992                                     getTranslationUnitDecl(),
4993                                     SourceLocation(), SourceLocation(),
4994                                     &Idents.get("id"), IdInfo);
4995  }
4996
4997  return ObjCIdDecl;
4998}
4999
5000TypedefDecl *ASTContext::getObjCSelDecl() const {
5001  if (!ObjCSelDecl) {
5002    QualType SelT = getPointerType(ObjCBuiltinSelTy);
5003    TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5004    ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5005                                      getTranslationUnitDecl(),
5006                                      SourceLocation(), SourceLocation(),
5007                                      &Idents.get("SEL"), SelInfo);
5008  }
5009  return ObjCSelDecl;
5010}
5011
5012TypedefDecl *ASTContext::getObjCClassDecl() const {
5013  if (!ObjCClassDecl) {
5014    QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5015    T = getObjCObjectPointerType(T);
5016    TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5017    ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5018                                        getTranslationUnitDecl(),
5019                                        SourceLocation(), SourceLocation(),
5020                                        &Idents.get("Class"), ClassInfo);
5021  }
5022
5023  return ObjCClassDecl;
5024}
5025
5026ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5027  if (!ObjCProtocolClassDecl) {
5028    ObjCProtocolClassDecl
5029      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5030                                  SourceLocation(),
5031                                  &Idents.get("Protocol"),
5032                                  /*PrevDecl=*/0,
5033                                  SourceLocation(), true);
5034  }
5035
5036  return ObjCProtocolClassDecl;
5037}
5038
5039//===----------------------------------------------------------------------===//
5040// __builtin_va_list Construction Functions
5041//===----------------------------------------------------------------------===//
5042
5043static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5044  // typedef char* __builtin_va_list;
5045  QualType CharPtrType = Context->getPointerType(Context->CharTy);
5046  TypeSourceInfo *TInfo
5047    = Context->getTrivialTypeSourceInfo(CharPtrType);
5048
5049  TypedefDecl *VaListTypeDecl
5050    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5051                          Context->getTranslationUnitDecl(),
5052                          SourceLocation(), SourceLocation(),
5053                          &Context->Idents.get("__builtin_va_list"),
5054                          TInfo);
5055  return VaListTypeDecl;
5056}
5057
5058static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5059  // typedef void* __builtin_va_list;
5060  QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5061  TypeSourceInfo *TInfo
5062    = Context->getTrivialTypeSourceInfo(VoidPtrType);
5063
5064  TypedefDecl *VaListTypeDecl
5065    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5066                          Context->getTranslationUnitDecl(),
5067                          SourceLocation(), SourceLocation(),
5068                          &Context->Idents.get("__builtin_va_list"),
5069                          TInfo);
5070  return VaListTypeDecl;
5071}
5072
5073static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5074  // typedef struct __va_list_tag {
5075  RecordDecl *VaListTagDecl;
5076
5077  VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5078                                   Context->getTranslationUnitDecl(),
5079                                   &Context->Idents.get("__va_list_tag"));
5080  VaListTagDecl->startDefinition();
5081
5082  const size_t NumFields = 5;
5083  QualType FieldTypes[NumFields];
5084  const char *FieldNames[NumFields];
5085
5086  //   unsigned char gpr;
5087  FieldTypes[0] = Context->UnsignedCharTy;
5088  FieldNames[0] = "gpr";
5089
5090  //   unsigned char fpr;
5091  FieldTypes[1] = Context->UnsignedCharTy;
5092  FieldNames[1] = "fpr";
5093
5094  //   unsigned short reserved;
5095  FieldTypes[2] = Context->UnsignedShortTy;
5096  FieldNames[2] = "reserved";
5097
5098  //   void* overflow_arg_area;
5099  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5100  FieldNames[3] = "overflow_arg_area";
5101
5102  //   void* reg_save_area;
5103  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5104  FieldNames[4] = "reg_save_area";
5105
5106  // Create fields
5107  for (unsigned i = 0; i < NumFields; ++i) {
5108    FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5109                                         SourceLocation(),
5110                                         SourceLocation(),
5111                                         &Context->Idents.get(FieldNames[i]),
5112                                         FieldTypes[i], /*TInfo=*/0,
5113                                         /*BitWidth=*/0,
5114                                         /*Mutable=*/false,
5115                                         ICIS_NoInit);
5116    Field->setAccess(AS_public);
5117    VaListTagDecl->addDecl(Field);
5118  }
5119  VaListTagDecl->completeDefinition();
5120  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5121  Context->VaListTagTy = VaListTagType;
5122
5123  // } __va_list_tag;
5124  TypedefDecl *VaListTagTypedefDecl
5125    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5126                          Context->getTranslationUnitDecl(),
5127                          SourceLocation(), SourceLocation(),
5128                          &Context->Idents.get("__va_list_tag"),
5129                          Context->getTrivialTypeSourceInfo(VaListTagType));
5130  QualType VaListTagTypedefType =
5131    Context->getTypedefType(VaListTagTypedefDecl);
5132
5133  // typedef __va_list_tag __builtin_va_list[1];
5134  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5135  QualType VaListTagArrayType
5136    = Context->getConstantArrayType(VaListTagTypedefType,
5137                                    Size, ArrayType::Normal, 0);
5138  TypeSourceInfo *TInfo
5139    = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5140  TypedefDecl *VaListTypedefDecl
5141    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5142                          Context->getTranslationUnitDecl(),
5143                          SourceLocation(), SourceLocation(),
5144                          &Context->Idents.get("__builtin_va_list"),
5145                          TInfo);
5146
5147  return VaListTypedefDecl;
5148}
5149
5150static TypedefDecl *
5151CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5152  // typedef struct __va_list_tag {
5153  RecordDecl *VaListTagDecl;
5154  VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5155                                   Context->getTranslationUnitDecl(),
5156                                   &Context->Idents.get("__va_list_tag"));
5157  VaListTagDecl->startDefinition();
5158
5159  const size_t NumFields = 4;
5160  QualType FieldTypes[NumFields];
5161  const char *FieldNames[NumFields];
5162
5163  //   unsigned gp_offset;
5164  FieldTypes[0] = Context->UnsignedIntTy;
5165  FieldNames[0] = "gp_offset";
5166
5167  //   unsigned fp_offset;
5168  FieldTypes[1] = Context->UnsignedIntTy;
5169  FieldNames[1] = "fp_offset";
5170
5171  //   void* overflow_arg_area;
5172  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5173  FieldNames[2] = "overflow_arg_area";
5174
5175  //   void* reg_save_area;
5176  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5177  FieldNames[3] = "reg_save_area";
5178
5179  // Create fields
5180  for (unsigned i = 0; i < NumFields; ++i) {
5181    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5182                                         VaListTagDecl,
5183                                         SourceLocation(),
5184                                         SourceLocation(),
5185                                         &Context->Idents.get(FieldNames[i]),
5186                                         FieldTypes[i], /*TInfo=*/0,
5187                                         /*BitWidth=*/0,
5188                                         /*Mutable=*/false,
5189                                         ICIS_NoInit);
5190    Field->setAccess(AS_public);
5191    VaListTagDecl->addDecl(Field);
5192  }
5193  VaListTagDecl->completeDefinition();
5194  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5195  Context->VaListTagTy = VaListTagType;
5196
5197  // } __va_list_tag;
5198  TypedefDecl *VaListTagTypedefDecl
5199    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5200                          Context->getTranslationUnitDecl(),
5201                          SourceLocation(), SourceLocation(),
5202                          &Context->Idents.get("__va_list_tag"),
5203                          Context->getTrivialTypeSourceInfo(VaListTagType));
5204  QualType VaListTagTypedefType =
5205    Context->getTypedefType(VaListTagTypedefDecl);
5206
5207  // typedef __va_list_tag __builtin_va_list[1];
5208  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5209  QualType VaListTagArrayType
5210    = Context->getConstantArrayType(VaListTagTypedefType,
5211                                      Size, ArrayType::Normal,0);
5212  TypeSourceInfo *TInfo
5213    = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5214  TypedefDecl *VaListTypedefDecl
5215    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5216                          Context->getTranslationUnitDecl(),
5217                          SourceLocation(), SourceLocation(),
5218                          &Context->Idents.get("__builtin_va_list"),
5219                          TInfo);
5220
5221  return VaListTypedefDecl;
5222}
5223
5224static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5225  // typedef int __builtin_va_list[4];
5226  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5227  QualType IntArrayType
5228    = Context->getConstantArrayType(Context->IntTy,
5229				    Size, ArrayType::Normal, 0);
5230  TypedefDecl *VaListTypedefDecl
5231    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5232                          Context->getTranslationUnitDecl(),
5233                          SourceLocation(), SourceLocation(),
5234                          &Context->Idents.get("__builtin_va_list"),
5235                          Context->getTrivialTypeSourceInfo(IntArrayType));
5236
5237  return VaListTypedefDecl;
5238}
5239
5240static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5241                                     TargetInfo::BuiltinVaListKind Kind) {
5242  switch (Kind) {
5243  case TargetInfo::CharPtrBuiltinVaList:
5244    return CreateCharPtrBuiltinVaListDecl(Context);
5245  case TargetInfo::VoidPtrBuiltinVaList:
5246    return CreateVoidPtrBuiltinVaListDecl(Context);
5247  case TargetInfo::PowerABIBuiltinVaList:
5248    return CreatePowerABIBuiltinVaListDecl(Context);
5249  case TargetInfo::X86_64ABIBuiltinVaList:
5250    return CreateX86_64ABIBuiltinVaListDecl(Context);
5251  case TargetInfo::PNaClABIBuiltinVaList:
5252    return CreatePNaClABIBuiltinVaListDecl(Context);
5253  }
5254
5255  llvm_unreachable("Unhandled __builtin_va_list type kind");
5256}
5257
5258TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5259  if (!BuiltinVaListDecl)
5260    BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5261
5262  return BuiltinVaListDecl;
5263}
5264
5265QualType ASTContext::getVaListTagType() const {
5266  // Force the creation of VaListTagTy by building the __builtin_va_list
5267  // declaration.
5268  if (VaListTagTy.isNull())
5269    (void) getBuiltinVaListDecl();
5270
5271  return VaListTagTy;
5272}
5273
5274void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
5275  assert(ObjCConstantStringType.isNull() &&
5276         "'NSConstantString' type already set!");
5277
5278  ObjCConstantStringType = getObjCInterfaceType(Decl);
5279}
5280
5281/// \brief Retrieve the template name that corresponds to a non-empty
5282/// lookup.
5283TemplateName
5284ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5285                                      UnresolvedSetIterator End) const {
5286  unsigned size = End - Begin;
5287  assert(size > 1 && "set is not overloaded!");
5288
5289  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5290                          size * sizeof(FunctionTemplateDecl*));
5291  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5292
5293  NamedDecl **Storage = OT->getStorage();
5294  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
5295    NamedDecl *D = *I;
5296    assert(isa<FunctionTemplateDecl>(D) ||
5297           (isa<UsingShadowDecl>(D) &&
5298            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5299    *Storage++ = D;
5300  }
5301
5302  return TemplateName(OT);
5303}
5304
5305/// \brief Retrieve the template name that represents a qualified
5306/// template name such as \c std::vector.
5307TemplateName
5308ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5309                                     bool TemplateKeyword,
5310                                     TemplateDecl *Template) const {
5311  assert(NNS && "Missing nested-name-specifier in qualified template name");
5312
5313  // FIXME: Canonicalization?
5314  llvm::FoldingSetNodeID ID;
5315  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5316
5317  void *InsertPos = 0;
5318  QualifiedTemplateName *QTN =
5319    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5320  if (!QTN) {
5321    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5322    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5323  }
5324
5325  return TemplateName(QTN);
5326}
5327
5328/// \brief Retrieve the template name that represents a dependent
5329/// template name such as \c MetaFun::template apply.
5330TemplateName
5331ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5332                                     const IdentifierInfo *Name) const {
5333  assert((!NNS || NNS->isDependent()) &&
5334         "Nested name specifier must be dependent");
5335
5336  llvm::FoldingSetNodeID ID;
5337  DependentTemplateName::Profile(ID, NNS, Name);
5338
5339  void *InsertPos = 0;
5340  DependentTemplateName *QTN =
5341    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5342
5343  if (QTN)
5344    return TemplateName(QTN);
5345
5346  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5347  if (CanonNNS == NNS) {
5348    QTN = new (*this,4) DependentTemplateName(NNS, Name);
5349  } else {
5350    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5351    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
5352    DependentTemplateName *CheckQTN =
5353      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5354    assert(!CheckQTN && "Dependent type name canonicalization broken");
5355    (void)CheckQTN;
5356  }
5357
5358  DependentTemplateNames.InsertNode(QTN, InsertPos);
5359  return TemplateName(QTN);
5360}
5361
5362/// \brief Retrieve the template name that represents a dependent
5363/// template name such as \c MetaFun::template operator+.
5364TemplateName
5365ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5366                                     OverloadedOperatorKind Operator) const {
5367  assert((!NNS || NNS->isDependent()) &&
5368         "Nested name specifier must be dependent");
5369
5370  llvm::FoldingSetNodeID ID;
5371  DependentTemplateName::Profile(ID, NNS, Operator);
5372
5373  void *InsertPos = 0;
5374  DependentTemplateName *QTN
5375    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5376
5377  if (QTN)
5378    return TemplateName(QTN);
5379
5380  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5381  if (CanonNNS == NNS) {
5382    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5383  } else {
5384    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5385    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
5386
5387    DependentTemplateName *CheckQTN
5388      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5389    assert(!CheckQTN && "Dependent template name canonicalization broken");
5390    (void)CheckQTN;
5391  }
5392
5393  DependentTemplateNames.InsertNode(QTN, InsertPos);
5394  return TemplateName(QTN);
5395}
5396
5397TemplateName
5398ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5399                                         TemplateName replacement) const {
5400  llvm::FoldingSetNodeID ID;
5401  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5402
5403  void *insertPos = 0;
5404  SubstTemplateTemplateParmStorage *subst
5405    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5406
5407  if (!subst) {
5408    subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5409    SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5410  }
5411
5412  return TemplateName(subst);
5413}
5414
5415TemplateName
5416ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5417                                       const TemplateArgument &ArgPack) const {
5418  ASTContext &Self = const_cast<ASTContext &>(*this);
5419  llvm::FoldingSetNodeID ID;
5420  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5421
5422  void *InsertPos = 0;
5423  SubstTemplateTemplateParmPackStorage *Subst
5424    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5425
5426  if (!Subst) {
5427    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
5428                                                           ArgPack.pack_size(),
5429                                                         ArgPack.pack_begin());
5430    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5431  }
5432
5433  return TemplateName(Subst);
5434}
5435
5436/// getFromTargetType - Given one of the integer types provided by
5437/// TargetInfo, produce the corresponding type. The unsigned @p Type
5438/// is actually a value of type @c TargetInfo::IntType.
5439CanQualType ASTContext::getFromTargetType(unsigned Type) const {
5440  switch (Type) {
5441  case TargetInfo::NoInt: return CanQualType();
5442  case TargetInfo::SignedShort: return ShortTy;
5443  case TargetInfo::UnsignedShort: return UnsignedShortTy;
5444  case TargetInfo::SignedInt: return IntTy;
5445  case TargetInfo::UnsignedInt: return UnsignedIntTy;
5446  case TargetInfo::SignedLong: return LongTy;
5447  case TargetInfo::UnsignedLong: return UnsignedLongTy;
5448  case TargetInfo::SignedLongLong: return LongLongTy;
5449  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5450  }
5451
5452  llvm_unreachable("Unhandled TargetInfo::IntType value");
5453}
5454
5455//===----------------------------------------------------------------------===//
5456//                        Type Predicates.
5457//===----------------------------------------------------------------------===//
5458
5459/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5460/// garbage collection attribute.
5461///
5462Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
5463  if (getLangOpts().getGC() == LangOptions::NonGC)
5464    return Qualifiers::GCNone;
5465
5466  assert(getLangOpts().ObjC1);
5467  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5468
5469  // Default behaviour under objective-C's gc is for ObjC pointers
5470  // (or pointers to them) be treated as though they were declared
5471  // as __strong.
5472  if (GCAttrs == Qualifiers::GCNone) {
5473    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5474      return Qualifiers::Strong;
5475    else if (Ty->isPointerType())
5476      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5477  } else {
5478    // It's not valid to set GC attributes on anything that isn't a
5479    // pointer.
5480#ifndef NDEBUG
5481    QualType CT = Ty->getCanonicalTypeInternal();
5482    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5483      CT = AT->getElementType();
5484    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5485#endif
5486  }
5487  return GCAttrs;
5488}
5489
5490//===----------------------------------------------------------------------===//
5491//                        Type Compatibility Testing
5492//===----------------------------------------------------------------------===//
5493
5494/// areCompatVectorTypes - Return true if the two specified vector types are
5495/// compatible.
5496static bool areCompatVectorTypes(const VectorType *LHS,
5497                                 const VectorType *RHS) {
5498  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5499  return LHS->getElementType() == RHS->getElementType() &&
5500         LHS->getNumElements() == RHS->getNumElements();
5501}
5502
5503bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5504                                          QualType SecondVec) {
5505  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5506  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5507
5508  if (hasSameUnqualifiedType(FirstVec, SecondVec))
5509    return true;
5510
5511  // Treat Neon vector types and most AltiVec vector types as if they are the
5512  // equivalent GCC vector types.
5513  const VectorType *First = FirstVec->getAs<VectorType>();
5514  const VectorType *Second = SecondVec->getAs<VectorType>();
5515  if (First->getNumElements() == Second->getNumElements() &&
5516      hasSameType(First->getElementType(), Second->getElementType()) &&
5517      First->getVectorKind() != VectorType::AltiVecPixel &&
5518      First->getVectorKind() != VectorType::AltiVecBool &&
5519      Second->getVectorKind() != VectorType::AltiVecPixel &&
5520      Second->getVectorKind() != VectorType::AltiVecBool)
5521    return true;
5522
5523  return false;
5524}
5525
5526//===----------------------------------------------------------------------===//
5527// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5528//===----------------------------------------------------------------------===//
5529
5530/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5531/// inheritance hierarchy of 'rProto'.
5532bool
5533ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5534                                           ObjCProtocolDecl *rProto) const {
5535  if (declaresSameEntity(lProto, rProto))
5536    return true;
5537  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5538       E = rProto->protocol_end(); PI != E; ++PI)
5539    if (ProtocolCompatibleWithProtocol(lProto, *PI))
5540      return true;
5541  return false;
5542}
5543
5544/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5545/// return true if lhs's protocols conform to rhs's protocol; false
5546/// otherwise.
5547bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5548  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5549    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5550  return false;
5551}
5552
5553/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
5554/// Class<p1, ...>.
5555bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5556                                                      QualType rhs) {
5557  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5558  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5559  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5560
5561  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5562       E = lhsQID->qual_end(); I != E; ++I) {
5563    bool match = false;
5564    ObjCProtocolDecl *lhsProto = *I;
5565    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5566         E = rhsOPT->qual_end(); J != E; ++J) {
5567      ObjCProtocolDecl *rhsProto = *J;
5568      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5569        match = true;
5570        break;
5571      }
5572    }
5573    if (!match)
5574      return false;
5575  }
5576  return true;
5577}
5578
5579/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5580/// ObjCQualifiedIDType.
5581bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5582                                                   bool compare) {
5583  // Allow id<P..> and an 'id' or void* type in all cases.
5584  if (lhs->isVoidPointerType() ||
5585      lhs->isObjCIdType() || lhs->isObjCClassType())
5586    return true;
5587  else if (rhs->isVoidPointerType() ||
5588           rhs->isObjCIdType() || rhs->isObjCClassType())
5589    return true;
5590
5591  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5592    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5593
5594    if (!rhsOPT) return false;
5595
5596    if (rhsOPT->qual_empty()) {
5597      // If the RHS is a unqualified interface pointer "NSString*",
5598      // make sure we check the class hierarchy.
5599      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5600        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5601             E = lhsQID->qual_end(); I != E; ++I) {
5602          // when comparing an id<P> on lhs with a static type on rhs,
5603          // see if static class implements all of id's protocols, directly or
5604          // through its super class and categories.
5605          if (!rhsID->ClassImplementsProtocol(*I, true))
5606            return false;
5607        }
5608      }
5609      // If there are no qualifiers and no interface, we have an 'id'.
5610      return true;
5611    }
5612    // Both the right and left sides have qualifiers.
5613    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5614         E = lhsQID->qual_end(); I != E; ++I) {
5615      ObjCProtocolDecl *lhsProto = *I;
5616      bool match = false;
5617
5618      // when comparing an id<P> on lhs with a static type on rhs,
5619      // see if static class implements all of id's protocols, directly or
5620      // through its super class and categories.
5621      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5622           E = rhsOPT->qual_end(); J != E; ++J) {
5623        ObjCProtocolDecl *rhsProto = *J;
5624        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5625            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5626          match = true;
5627          break;
5628        }
5629      }
5630      // If the RHS is a qualified interface pointer "NSString<P>*",
5631      // make sure we check the class hierarchy.
5632      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5633        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5634             E = lhsQID->qual_end(); I != E; ++I) {
5635          // when comparing an id<P> on lhs with a static type on rhs,
5636          // see if static class implements all of id's protocols, directly or
5637          // through its super class and categories.
5638          if (rhsID->ClassImplementsProtocol(*I, true)) {
5639            match = true;
5640            break;
5641          }
5642        }
5643      }
5644      if (!match)
5645        return false;
5646    }
5647
5648    return true;
5649  }
5650
5651  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5652  assert(rhsQID && "One of the LHS/RHS should be id<x>");
5653
5654  if (const ObjCObjectPointerType *lhsOPT =
5655        lhs->getAsObjCInterfacePointerType()) {
5656    // If both the right and left sides have qualifiers.
5657    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5658         E = lhsOPT->qual_end(); I != E; ++I) {
5659      ObjCProtocolDecl *lhsProto = *I;
5660      bool match = false;
5661
5662      // when comparing an id<P> on rhs with a static type on lhs,
5663      // see if static class implements all of id's protocols, directly or
5664      // through its super class and categories.
5665      // First, lhs protocols in the qualifier list must be found, direct
5666      // or indirect in rhs's qualifier list or it is a mismatch.
5667      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5668           E = rhsQID->qual_end(); J != E; ++J) {
5669        ObjCProtocolDecl *rhsProto = *J;
5670        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5671            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5672          match = true;
5673          break;
5674        }
5675      }
5676      if (!match)
5677        return false;
5678    }
5679
5680    // Static class's protocols, or its super class or category protocols
5681    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5682    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5683      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5684      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5685      // This is rather dubious but matches gcc's behavior. If lhs has
5686      // no type qualifier and its class has no static protocol(s)
5687      // assume that it is mismatch.
5688      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5689        return false;
5690      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5691           LHSInheritedProtocols.begin(),
5692           E = LHSInheritedProtocols.end(); I != E; ++I) {
5693        bool match = false;
5694        ObjCProtocolDecl *lhsProto = (*I);
5695        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5696             E = rhsQID->qual_end(); J != E; ++J) {
5697          ObjCProtocolDecl *rhsProto = *J;
5698          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5699              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5700            match = true;
5701            break;
5702          }
5703        }
5704        if (!match)
5705          return false;
5706      }
5707    }
5708    return true;
5709  }
5710  return false;
5711}
5712
5713/// canAssignObjCInterfaces - Return true if the two interface types are
5714/// compatible for assignment from RHS to LHS.  This handles validation of any
5715/// protocol qualifiers on the LHS or RHS.
5716///
5717bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5718                                         const ObjCObjectPointerType *RHSOPT) {
5719  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5720  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5721
5722  // If either type represents the built-in 'id' or 'Class' types, return true.
5723  if (LHS->isObjCUnqualifiedIdOrClass() ||
5724      RHS->isObjCUnqualifiedIdOrClass())
5725    return true;
5726
5727  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5728    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5729                                             QualType(RHSOPT,0),
5730                                             false);
5731
5732  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5733    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5734                                                QualType(RHSOPT,0));
5735
5736  // If we have 2 user-defined types, fall into that path.
5737  if (LHS->getInterface() && RHS->getInterface())
5738    return canAssignObjCInterfaces(LHS, RHS);
5739
5740  return false;
5741}
5742
5743/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5744/// for providing type-safety for objective-c pointers used to pass/return
5745/// arguments in block literals. When passed as arguments, passing 'A*' where
5746/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5747/// not OK. For the return type, the opposite is not OK.
5748bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5749                                         const ObjCObjectPointerType *LHSOPT,
5750                                         const ObjCObjectPointerType *RHSOPT,
5751                                         bool BlockReturnType) {
5752  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5753    return true;
5754
5755  if (LHSOPT->isObjCBuiltinType()) {
5756    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5757  }
5758
5759  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5760    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5761                                             QualType(RHSOPT,0),
5762                                             false);
5763
5764  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5765  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5766  if (LHS && RHS)  { // We have 2 user-defined types.
5767    if (LHS != RHS) {
5768      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5769        return BlockReturnType;
5770      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5771        return !BlockReturnType;
5772    }
5773    else
5774      return true;
5775  }
5776  return false;
5777}
5778
5779/// getIntersectionOfProtocols - This routine finds the intersection of set
5780/// of protocols inherited from two distinct objective-c pointer objects.
5781/// It is used to build composite qualifier list of the composite type of
5782/// the conditional expression involving two objective-c pointer objects.
5783static
5784void getIntersectionOfProtocols(ASTContext &Context,
5785                                const ObjCObjectPointerType *LHSOPT,
5786                                const ObjCObjectPointerType *RHSOPT,
5787      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5788
5789  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5790  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5791  assert(LHS->getInterface() && "LHS must have an interface base");
5792  assert(RHS->getInterface() && "RHS must have an interface base");
5793
5794  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5795  unsigned LHSNumProtocols = LHS->getNumProtocols();
5796  if (LHSNumProtocols > 0)
5797    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5798  else {
5799    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5800    Context.CollectInheritedProtocols(LHS->getInterface(),
5801                                      LHSInheritedProtocols);
5802    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5803                                LHSInheritedProtocols.end());
5804  }
5805
5806  unsigned RHSNumProtocols = RHS->getNumProtocols();
5807  if (RHSNumProtocols > 0) {
5808    ObjCProtocolDecl **RHSProtocols =
5809      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5810    for (unsigned i = 0; i < RHSNumProtocols; ++i)
5811      if (InheritedProtocolSet.count(RHSProtocols[i]))
5812        IntersectionOfProtocols.push_back(RHSProtocols[i]);
5813  } else {
5814    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5815    Context.CollectInheritedProtocols(RHS->getInterface(),
5816                                      RHSInheritedProtocols);
5817    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5818         RHSInheritedProtocols.begin(),
5819         E = RHSInheritedProtocols.end(); I != E; ++I)
5820      if (InheritedProtocolSet.count((*I)))
5821        IntersectionOfProtocols.push_back((*I));
5822  }
5823}
5824
5825/// areCommonBaseCompatible - Returns common base class of the two classes if
5826/// one found. Note that this is O'2 algorithm. But it will be called as the
5827/// last type comparison in a ?-exp of ObjC pointer types before a
5828/// warning is issued. So, its invokation is extremely rare.
5829QualType ASTContext::areCommonBaseCompatible(
5830                                          const ObjCObjectPointerType *Lptr,
5831                                          const ObjCObjectPointerType *Rptr) {
5832  const ObjCObjectType *LHS = Lptr->getObjectType();
5833  const ObjCObjectType *RHS = Rptr->getObjectType();
5834  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5835  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5836  if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
5837    return QualType();
5838
5839  do {
5840    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5841    if (canAssignObjCInterfaces(LHS, RHS)) {
5842      SmallVector<ObjCProtocolDecl *, 8> Protocols;
5843      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5844
5845      QualType Result = QualType(LHS, 0);
5846      if (!Protocols.empty())
5847        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5848      Result = getObjCObjectPointerType(Result);
5849      return Result;
5850    }
5851  } while ((LDecl = LDecl->getSuperClass()));
5852
5853  return QualType();
5854}
5855
5856bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5857                                         const ObjCObjectType *RHS) {
5858  assert(LHS->getInterface() && "LHS is not an interface type");
5859  assert(RHS->getInterface() && "RHS is not an interface type");
5860
5861  // Verify that the base decls are compatible: the RHS must be a subclass of
5862  // the LHS.
5863  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5864    return false;
5865
5866  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5867  // protocol qualified at all, then we are good.
5868  if (LHS->getNumProtocols() == 0)
5869    return true;
5870
5871  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5872  // more detailed analysis is required.
5873  if (RHS->getNumProtocols() == 0) {
5874    // OK, if LHS is a superclass of RHS *and*
5875    // this superclass is assignment compatible with LHS.
5876    // false otherwise.
5877    bool IsSuperClass =
5878      LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5879    if (IsSuperClass) {
5880      // OK if conversion of LHS to SuperClass results in narrowing of types
5881      // ; i.e., SuperClass may implement at least one of the protocols
5882      // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5883      // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5884      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5885      CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5886      // If super class has no protocols, it is not a match.
5887      if (SuperClassInheritedProtocols.empty())
5888        return false;
5889
5890      for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5891           LHSPE = LHS->qual_end();
5892           LHSPI != LHSPE; LHSPI++) {
5893        bool SuperImplementsProtocol = false;
5894        ObjCProtocolDecl *LHSProto = (*LHSPI);
5895
5896        for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5897             SuperClassInheritedProtocols.begin(),
5898             E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5899          ObjCProtocolDecl *SuperClassProto = (*I);
5900          if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5901            SuperImplementsProtocol = true;
5902            break;
5903          }
5904        }
5905        if (!SuperImplementsProtocol)
5906          return false;
5907      }
5908      return true;
5909    }
5910    return false;
5911  }
5912
5913  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5914                                     LHSPE = LHS->qual_end();
5915       LHSPI != LHSPE; LHSPI++) {
5916    bool RHSImplementsProtocol = false;
5917
5918    // If the RHS doesn't implement the protocol on the left, the types
5919    // are incompatible.
5920    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5921                                       RHSPE = RHS->qual_end();
5922         RHSPI != RHSPE; RHSPI++) {
5923      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5924        RHSImplementsProtocol = true;
5925        break;
5926      }
5927    }
5928    // FIXME: For better diagnostics, consider passing back the protocol name.
5929    if (!RHSImplementsProtocol)
5930      return false;
5931  }
5932  // The RHS implements all protocols listed on the LHS.
5933  return true;
5934}
5935
5936bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5937  // get the "pointed to" types
5938  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5939  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5940
5941  if (!LHSOPT || !RHSOPT)
5942    return false;
5943
5944  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5945         canAssignObjCInterfaces(RHSOPT, LHSOPT);
5946}
5947
5948bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5949  return canAssignObjCInterfaces(
5950                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5951                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5952}
5953
5954/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5955/// both shall have the identically qualified version of a compatible type.
5956/// C99 6.2.7p1: Two types have compatible types if their types are the
5957/// same. See 6.7.[2,3,5] for additional rules.
5958bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5959                                    bool CompareUnqualified) {
5960  if (getLangOpts().CPlusPlus)
5961    return hasSameType(LHS, RHS);
5962
5963  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5964}
5965
5966bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5967  return typesAreCompatible(LHS, RHS);
5968}
5969
5970bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5971  return !mergeTypes(LHS, RHS, true).isNull();
5972}
5973
5974/// mergeTransparentUnionType - if T is a transparent union type and a member
5975/// of T is compatible with SubType, return the merged type, else return
5976/// QualType()
5977QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5978                                               bool OfBlockPointer,
5979                                               bool Unqualified) {
5980  if (const RecordType *UT = T->getAsUnionType()) {
5981    RecordDecl *UD = UT->getDecl();
5982    if (UD->hasAttr<TransparentUnionAttr>()) {
5983      for (RecordDecl::field_iterator it = UD->field_begin(),
5984           itend = UD->field_end(); it != itend; ++it) {
5985        QualType ET = it->getType().getUnqualifiedType();
5986        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5987        if (!MT.isNull())
5988          return MT;
5989      }
5990    }
5991  }
5992
5993  return QualType();
5994}
5995
5996/// mergeFunctionArgumentTypes - merge two types which appear as function
5997/// argument types
5998QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5999                                                bool OfBlockPointer,
6000                                                bool Unqualified) {
6001  // GNU extension: two types are compatible if they appear as a function
6002  // argument, one of the types is a transparent union type and the other
6003  // type is compatible with a union member
6004  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6005                                              Unqualified);
6006  if (!lmerge.isNull())
6007    return lmerge;
6008
6009  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6010                                              Unqualified);
6011  if (!rmerge.isNull())
6012    return rmerge;
6013
6014  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6015}
6016
6017QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6018                                        bool OfBlockPointer,
6019                                        bool Unqualified) {
6020  const FunctionType *lbase = lhs->getAs<FunctionType>();
6021  const FunctionType *rbase = rhs->getAs<FunctionType>();
6022  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6023  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6024  bool allLTypes = true;
6025  bool allRTypes = true;
6026
6027  // Check return type
6028  QualType retType;
6029  if (OfBlockPointer) {
6030    QualType RHS = rbase->getResultType();
6031    QualType LHS = lbase->getResultType();
6032    bool UnqualifiedResult = Unqualified;
6033    if (!UnqualifiedResult)
6034      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6035    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6036  }
6037  else
6038    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6039                         Unqualified);
6040  if (retType.isNull()) return QualType();
6041
6042  if (Unqualified)
6043    retType = retType.getUnqualifiedType();
6044
6045  CanQualType LRetType = getCanonicalType(lbase->getResultType());
6046  CanQualType RRetType = getCanonicalType(rbase->getResultType());
6047  if (Unqualified) {
6048    LRetType = LRetType.getUnqualifiedType();
6049    RRetType = RRetType.getUnqualifiedType();
6050  }
6051
6052  if (getCanonicalType(retType) != LRetType)
6053    allLTypes = false;
6054  if (getCanonicalType(retType) != RRetType)
6055    allRTypes = false;
6056
6057  // FIXME: double check this
6058  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6059  //                           rbase->getRegParmAttr() != 0 &&
6060  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6061  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6062  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6063
6064  // Compatible functions must have compatible calling conventions
6065  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
6066    return QualType();
6067
6068  // Regparm is part of the calling convention.
6069  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6070    return QualType();
6071  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6072    return QualType();
6073
6074  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6075    return QualType();
6076
6077  // functypes which return are preferred over those that do not.
6078  if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6079    allLTypes = false;
6080  else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6081    allRTypes = false;
6082  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6083  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6084
6085  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6086
6087  if (lproto && rproto) { // two C99 style function prototypes
6088    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6089           "C++ shouldn't be here");
6090    unsigned lproto_nargs = lproto->getNumArgs();
6091    unsigned rproto_nargs = rproto->getNumArgs();
6092
6093    // Compatible functions must have the same number of arguments
6094    if (lproto_nargs != rproto_nargs)
6095      return QualType();
6096
6097    // Variadic and non-variadic functions aren't compatible
6098    if (lproto->isVariadic() != rproto->isVariadic())
6099      return QualType();
6100
6101    if (lproto->getTypeQuals() != rproto->getTypeQuals())
6102      return QualType();
6103
6104    if (LangOpts.ObjCAutoRefCount &&
6105        !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6106      return QualType();
6107
6108    // Check argument compatibility
6109    SmallVector<QualType, 10> types;
6110    for (unsigned i = 0; i < lproto_nargs; i++) {
6111      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6112      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
6113      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6114                                                    OfBlockPointer,
6115                                                    Unqualified);
6116      if (argtype.isNull()) return QualType();
6117
6118      if (Unqualified)
6119        argtype = argtype.getUnqualifiedType();
6120
6121      types.push_back(argtype);
6122      if (Unqualified) {
6123        largtype = largtype.getUnqualifiedType();
6124        rargtype = rargtype.getUnqualifiedType();
6125      }
6126
6127      if (getCanonicalType(argtype) != getCanonicalType(largtype))
6128        allLTypes = false;
6129      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6130        allRTypes = false;
6131    }
6132
6133    if (allLTypes) return lhs;
6134    if (allRTypes) return rhs;
6135
6136    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6137    EPI.ExtInfo = einfo;
6138    return getFunctionType(retType, types.begin(), types.size(), EPI);
6139  }
6140
6141  if (lproto) allRTypes = false;
6142  if (rproto) allLTypes = false;
6143
6144  const FunctionProtoType *proto = lproto ? lproto : rproto;
6145  if (proto) {
6146    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
6147    if (proto->isVariadic()) return QualType();
6148    // Check that the types are compatible with the types that
6149    // would result from default argument promotions (C99 6.7.5.3p15).
6150    // The only types actually affected are promotable integer
6151    // types and floats, which would be passed as a different
6152    // type depending on whether the prototype is visible.
6153    unsigned proto_nargs = proto->getNumArgs();
6154    for (unsigned i = 0; i < proto_nargs; ++i) {
6155      QualType argTy = proto->getArgType(i);
6156
6157      // Look at the promotion type of enum types, since that is the type used
6158      // to pass enum values.
6159      if (const EnumType *Enum = argTy->getAs<EnumType>())
6160        argTy = Enum->getDecl()->getPromotionType();
6161
6162      if (argTy->isPromotableIntegerType() ||
6163          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6164        return QualType();
6165    }
6166
6167    if (allLTypes) return lhs;
6168    if (allRTypes) return rhs;
6169
6170    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6171    EPI.ExtInfo = einfo;
6172    return getFunctionType(retType, proto->arg_type_begin(),
6173                           proto->getNumArgs(), EPI);
6174  }
6175
6176  if (allLTypes) return lhs;
6177  if (allRTypes) return rhs;
6178  return getFunctionNoProtoType(retType, einfo);
6179}
6180
6181QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
6182                                bool OfBlockPointer,
6183                                bool Unqualified, bool BlockReturnType) {
6184  // C++ [expr]: If an expression initially has the type "reference to T", the
6185  // type is adjusted to "T" prior to any further analysis, the expression
6186  // designates the object or function denoted by the reference, and the
6187  // expression is an lvalue unless the reference is an rvalue reference and
6188  // the expression is a function call (possibly inside parentheses).
6189  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6190  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
6191
6192  if (Unqualified) {
6193    LHS = LHS.getUnqualifiedType();
6194    RHS = RHS.getUnqualifiedType();
6195  }
6196
6197  QualType LHSCan = getCanonicalType(LHS),
6198           RHSCan = getCanonicalType(RHS);
6199
6200  // If two types are identical, they are compatible.
6201  if (LHSCan == RHSCan)
6202    return LHS;
6203
6204  // If the qualifiers are different, the types aren't compatible... mostly.
6205  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6206  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6207  if (LQuals != RQuals) {
6208    // If any of these qualifiers are different, we have a type
6209    // mismatch.
6210    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6211        LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6212        LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
6213      return QualType();
6214
6215    // Exactly one GC qualifier difference is allowed: __strong is
6216    // okay if the other type has no GC qualifier but is an Objective
6217    // C object pointer (i.e. implicitly strong by default).  We fix
6218    // this by pretending that the unqualified type was actually
6219    // qualified __strong.
6220    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6221    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6222    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6223
6224    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6225      return QualType();
6226
6227    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6228      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6229    }
6230    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6231      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6232    }
6233    return QualType();
6234  }
6235
6236  // Okay, qualifiers are equal.
6237
6238  Type::TypeClass LHSClass = LHSCan->getTypeClass();
6239  Type::TypeClass RHSClass = RHSCan->getTypeClass();
6240
6241  // We want to consider the two function types to be the same for these
6242  // comparisons, just force one to the other.
6243  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6244  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
6245
6246  // Same as above for arrays
6247  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6248    LHSClass = Type::ConstantArray;
6249  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6250    RHSClass = Type::ConstantArray;
6251
6252  // ObjCInterfaces are just specialized ObjCObjects.
6253  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6254  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6255
6256  // Canonicalize ExtVector -> Vector.
6257  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6258  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
6259
6260  // If the canonical type classes don't match.
6261  if (LHSClass != RHSClass) {
6262    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6263    // a signed integer type, or an unsigned integer type.
6264    // Compatibility is based on the underlying type, not the promotion
6265    // type.
6266    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
6267      QualType TINT = ETy->getDecl()->getIntegerType();
6268      if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
6269        return RHS;
6270    }
6271    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
6272      QualType TINT = ETy->getDecl()->getIntegerType();
6273      if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
6274        return LHS;
6275    }
6276    // allow block pointer type to match an 'id' type.
6277    if (OfBlockPointer && !BlockReturnType) {
6278       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6279         return LHS;
6280      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6281        return RHS;
6282    }
6283
6284    return QualType();
6285  }
6286
6287  // The canonical type classes match.
6288  switch (LHSClass) {
6289#define TYPE(Class, Base)
6290#define ABSTRACT_TYPE(Class, Base)
6291#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
6292#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6293#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6294#include "clang/AST/TypeNodes.def"
6295    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
6296
6297  case Type::LValueReference:
6298  case Type::RValueReference:
6299  case Type::MemberPointer:
6300    llvm_unreachable("C++ should never be in mergeTypes");
6301
6302  case Type::ObjCInterface:
6303  case Type::IncompleteArray:
6304  case Type::VariableArray:
6305  case Type::FunctionProto:
6306  case Type::ExtVector:
6307    llvm_unreachable("Types are eliminated above");
6308
6309  case Type::Pointer:
6310  {
6311    // Merge two pointer types, while trying to preserve typedef info
6312    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6313    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
6314    if (Unqualified) {
6315      LHSPointee = LHSPointee.getUnqualifiedType();
6316      RHSPointee = RHSPointee.getUnqualifiedType();
6317    }
6318    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6319                                     Unqualified);
6320    if (ResultType.isNull()) return QualType();
6321    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6322      return LHS;
6323    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6324      return RHS;
6325    return getPointerType(ResultType);
6326  }
6327  case Type::BlockPointer:
6328  {
6329    // Merge two block pointer types, while trying to preserve typedef info
6330    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6331    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
6332    if (Unqualified) {
6333      LHSPointee = LHSPointee.getUnqualifiedType();
6334      RHSPointee = RHSPointee.getUnqualifiedType();
6335    }
6336    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6337                                     Unqualified);
6338    if (ResultType.isNull()) return QualType();
6339    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6340      return LHS;
6341    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6342      return RHS;
6343    return getBlockPointerType(ResultType);
6344  }
6345  case Type::Atomic:
6346  {
6347    // Merge two pointer types, while trying to preserve typedef info
6348    QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6349    QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6350    if (Unqualified) {
6351      LHSValue = LHSValue.getUnqualifiedType();
6352      RHSValue = RHSValue.getUnqualifiedType();
6353    }
6354    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6355                                     Unqualified);
6356    if (ResultType.isNull()) return QualType();
6357    if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6358      return LHS;
6359    if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6360      return RHS;
6361    return getAtomicType(ResultType);
6362  }
6363  case Type::ConstantArray:
6364  {
6365    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6366    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6367    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6368      return QualType();
6369
6370    QualType LHSElem = getAsArrayType(LHS)->getElementType();
6371    QualType RHSElem = getAsArrayType(RHS)->getElementType();
6372    if (Unqualified) {
6373      LHSElem = LHSElem.getUnqualifiedType();
6374      RHSElem = RHSElem.getUnqualifiedType();
6375    }
6376
6377    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
6378    if (ResultType.isNull()) return QualType();
6379    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6380      return LHS;
6381    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6382      return RHS;
6383    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6384                                          ArrayType::ArraySizeModifier(), 0);
6385    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6386                                          ArrayType::ArraySizeModifier(), 0);
6387    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6388    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
6389    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6390      return LHS;
6391    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6392      return RHS;
6393    if (LVAT) {
6394      // FIXME: This isn't correct! But tricky to implement because
6395      // the array's size has to be the size of LHS, but the type
6396      // has to be different.
6397      return LHS;
6398    }
6399    if (RVAT) {
6400      // FIXME: This isn't correct! But tricky to implement because
6401      // the array's size has to be the size of RHS, but the type
6402      // has to be different.
6403      return RHS;
6404    }
6405    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6406    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
6407    return getIncompleteArrayType(ResultType,
6408                                  ArrayType::ArraySizeModifier(), 0);
6409  }
6410  case Type::FunctionNoProto:
6411    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
6412  case Type::Record:
6413  case Type::Enum:
6414    return QualType();
6415  case Type::Builtin:
6416    // Only exactly equal builtin types are compatible, which is tested above.
6417    return QualType();
6418  case Type::Complex:
6419    // Distinct complex types are incompatible.
6420    return QualType();
6421  case Type::Vector:
6422    // FIXME: The merged type should be an ExtVector!
6423    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6424                             RHSCan->getAs<VectorType>()))
6425      return LHS;
6426    return QualType();
6427  case Type::ObjCObject: {
6428    // Check if the types are assignment compatible.
6429    // FIXME: This should be type compatibility, e.g. whether
6430    // "LHS x; RHS x;" at global scope is legal.
6431    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6432    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6433    if (canAssignObjCInterfaces(LHSIface, RHSIface))
6434      return LHS;
6435
6436    return QualType();
6437  }
6438  case Type::ObjCObjectPointer: {
6439    if (OfBlockPointer) {
6440      if (canAssignObjCInterfacesInBlockPointer(
6441                                          LHS->getAs<ObjCObjectPointerType>(),
6442                                          RHS->getAs<ObjCObjectPointerType>(),
6443                                          BlockReturnType))
6444        return LHS;
6445      return QualType();
6446    }
6447    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6448                                RHS->getAs<ObjCObjectPointerType>()))
6449      return LHS;
6450
6451    return QualType();
6452  }
6453  }
6454
6455  llvm_unreachable("Invalid Type::Class!");
6456}
6457
6458bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6459                   const FunctionProtoType *FromFunctionType,
6460                   const FunctionProtoType *ToFunctionType) {
6461  if (FromFunctionType->hasAnyConsumedArgs() !=
6462      ToFunctionType->hasAnyConsumedArgs())
6463    return false;
6464  FunctionProtoType::ExtProtoInfo FromEPI =
6465    FromFunctionType->getExtProtoInfo();
6466  FunctionProtoType::ExtProtoInfo ToEPI =
6467    ToFunctionType->getExtProtoInfo();
6468  if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6469    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6470         ArgIdx != NumArgs; ++ArgIdx)  {
6471      if (FromEPI.ConsumedArguments[ArgIdx] !=
6472          ToEPI.ConsumedArguments[ArgIdx])
6473        return false;
6474    }
6475  return true;
6476}
6477
6478/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6479/// 'RHS' attributes and returns the merged version; including for function
6480/// return types.
6481QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6482  QualType LHSCan = getCanonicalType(LHS),
6483  RHSCan = getCanonicalType(RHS);
6484  // If two types are identical, they are compatible.
6485  if (LHSCan == RHSCan)
6486    return LHS;
6487  if (RHSCan->isFunctionType()) {
6488    if (!LHSCan->isFunctionType())
6489      return QualType();
6490    QualType OldReturnType =
6491      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6492    QualType NewReturnType =
6493      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6494    QualType ResReturnType =
6495      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6496    if (ResReturnType.isNull())
6497      return QualType();
6498    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6499      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6500      // In either case, use OldReturnType to build the new function type.
6501      const FunctionType *F = LHS->getAs<FunctionType>();
6502      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6503        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6504        EPI.ExtInfo = getFunctionExtInfo(LHS);
6505        QualType ResultType
6506          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6507                            FPT->getNumArgs(), EPI);
6508        return ResultType;
6509      }
6510    }
6511    return QualType();
6512  }
6513
6514  // If the qualifiers are different, the types can still be merged.
6515  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6516  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6517  if (LQuals != RQuals) {
6518    // If any of these qualifiers are different, we have a type mismatch.
6519    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6520        LQuals.getAddressSpace() != RQuals.getAddressSpace())
6521      return QualType();
6522
6523    // Exactly one GC qualifier difference is allowed: __strong is
6524    // okay if the other type has no GC qualifier but is an Objective
6525    // C object pointer (i.e. implicitly strong by default).  We fix
6526    // this by pretending that the unqualified type was actually
6527    // qualified __strong.
6528    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6529    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6530    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6531
6532    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6533      return QualType();
6534
6535    if (GC_L == Qualifiers::Strong)
6536      return LHS;
6537    if (GC_R == Qualifiers::Strong)
6538      return RHS;
6539    return QualType();
6540  }
6541
6542  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6543    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6544    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6545    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6546    if (ResQT == LHSBaseQT)
6547      return LHS;
6548    if (ResQT == RHSBaseQT)
6549      return RHS;
6550  }
6551  return QualType();
6552}
6553
6554//===----------------------------------------------------------------------===//
6555//                         Integer Predicates
6556//===----------------------------------------------------------------------===//
6557
6558unsigned ASTContext::getIntWidth(QualType T) const {
6559  if (const EnumType *ET = dyn_cast<EnumType>(T))
6560    T = ET->getDecl()->getIntegerType();
6561  if (T->isBooleanType())
6562    return 1;
6563  // For builtin types, just use the standard type sizing method
6564  return (unsigned)getTypeSize(T);
6565}
6566
6567QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6568  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6569
6570  // Turn <4 x signed int> -> <4 x unsigned int>
6571  if (const VectorType *VTy = T->getAs<VectorType>())
6572    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6573                         VTy->getNumElements(), VTy->getVectorKind());
6574
6575  // For enums, we return the unsigned version of the base type.
6576  if (const EnumType *ETy = T->getAs<EnumType>())
6577    T = ETy->getDecl()->getIntegerType();
6578
6579  const BuiltinType *BTy = T->getAs<BuiltinType>();
6580  assert(BTy && "Unexpected signed integer type");
6581  switch (BTy->getKind()) {
6582  case BuiltinType::Char_S:
6583  case BuiltinType::SChar:
6584    return UnsignedCharTy;
6585  case BuiltinType::Short:
6586    return UnsignedShortTy;
6587  case BuiltinType::Int:
6588    return UnsignedIntTy;
6589  case BuiltinType::Long:
6590    return UnsignedLongTy;
6591  case BuiltinType::LongLong:
6592    return UnsignedLongLongTy;
6593  case BuiltinType::Int128:
6594    return UnsignedInt128Ty;
6595  default:
6596    llvm_unreachable("Unexpected signed integer type");
6597  }
6598}
6599
6600ASTMutationListener::~ASTMutationListener() { }
6601
6602
6603//===----------------------------------------------------------------------===//
6604//                          Builtin Type Computation
6605//===----------------------------------------------------------------------===//
6606
6607/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6608/// pointer over the consumed characters.  This returns the resultant type.  If
6609/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6610/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
6611/// a vector of "i*".
6612///
6613/// RequiresICE is filled in on return to indicate whether the value is required
6614/// to be an Integer Constant Expression.
6615static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6616                                  ASTContext::GetBuiltinTypeError &Error,
6617                                  bool &RequiresICE,
6618                                  bool AllowTypeModifiers) {
6619  // Modifiers.
6620  int HowLong = 0;
6621  bool Signed = false, Unsigned = false;
6622  RequiresICE = false;
6623
6624  // Read the prefixed modifiers first.
6625  bool Done = false;
6626  while (!Done) {
6627    switch (*Str++) {
6628    default: Done = true; --Str; break;
6629    case 'I':
6630      RequiresICE = true;
6631      break;
6632    case 'S':
6633      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6634      assert(!Signed && "Can't use 'S' modifier multiple times!");
6635      Signed = true;
6636      break;
6637    case 'U':
6638      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6639      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6640      Unsigned = true;
6641      break;
6642    case 'L':
6643      assert(HowLong <= 2 && "Can't have LLLL modifier");
6644      ++HowLong;
6645      break;
6646    }
6647  }
6648
6649  QualType Type;
6650
6651  // Read the base type.
6652  switch (*Str++) {
6653  default: llvm_unreachable("Unknown builtin type letter!");
6654  case 'v':
6655    assert(HowLong == 0 && !Signed && !Unsigned &&
6656           "Bad modifiers used with 'v'!");
6657    Type = Context.VoidTy;
6658    break;
6659  case 'f':
6660    assert(HowLong == 0 && !Signed && !Unsigned &&
6661           "Bad modifiers used with 'f'!");
6662    Type = Context.FloatTy;
6663    break;
6664  case 'd':
6665    assert(HowLong < 2 && !Signed && !Unsigned &&
6666           "Bad modifiers used with 'd'!");
6667    if (HowLong)
6668      Type = Context.LongDoubleTy;
6669    else
6670      Type = Context.DoubleTy;
6671    break;
6672  case 's':
6673    assert(HowLong == 0 && "Bad modifiers used with 's'!");
6674    if (Unsigned)
6675      Type = Context.UnsignedShortTy;
6676    else
6677      Type = Context.ShortTy;
6678    break;
6679  case 'i':
6680    if (HowLong == 3)
6681      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6682    else if (HowLong == 2)
6683      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6684    else if (HowLong == 1)
6685      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6686    else
6687      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6688    break;
6689  case 'c':
6690    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6691    if (Signed)
6692      Type = Context.SignedCharTy;
6693    else if (Unsigned)
6694      Type = Context.UnsignedCharTy;
6695    else
6696      Type = Context.CharTy;
6697    break;
6698  case 'b': // boolean
6699    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6700    Type = Context.BoolTy;
6701    break;
6702  case 'z':  // size_t.
6703    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6704    Type = Context.getSizeType();
6705    break;
6706  case 'F':
6707    Type = Context.getCFConstantStringType();
6708    break;
6709  case 'G':
6710    Type = Context.getObjCIdType();
6711    break;
6712  case 'H':
6713    Type = Context.getObjCSelType();
6714    break;
6715  case 'a':
6716    Type = Context.getBuiltinVaListType();
6717    assert(!Type.isNull() && "builtin va list type not initialized!");
6718    break;
6719  case 'A':
6720    // This is a "reference" to a va_list; however, what exactly
6721    // this means depends on how va_list is defined. There are two
6722    // different kinds of va_list: ones passed by value, and ones
6723    // passed by reference.  An example of a by-value va_list is
6724    // x86, where va_list is a char*. An example of by-ref va_list
6725    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6726    // we want this argument to be a char*&; for x86-64, we want
6727    // it to be a __va_list_tag*.
6728    Type = Context.getBuiltinVaListType();
6729    assert(!Type.isNull() && "builtin va list type not initialized!");
6730    if (Type->isArrayType())
6731      Type = Context.getArrayDecayedType(Type);
6732    else
6733      Type = Context.getLValueReferenceType(Type);
6734    break;
6735  case 'V': {
6736    char *End;
6737    unsigned NumElements = strtoul(Str, &End, 10);
6738    assert(End != Str && "Missing vector size");
6739    Str = End;
6740
6741    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6742                                             RequiresICE, false);
6743    assert(!RequiresICE && "Can't require vector ICE");
6744
6745    // TODO: No way to make AltiVec vectors in builtins yet.
6746    Type = Context.getVectorType(ElementType, NumElements,
6747                                 VectorType::GenericVector);
6748    break;
6749  }
6750  case 'E': {
6751    char *End;
6752
6753    unsigned NumElements = strtoul(Str, &End, 10);
6754    assert(End != Str && "Missing vector size");
6755
6756    Str = End;
6757
6758    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6759                                             false);
6760    Type = Context.getExtVectorType(ElementType, NumElements);
6761    break;
6762  }
6763  case 'X': {
6764    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6765                                             false);
6766    assert(!RequiresICE && "Can't require complex ICE");
6767    Type = Context.getComplexType(ElementType);
6768    break;
6769  }
6770  case 'Y' : {
6771    Type = Context.getPointerDiffType();
6772    break;
6773  }
6774  case 'P':
6775    Type = Context.getFILEType();
6776    if (Type.isNull()) {
6777      Error = ASTContext::GE_Missing_stdio;
6778      return QualType();
6779    }
6780    break;
6781  case 'J':
6782    if (Signed)
6783      Type = Context.getsigjmp_bufType();
6784    else
6785      Type = Context.getjmp_bufType();
6786
6787    if (Type.isNull()) {
6788      Error = ASTContext::GE_Missing_setjmp;
6789      return QualType();
6790    }
6791    break;
6792  case 'K':
6793    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6794    Type = Context.getucontext_tType();
6795
6796    if (Type.isNull()) {
6797      Error = ASTContext::GE_Missing_ucontext;
6798      return QualType();
6799    }
6800    break;
6801  }
6802
6803  // If there are modifiers and if we're allowed to parse them, go for it.
6804  Done = !AllowTypeModifiers;
6805  while (!Done) {
6806    switch (char c = *Str++) {
6807    default: Done = true; --Str; break;
6808    case '*':
6809    case '&': {
6810      // Both pointers and references can have their pointee types
6811      // qualified with an address space.
6812      char *End;
6813      unsigned AddrSpace = strtoul(Str, &End, 10);
6814      if (End != Str && AddrSpace != 0) {
6815        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6816        Str = End;
6817      }
6818      if (c == '*')
6819        Type = Context.getPointerType(Type);
6820      else
6821        Type = Context.getLValueReferenceType(Type);
6822      break;
6823    }
6824    // FIXME: There's no way to have a built-in with an rvalue ref arg.
6825    case 'C':
6826      Type = Type.withConst();
6827      break;
6828    case 'D':
6829      Type = Context.getVolatileType(Type);
6830      break;
6831    case 'R':
6832      Type = Type.withRestrict();
6833      break;
6834    }
6835  }
6836
6837  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6838         "Integer constant 'I' type must be an integer");
6839
6840  return Type;
6841}
6842
6843/// GetBuiltinType - Return the type for the specified builtin.
6844QualType ASTContext::GetBuiltinType(unsigned Id,
6845                                    GetBuiltinTypeError &Error,
6846                                    unsigned *IntegerConstantArgs) const {
6847  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6848
6849  SmallVector<QualType, 8> ArgTypes;
6850
6851  bool RequiresICE = false;
6852  Error = GE_None;
6853  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6854                                       RequiresICE, true);
6855  if (Error != GE_None)
6856    return QualType();
6857
6858  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6859
6860  while (TypeStr[0] && TypeStr[0] != '.') {
6861    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6862    if (Error != GE_None)
6863      return QualType();
6864
6865    // If this argument is required to be an IntegerConstantExpression and the
6866    // caller cares, fill in the bitmask we return.
6867    if (RequiresICE && IntegerConstantArgs)
6868      *IntegerConstantArgs |= 1 << ArgTypes.size();
6869
6870    // Do array -> pointer decay.  The builtin should use the decayed type.
6871    if (Ty->isArrayType())
6872      Ty = getArrayDecayedType(Ty);
6873
6874    ArgTypes.push_back(Ty);
6875  }
6876
6877  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6878         "'.' should only occur at end of builtin type list!");
6879
6880  FunctionType::ExtInfo EI;
6881  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6882
6883  bool Variadic = (TypeStr[0] == '.');
6884
6885  // We really shouldn't be making a no-proto type here, especially in C++.
6886  if (ArgTypes.empty() && Variadic)
6887    return getFunctionNoProtoType(ResType, EI);
6888
6889  FunctionProtoType::ExtProtoInfo EPI;
6890  EPI.ExtInfo = EI;
6891  EPI.Variadic = Variadic;
6892
6893  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6894}
6895
6896GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6897  GVALinkage External = GVA_StrongExternal;
6898
6899  Linkage L = FD->getLinkage();
6900  switch (L) {
6901  case NoLinkage:
6902  case InternalLinkage:
6903  case UniqueExternalLinkage:
6904    return GVA_Internal;
6905
6906  case ExternalLinkage:
6907    switch (FD->getTemplateSpecializationKind()) {
6908    case TSK_Undeclared:
6909    case TSK_ExplicitSpecialization:
6910      External = GVA_StrongExternal;
6911      break;
6912
6913    case TSK_ExplicitInstantiationDefinition:
6914      return GVA_ExplicitTemplateInstantiation;
6915
6916    case TSK_ExplicitInstantiationDeclaration:
6917    case TSK_ImplicitInstantiation:
6918      External = GVA_TemplateInstantiation;
6919      break;
6920    }
6921  }
6922
6923  if (!FD->isInlined())
6924    return External;
6925
6926  if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6927    // GNU or C99 inline semantics. Determine whether this symbol should be
6928    // externally visible.
6929    if (FD->isInlineDefinitionExternallyVisible())
6930      return External;
6931
6932    // C99 inline semantics, where the symbol is not externally visible.
6933    return GVA_C99Inline;
6934  }
6935
6936  // C++0x [temp.explicit]p9:
6937  //   [ Note: The intent is that an inline function that is the subject of
6938  //   an explicit instantiation declaration will still be implicitly
6939  //   instantiated when used so that the body can be considered for
6940  //   inlining, but that no out-of-line copy of the inline function would be
6941  //   generated in the translation unit. -- end note ]
6942  if (FD->getTemplateSpecializationKind()
6943                                       == TSK_ExplicitInstantiationDeclaration)
6944    return GVA_C99Inline;
6945
6946  return GVA_CXXInline;
6947}
6948
6949GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6950  // If this is a static data member, compute the kind of template
6951  // specialization. Otherwise, this variable is not part of a
6952  // template.
6953  TemplateSpecializationKind TSK = TSK_Undeclared;
6954  if (VD->isStaticDataMember())
6955    TSK = VD->getTemplateSpecializationKind();
6956
6957  Linkage L = VD->getLinkage();
6958  if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
6959      VD->getType()->getLinkage() == UniqueExternalLinkage)
6960    L = UniqueExternalLinkage;
6961
6962  switch (L) {
6963  case NoLinkage:
6964  case InternalLinkage:
6965  case UniqueExternalLinkage:
6966    return GVA_Internal;
6967
6968  case ExternalLinkage:
6969    switch (TSK) {
6970    case TSK_Undeclared:
6971    case TSK_ExplicitSpecialization:
6972      return GVA_StrongExternal;
6973
6974    case TSK_ExplicitInstantiationDeclaration:
6975      llvm_unreachable("Variable should not be instantiated");
6976      // Fall through to treat this like any other instantiation.
6977
6978    case TSK_ExplicitInstantiationDefinition:
6979      return GVA_ExplicitTemplateInstantiation;
6980
6981    case TSK_ImplicitInstantiation:
6982      return GVA_TemplateInstantiation;
6983    }
6984  }
6985
6986  llvm_unreachable("Invalid Linkage!");
6987}
6988
6989bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6990  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6991    if (!VD->isFileVarDecl())
6992      return false;
6993  } else if (!isa<FunctionDecl>(D))
6994    return false;
6995
6996  // Weak references don't produce any output by themselves.
6997  if (D->hasAttr<WeakRefAttr>())
6998    return false;
6999
7000  // Aliases and used decls are required.
7001  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7002    return true;
7003
7004  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7005    // Forward declarations aren't required.
7006    if (!FD->doesThisDeclarationHaveABody())
7007      return FD->doesDeclarationForceExternallyVisibleDefinition();
7008
7009    // Constructors and destructors are required.
7010    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7011      return true;
7012
7013    // The key function for a class is required.
7014    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7015      const CXXRecordDecl *RD = MD->getParent();
7016      if (MD->isOutOfLine() && RD->isDynamicClass()) {
7017        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7018        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7019          return true;
7020      }
7021    }
7022
7023    GVALinkage Linkage = GetGVALinkageForFunction(FD);
7024
7025    // static, static inline, always_inline, and extern inline functions can
7026    // always be deferred.  Normal inline functions can be deferred in C99/C++.
7027    // Implicit template instantiations can also be deferred in C++.
7028    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
7029        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7030      return false;
7031    return true;
7032  }
7033
7034  const VarDecl *VD = cast<VarDecl>(D);
7035  assert(VD->isFileVarDecl() && "Expected file scoped var");
7036
7037  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7038    return false;
7039
7040  // Structs that have non-trivial constructors or destructors are required.
7041
7042  // FIXME: Handle references.
7043  // FIXME: Be more selective about which constructors we care about.
7044  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7045    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
7046      if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7047                                   RD->hasTrivialCopyConstructor() &&
7048                                   RD->hasTrivialMoveConstructor() &&
7049                                   RD->hasTrivialDestructor()))
7050        return true;
7051    }
7052  }
7053
7054  GVALinkage L = GetGVALinkageForVariable(VD);
7055  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7056    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7057      return false;
7058  }
7059
7060  return true;
7061}
7062
7063CallingConv ASTContext::getDefaultMethodCallConv() {
7064  // Pass through to the C++ ABI object
7065  return ABI->getDefaultMethodCallConv();
7066}
7067
7068bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7069  // Pass through to the C++ ABI object
7070  return ABI->isNearlyEmpty(RD);
7071}
7072
7073MangleContext *ASTContext::createMangleContext() {
7074  switch (Target->getCXXABI()) {
7075  case CXXABI_ARM:
7076  case CXXABI_Itanium:
7077    return createItaniumMangleContext(*this, getDiagnostics());
7078  case CXXABI_Microsoft:
7079    return createMicrosoftMangleContext(*this, getDiagnostics());
7080  }
7081  llvm_unreachable("Unsupported ABI");
7082}
7083
7084CXXABI::~CXXABI() {}
7085
7086size_t ASTContext::getSideTableAllocatedMemory() const {
7087  return ASTRecordLayouts.getMemorySize()
7088    + llvm::capacity_in_bytes(ObjCLayouts)
7089    + llvm::capacity_in_bytes(KeyFunctions)
7090    + llvm::capacity_in_bytes(ObjCImpls)
7091    + llvm::capacity_in_bytes(BlockVarCopyInits)
7092    + llvm::capacity_in_bytes(DeclAttrs)
7093    + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7094    + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7095    + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7096    + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7097    + llvm::capacity_in_bytes(OverriddenMethods)
7098    + llvm::capacity_in_bytes(Types)
7099    + llvm::capacity_in_bytes(VariableArrayTypes)
7100    + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
7101}
7102
7103unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7104  CXXRecordDecl *Lambda = CallOperator->getParent();
7105  return LambdaMangleContexts[Lambda->getDeclContext()]
7106           .getManglingNumber(CallOperator);
7107}
7108
7109
7110void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7111  ParamIndices[D] = index;
7112}
7113
7114unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7115  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7116  assert(I != ParamIndices.end() &&
7117         "ParmIndices lacks entry set by ParmVarDecl");
7118  return I->second;
7119}
7120