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