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