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