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