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