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