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 getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
5037          VD->getType()->isIntegralOrEnumerationType() &&
5038          VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
5039 }
5040 
5041 static inline
5042 std::string charUnitsToString(const CharUnits &CU) {
5043   return llvm::itostr(CU.getQuantity());
5044 }
5045 
5046 /// getObjCEncodingForBlock - Return the encoded type for this block
5047 /// declaration.
5048 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5049   std::string S;
5050 
5051   const BlockDecl *Decl = Expr->getBlockDecl();
5052   QualType BlockTy =
5053       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5054   // Encode result type.
5055   if (getLangOpts().EncodeExtendedBlockSig)
5056     getObjCEncodingForMethodParameter(
5057         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5058         true /*Extended*/);
5059   else
5060     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5061   // Compute size of all parameters.
5062   // Start with computing size of a pointer in number of bytes.
5063   // FIXME: There might(should) be a better way of doing this computation!
5064   SourceLocation Loc;
5065   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5066   CharUnits ParmOffset = PtrSize;
5067   for (auto PI : Decl->params()) {
5068     QualType PType = PI->getType();
5069     CharUnits sz = getObjCEncodingTypeSize(PType);
5070     if (sz.isZero())
5071       continue;
5072     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5073     ParmOffset += sz;
5074   }
5075   // Size of the argument frame
5076   S += charUnitsToString(ParmOffset);
5077   // Block pointer and offset.
5078   S += "@?0";
5079 
5080   // Argument types.
5081   ParmOffset = PtrSize;
5082   for (auto PVDecl : Decl->params()) {
5083     QualType PType = PVDecl->getOriginalType();
5084     if (const ArrayType *AT =
5085           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5086       // Use array's original type only if it has known number of
5087       // elements.
5088       if (!isa<ConstantArrayType>(AT))
5089         PType = PVDecl->getType();
5090     } else if (PType->isFunctionType())
5091       PType = PVDecl->getType();
5092     if (getLangOpts().EncodeExtendedBlockSig)
5093       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5094                                       S, true /*Extended*/);
5095     else
5096       getObjCEncodingForType(PType, S);
5097     S += charUnitsToString(ParmOffset);
5098     ParmOffset += getObjCEncodingTypeSize(PType);
5099   }
5100 
5101   return S;
5102 }
5103 
5104 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5105                                                 std::string& S) {
5106   // Encode result type.
5107   getObjCEncodingForType(Decl->getReturnType(), S);
5108   CharUnits ParmOffset;
5109   // Compute size of all parameters.
5110   for (auto PI : Decl->params()) {
5111     QualType PType = PI->getType();
5112     CharUnits sz = getObjCEncodingTypeSize(PType);
5113     if (sz.isZero())
5114       continue;
5115 
5116     assert (sz.isPositive() &&
5117         "getObjCEncodingForFunctionDecl - Incomplete param type");
5118     ParmOffset += sz;
5119   }
5120   S += charUnitsToString(ParmOffset);
5121   ParmOffset = CharUnits::Zero();
5122 
5123   // Argument types.
5124   for (auto PVDecl : Decl->params()) {
5125     QualType PType = PVDecl->getOriginalType();
5126     if (const ArrayType *AT =
5127           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5128       // Use array's original type only if it has known number of
5129       // elements.
5130       if (!isa<ConstantArrayType>(AT))
5131         PType = PVDecl->getType();
5132     } else if (PType->isFunctionType())
5133       PType = PVDecl->getType();
5134     getObjCEncodingForType(PType, S);
5135     S += charUnitsToString(ParmOffset);
5136     ParmOffset += getObjCEncodingTypeSize(PType);
5137   }
5138 
5139   return false;
5140 }
5141 
5142 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5143 /// method parameter or return type. If Extended, include class names and
5144 /// block object types.
5145 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5146                                                    QualType T, std::string& S,
5147                                                    bool Extended) const {
5148   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5149   getObjCEncodingForTypeQualifier(QT, S);
5150   // Encode parameter type.
5151   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5152                              true     /*OutermostType*/,
5153                              false    /*EncodingProperty*/,
5154                              false    /*StructField*/,
5155                              Extended /*EncodeBlockParameters*/,
5156                              Extended /*EncodeClassNames*/);
5157 }
5158 
5159 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5160 /// declaration.
5161 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5162                                               std::string& S,
5163                                               bool Extended) const {
5164   // FIXME: This is not very efficient.
5165   // Encode return type.
5166   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5167                                     Decl->getReturnType(), S, Extended);
5168   // Compute size of all parameters.
5169   // Start with computing size of a pointer in number of bytes.
5170   // FIXME: There might(should) be a better way of doing this computation!
5171   SourceLocation Loc;
5172   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5173   // The first two arguments (self and _cmd) are pointers; account for
5174   // their size.
5175   CharUnits ParmOffset = 2 * PtrSize;
5176   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5177        E = Decl->sel_param_end(); PI != E; ++PI) {
5178     QualType PType = (*PI)->getType();
5179     CharUnits sz = getObjCEncodingTypeSize(PType);
5180     if (sz.isZero())
5181       continue;
5182 
5183     assert (sz.isPositive() &&
5184         "getObjCEncodingForMethodDecl - Incomplete param type");
5185     ParmOffset += sz;
5186   }
5187   S += charUnitsToString(ParmOffset);
5188   S += "@0:";
5189   S += charUnitsToString(PtrSize);
5190 
5191   // Argument types.
5192   ParmOffset = 2 * PtrSize;
5193   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5194        E = Decl->sel_param_end(); PI != E; ++PI) {
5195     const ParmVarDecl *PVDecl = *PI;
5196     QualType PType = PVDecl->getOriginalType();
5197     if (const ArrayType *AT =
5198           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5199       // Use array's original type only if it has known number of
5200       // elements.
5201       if (!isa<ConstantArrayType>(AT))
5202         PType = PVDecl->getType();
5203     } else if (PType->isFunctionType())
5204       PType = PVDecl->getType();
5205     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5206                                       PType, S, Extended);
5207     S += charUnitsToString(ParmOffset);
5208     ParmOffset += getObjCEncodingTypeSize(PType);
5209   }
5210 
5211   return false;
5212 }
5213 
5214 ObjCPropertyImplDecl *
5215 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5216                                       const ObjCPropertyDecl *PD,
5217                                       const Decl *Container) const {
5218   if (!Container)
5219     return nullptr;
5220   if (const ObjCCategoryImplDecl *CID =
5221       dyn_cast<ObjCCategoryImplDecl>(Container)) {
5222     for (auto *PID : CID->property_impls())
5223       if (PID->getPropertyDecl() == PD)
5224         return PID;
5225   } else {
5226     const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5227     for (auto *PID : OID->property_impls())
5228       if (PID->getPropertyDecl() == PD)
5229         return PID;
5230   }
5231   return nullptr;
5232 }
5233 
5234 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5235 /// property declaration. If non-NULL, Container must be either an
5236 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5237 /// NULL when getting encodings for protocol properties.
5238 /// Property attributes are stored as a comma-delimited C string. The simple
5239 /// attributes readonly and bycopy are encoded as single characters. The
5240 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5241 /// encoded as single characters, followed by an identifier. Property types
5242 /// are also encoded as a parametrized attribute. The characters used to encode
5243 /// these attributes are defined by the following enumeration:
5244 /// @code
5245 /// enum PropertyAttributes {
5246 /// kPropertyReadOnly = 'R',   // property is read-only.
5247 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
5248 /// kPropertyByref = '&',  // property is a reference to the value last assigned
5249 /// kPropertyDynamic = 'D',    // property is dynamic
5250 /// kPropertyGetter = 'G',     // followed by getter selector name
5251 /// kPropertySetter = 'S',     // followed by setter selector name
5252 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
5253 /// kPropertyType = 'T'              // followed by old-style type encoding.
5254 /// kPropertyWeak = 'W'              // 'weak' property
5255 /// kPropertyStrong = 'P'            // property GC'able
5256 /// kPropertyNonAtomic = 'N'         // property non-atomic
5257 /// };
5258 /// @endcode
5259 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5260                                                 const Decl *Container,
5261                                                 std::string& S) const {
5262   // Collect information from the property implementation decl(s).
5263   bool Dynamic = false;
5264   ObjCPropertyImplDecl *SynthesizePID = nullptr;
5265 
5266   if (ObjCPropertyImplDecl *PropertyImpDecl =
5267       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5268     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5269       Dynamic = true;
5270     else
5271       SynthesizePID = PropertyImpDecl;
5272   }
5273 
5274   // FIXME: This is not very efficient.
5275   S = "T";
5276 
5277   // Encode result type.
5278   // GCC has some special rules regarding encoding of properties which
5279   // closely resembles encoding of ivars.
5280   getObjCEncodingForPropertyType(PD->getType(), S);
5281 
5282   if (PD->isReadOnly()) {
5283     S += ",R";
5284     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5285       S += ",C";
5286     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5287       S += ",&";
5288     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5289       S += ",W";
5290   } else {
5291     switch (PD->getSetterKind()) {
5292     case ObjCPropertyDecl::Assign: break;
5293     case ObjCPropertyDecl::Copy:   S += ",C"; break;
5294     case ObjCPropertyDecl::Retain: S += ",&"; break;
5295     case ObjCPropertyDecl::Weak:   S += ",W"; break;
5296     }
5297   }
5298 
5299   // It really isn't clear at all what this means, since properties
5300   // are "dynamic by default".
5301   if (Dynamic)
5302     S += ",D";
5303 
5304   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5305     S += ",N";
5306 
5307   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5308     S += ",G";
5309     S += PD->getGetterName().getAsString();
5310   }
5311 
5312   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5313     S += ",S";
5314     S += PD->getSetterName().getAsString();
5315   }
5316 
5317   if (SynthesizePID) {
5318     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5319     S += ",V";
5320     S += OID->getNameAsString();
5321   }
5322 
5323   // FIXME: OBJCGC: weak & strong
5324 }
5325 
5326 /// getLegacyIntegralTypeEncoding -
5327 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5328 /// 'l' or 'L' , but not always.  For typedefs, we need to use
5329 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5330 ///
5331 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5332   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5333     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5334       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5335         PointeeTy = UnsignedIntTy;
5336       else
5337         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5338           PointeeTy = IntTy;
5339     }
5340   }
5341 }
5342 
5343 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5344                                         const FieldDecl *Field,
5345                                         QualType *NotEncodedT) const {
5346   // We follow the behavior of gcc, expanding structures which are
5347   // directly pointed to, and expanding embedded structures. Note that
5348   // these rules are sufficient to prevent recursive encoding of the
5349   // same type.
5350   getObjCEncodingForTypeImpl(T, S, true, true, Field,
5351                              true /* outermost type */, false, false,
5352                              false, false, false, NotEncodedT);
5353 }
5354 
5355 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5356                                                 std::string& S) const {
5357   // Encode result type.
5358   // GCC has some special rules regarding encoding of properties which
5359   // closely resembles encoding of ivars.
5360   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5361                              true /* outermost type */,
5362                              true /* encoding property */);
5363 }
5364 
5365 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5366                                             BuiltinType::Kind kind) {
5367     switch (kind) {
5368     case BuiltinType::Void:       return 'v';
5369     case BuiltinType::Bool:       return 'B';
5370     case BuiltinType::Char_U:
5371     case BuiltinType::UChar:      return 'C';
5372     case BuiltinType::Char16:
5373     case BuiltinType::UShort:     return 'S';
5374     case BuiltinType::Char32:
5375     case BuiltinType::UInt:       return 'I';
5376     case BuiltinType::ULong:
5377         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5378     case BuiltinType::UInt128:    return 'T';
5379     case BuiltinType::ULongLong:  return 'Q';
5380     case BuiltinType::Char_S:
5381     case BuiltinType::SChar:      return 'c';
5382     case BuiltinType::Short:      return 's';
5383     case BuiltinType::WChar_S:
5384     case BuiltinType::WChar_U:
5385     case BuiltinType::Int:        return 'i';
5386     case BuiltinType::Long:
5387       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5388     case BuiltinType::LongLong:   return 'q';
5389     case BuiltinType::Int128:     return 't';
5390     case BuiltinType::Float:      return 'f';
5391     case BuiltinType::Double:     return 'd';
5392     case BuiltinType::LongDouble: return 'D';
5393     case BuiltinType::NullPtr:    return '*'; // like char*
5394 
5395     case BuiltinType::Half:
5396       // FIXME: potentially need @encodes for these!
5397       return ' ';
5398 
5399     case BuiltinType::ObjCId:
5400     case BuiltinType::ObjCClass:
5401     case BuiltinType::ObjCSel:
5402       llvm_unreachable("@encoding ObjC primitive type");
5403 
5404     // OpenCL and placeholder types don't need @encodings.
5405     case BuiltinType::OCLImage1d:
5406     case BuiltinType::OCLImage1dArray:
5407     case BuiltinType::OCLImage1dBuffer:
5408     case BuiltinType::OCLImage2d:
5409     case BuiltinType::OCLImage2dArray:
5410     case BuiltinType::OCLImage2dDepth:
5411     case BuiltinType::OCLImage2dArrayDepth:
5412     case BuiltinType::OCLImage2dMSAA:
5413     case BuiltinType::OCLImage2dArrayMSAA:
5414     case BuiltinType::OCLImage2dMSAADepth:
5415     case BuiltinType::OCLImage2dArrayMSAADepth:
5416     case BuiltinType::OCLImage3d:
5417     case BuiltinType::OCLEvent:
5418     case BuiltinType::OCLClkEvent:
5419     case BuiltinType::OCLQueue:
5420     case BuiltinType::OCLNDRange:
5421     case BuiltinType::OCLReserveID:
5422     case BuiltinType::OCLSampler:
5423     case BuiltinType::Dependent:
5424 #define BUILTIN_TYPE(KIND, ID)
5425 #define PLACEHOLDER_TYPE(KIND, ID) \
5426     case BuiltinType::KIND:
5427 #include "clang/AST/BuiltinTypes.def"
5428       llvm_unreachable("invalid builtin type for @encode");
5429     }
5430     llvm_unreachable("invalid BuiltinType::Kind value");
5431 }
5432 
5433 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5434   EnumDecl *Enum = ET->getDecl();
5435 
5436   // The encoding of an non-fixed enum type is always 'i', regardless of size.
5437   if (!Enum->isFixed())
5438     return 'i';
5439 
5440   // The encoding of a fixed enum type matches its fixed underlying type.
5441   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5442   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5443 }
5444 
5445 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5446                            QualType T, const FieldDecl *FD) {
5447   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5448   S += 'b';
5449   // The NeXT runtime encodes bit fields as b followed by the number of bits.
5450   // The GNU runtime requires more information; bitfields are encoded as b,
5451   // then the offset (in bits) of the first element, then the type of the
5452   // bitfield, then the size in bits.  For example, in this structure:
5453   //
5454   // struct
5455   // {
5456   //    int integer;
5457   //    int flags:2;
5458   // };
5459   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5460   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
5461   // information is not especially sensible, but we're stuck with it for
5462   // compatibility with GCC, although providing it breaks anything that
5463   // actually uses runtime introspection and wants to work on both runtimes...
5464   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5465     const RecordDecl *RD = FD->getParent();
5466     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5467     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5468     if (const EnumType *ET = T->getAs<EnumType>())
5469       S += ObjCEncodingForEnumType(Ctx, ET);
5470     else {
5471       const BuiltinType *BT = T->castAs<BuiltinType>();
5472       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5473     }
5474   }
5475   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5476 }
5477 
5478 // FIXME: Use SmallString for accumulating string.
5479 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5480                                             bool ExpandPointedToStructures,
5481                                             bool ExpandStructures,
5482                                             const FieldDecl *FD,
5483                                             bool OutermostType,
5484                                             bool EncodingProperty,
5485                                             bool StructField,
5486                                             bool EncodeBlockParameters,
5487                                             bool EncodeClassNames,
5488                                             bool EncodePointerToObjCTypedef,
5489                                             QualType *NotEncodedT) const {
5490   CanQualType CT = getCanonicalType(T);
5491   switch (CT->getTypeClass()) {
5492   case Type::Builtin:
5493   case Type::Enum:
5494     if (FD && FD->isBitField())
5495       return EncodeBitField(this, S, T, FD);
5496     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5497       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5498     else
5499       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5500     return;
5501 
5502   case Type::Complex: {
5503     const ComplexType *CT = T->castAs<ComplexType>();
5504     S += 'j';
5505     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5506     return;
5507   }
5508 
5509   case Type::Atomic: {
5510     const AtomicType *AT = T->castAs<AtomicType>();
5511     S += 'A';
5512     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5513     return;
5514   }
5515 
5516   // encoding for pointer or reference types.
5517   case Type::Pointer:
5518   case Type::LValueReference:
5519   case Type::RValueReference: {
5520     QualType PointeeTy;
5521     if (isa<PointerType>(CT)) {
5522       const PointerType *PT = T->castAs<PointerType>();
5523       if (PT->isObjCSelType()) {
5524         S += ':';
5525         return;
5526       }
5527       PointeeTy = PT->getPointeeType();
5528     } else {
5529       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5530     }
5531 
5532     bool isReadOnly = false;
5533     // For historical/compatibility reasons, the read-only qualifier of the
5534     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
5535     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5536     // Also, do not emit the 'r' for anything but the outermost type!
5537     if (isa<TypedefType>(T.getTypePtr())) {
5538       if (OutermostType && T.isConstQualified()) {
5539         isReadOnly = true;
5540         S += 'r';
5541       }
5542     } else if (OutermostType) {
5543       QualType P = PointeeTy;
5544       while (P->getAs<PointerType>())
5545         P = P->getAs<PointerType>()->getPointeeType();
5546       if (P.isConstQualified()) {
5547         isReadOnly = true;
5548         S += 'r';
5549       }
5550     }
5551     if (isReadOnly) {
5552       // Another legacy compatibility encoding. Some ObjC qualifier and type
5553       // combinations need to be rearranged.
5554       // Rewrite "in const" from "nr" to "rn"
5555       if (StringRef(S).endswith("nr"))
5556         S.replace(S.end()-2, S.end(), "rn");
5557     }
5558 
5559     if (PointeeTy->isCharType()) {
5560       // char pointer types should be encoded as '*' unless it is a
5561       // type that has been typedef'd to 'BOOL'.
5562       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5563         S += '*';
5564         return;
5565       }
5566     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5567       // GCC binary compat: Need to convert "struct objc_class *" to "#".
5568       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5569         S += '#';
5570         return;
5571       }
5572       // GCC binary compat: Need to convert "struct objc_object *" to "@".
5573       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5574         S += '@';
5575         return;
5576       }
5577       // fall through...
5578     }
5579     S += '^';
5580     getLegacyIntegralTypeEncoding(PointeeTy);
5581 
5582     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5583                                nullptr, false, false, false, false, false, false,
5584                                NotEncodedT);
5585     return;
5586   }
5587 
5588   case Type::ConstantArray:
5589   case Type::IncompleteArray:
5590   case Type::VariableArray: {
5591     const ArrayType *AT = cast<ArrayType>(CT);
5592 
5593     if (isa<IncompleteArrayType>(AT) && !StructField) {
5594       // Incomplete arrays are encoded as a pointer to the array element.
5595       S += '^';
5596 
5597       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5598                                  false, ExpandStructures, FD);
5599     } else {
5600       S += '[';
5601 
5602       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5603         S += llvm::utostr(CAT->getSize().getZExtValue());
5604       else {
5605         //Variable length arrays are encoded as a regular array with 0 elements.
5606         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5607                "Unknown array type!");
5608         S += '0';
5609       }
5610 
5611       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5612                                  false, ExpandStructures, FD,
5613                                  false, false, false, false, false, false,
5614                                  NotEncodedT);
5615       S += ']';
5616     }
5617     return;
5618   }
5619 
5620   case Type::FunctionNoProto:
5621   case Type::FunctionProto:
5622     S += '?';
5623     return;
5624 
5625   case Type::Record: {
5626     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5627     S += RDecl->isUnion() ? '(' : '{';
5628     // Anonymous structures print as '?'
5629     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5630       S += II->getName();
5631       if (ClassTemplateSpecializationDecl *Spec
5632           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5633         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5634         llvm::raw_string_ostream OS(S);
5635         TemplateSpecializationType::PrintTemplateArgumentList(OS,
5636                                             TemplateArgs.data(),
5637                                             TemplateArgs.size(),
5638                                             (*this).getPrintingPolicy());
5639       }
5640     } else {
5641       S += '?';
5642     }
5643     if (ExpandStructures) {
5644       S += '=';
5645       if (!RDecl->isUnion()) {
5646         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5647       } else {
5648         for (const auto *Field : RDecl->fields()) {
5649           if (FD) {
5650             S += '"';
5651             S += Field->getNameAsString();
5652             S += '"';
5653           }
5654 
5655           // Special case bit-fields.
5656           if (Field->isBitField()) {
5657             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5658                                        Field);
5659           } else {
5660             QualType qt = Field->getType();
5661             getLegacyIntegralTypeEncoding(qt);
5662             getObjCEncodingForTypeImpl(qt, S, false, true,
5663                                        FD, /*OutermostType*/false,
5664                                        /*EncodingProperty*/false,
5665                                        /*StructField*/true,
5666                                        false, false, false, NotEncodedT);
5667           }
5668         }
5669       }
5670     }
5671     S += RDecl->isUnion() ? ')' : '}';
5672     return;
5673   }
5674 
5675   case Type::BlockPointer: {
5676     const BlockPointerType *BT = T->castAs<BlockPointerType>();
5677     S += "@?"; // Unlike a pointer-to-function, which is "^?".
5678     if (EncodeBlockParameters) {
5679       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5680 
5681       S += '<';
5682       // Block return type
5683       getObjCEncodingForTypeImpl(
5684           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5685           FD, false /* OutermostType */, EncodingProperty,
5686           false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5687                                  NotEncodedT);
5688       // Block self
5689       S += "@?";
5690       // Block parameters
5691       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5692         for (const auto &I : FPT->param_types())
5693           getObjCEncodingForTypeImpl(
5694               I, S, ExpandPointedToStructures, ExpandStructures, FD,
5695               false /* OutermostType */, EncodingProperty,
5696               false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5697                                      false, NotEncodedT);
5698       }
5699       S += '>';
5700     }
5701     return;
5702   }
5703 
5704   case Type::ObjCObject: {
5705     // hack to match legacy encoding of *id and *Class
5706     QualType Ty = getObjCObjectPointerType(CT);
5707     if (Ty->isObjCIdType()) {
5708       S += "{objc_object=}";
5709       return;
5710     }
5711     else if (Ty->isObjCClassType()) {
5712       S += "{objc_class=}";
5713       return;
5714     }
5715   }
5716 
5717   case Type::ObjCInterface: {
5718     // Ignore protocol qualifiers when mangling at this level.
5719     // @encode(class_name)
5720     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5721     S += '{';
5722     S += OI->getObjCRuntimeNameAsString();
5723     S += '=';
5724     SmallVector<const ObjCIvarDecl*, 32> Ivars;
5725     DeepCollectObjCIvars(OI, true, Ivars);
5726     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5727       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5728       if (Field->isBitField())
5729         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5730       else
5731         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5732                                    false, false, false, false, false,
5733                                    EncodePointerToObjCTypedef,
5734                                    NotEncodedT);
5735     }
5736     S += '}';
5737     return;
5738   }
5739 
5740   case Type::ObjCObjectPointer: {
5741     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5742     if (OPT->isObjCIdType()) {
5743       S += '@';
5744       return;
5745     }
5746 
5747     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5748       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5749       // Since this is a binary compatibility issue, need to consult with runtime
5750       // folks. Fortunately, this is a *very* obsure construct.
5751       S += '#';
5752       return;
5753     }
5754 
5755     if (OPT->isObjCQualifiedIdType()) {
5756       getObjCEncodingForTypeImpl(getObjCIdType(), S,
5757                                  ExpandPointedToStructures,
5758                                  ExpandStructures, FD);
5759       if (FD || EncodingProperty || EncodeClassNames) {
5760         // Note that we do extended encoding of protocol qualifer list
5761         // Only when doing ivar or property encoding.
5762         S += '"';
5763         for (const auto *I : OPT->quals()) {
5764           S += '<';
5765           S += I->getObjCRuntimeNameAsString();
5766           S += '>';
5767         }
5768         S += '"';
5769       }
5770       return;
5771     }
5772 
5773     QualType PointeeTy = OPT->getPointeeType();
5774     if (!EncodingProperty &&
5775         isa<TypedefType>(PointeeTy.getTypePtr()) &&
5776         !EncodePointerToObjCTypedef) {
5777       // Another historical/compatibility reason.
5778       // We encode the underlying type which comes out as
5779       // {...};
5780       S += '^';
5781       if (FD && OPT->getInterfaceDecl()) {
5782         // Prevent recursive encoding of fields in some rare cases.
5783         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5784         SmallVector<const ObjCIvarDecl*, 32> Ivars;
5785         DeepCollectObjCIvars(OI, true, Ivars);
5786         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5787           if (cast<FieldDecl>(Ivars[i]) == FD) {
5788             S += '{';
5789             S += OI->getObjCRuntimeNameAsString();
5790             S += '}';
5791             return;
5792           }
5793         }
5794       }
5795       getObjCEncodingForTypeImpl(PointeeTy, S,
5796                                  false, ExpandPointedToStructures,
5797                                  nullptr,
5798                                  false, false, false, false, false,
5799                                  /*EncodePointerToObjCTypedef*/true);
5800       return;
5801     }
5802 
5803     S += '@';
5804     if (OPT->getInterfaceDecl() &&
5805         (FD || EncodingProperty || EncodeClassNames)) {
5806       S += '"';
5807       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5808       for (const auto *I : OPT->quals()) {
5809         S += '<';
5810         S += I->getObjCRuntimeNameAsString();
5811         S += '>';
5812       }
5813       S += '"';
5814     }
5815     return;
5816   }
5817 
5818   // gcc just blithely ignores member pointers.
5819   // FIXME: we shoul do better than that.  'M' is available.
5820   case Type::MemberPointer:
5821   // This matches gcc's encoding, even though technically it is insufficient.
5822   //FIXME. We should do a better job than gcc.
5823   case Type::Vector:
5824   case Type::ExtVector:
5825   // Until we have a coherent encoding of these three types, issue warning.
5826     { if (NotEncodedT)
5827         *NotEncodedT = T;
5828       return;
5829     }
5830 
5831   // We could see an undeduced auto type here during error recovery.
5832   // Just ignore it.
5833   case Type::Auto:
5834     return;
5835 
5836 
5837 #define ABSTRACT_TYPE(KIND, BASE)
5838 #define TYPE(KIND, BASE)
5839 #define DEPENDENT_TYPE(KIND, BASE) \
5840   case Type::KIND:
5841 #define NON_CANONICAL_TYPE(KIND, BASE) \
5842   case Type::KIND:
5843 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5844   case Type::KIND:
5845 #include "clang/AST/TypeNodes.def"
5846     llvm_unreachable("@encode for dependent type!");
5847   }
5848   llvm_unreachable("bad type kind!");
5849 }
5850 
5851 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5852                                                  std::string &S,
5853                                                  const FieldDecl *FD,
5854                                                  bool includeVBases,
5855                                                  QualType *NotEncodedT) const {
5856   assert(RDecl && "Expected non-null RecordDecl");
5857   assert(!RDecl->isUnion() && "Should not be called for unions");
5858   if (!RDecl->getDefinition())
5859     return;
5860 
5861   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5862   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5863   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5864 
5865   if (CXXRec) {
5866     for (const auto &BI : CXXRec->bases()) {
5867       if (!BI.isVirtual()) {
5868         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5869         if (base->isEmpty())
5870           continue;
5871         uint64_t offs = toBits(layout.getBaseClassOffset(base));
5872         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5873                                   std::make_pair(offs, base));
5874       }
5875     }
5876   }
5877 
5878   unsigned i = 0;
5879   for (auto *Field : RDecl->fields()) {
5880     uint64_t offs = layout.getFieldOffset(i);
5881     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5882                               std::make_pair(offs, Field));
5883     ++i;
5884   }
5885 
5886   if (CXXRec && includeVBases) {
5887     for (const auto &BI : CXXRec->vbases()) {
5888       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5889       if (base->isEmpty())
5890         continue;
5891       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5892       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5893           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5894         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5895                                   std::make_pair(offs, base));
5896     }
5897   }
5898 
5899   CharUnits size;
5900   if (CXXRec) {
5901     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5902   } else {
5903     size = layout.getSize();
5904   }
5905 
5906 #ifndef NDEBUG
5907   uint64_t CurOffs = 0;
5908 #endif
5909   std::multimap<uint64_t, NamedDecl *>::iterator
5910     CurLayObj = FieldOrBaseOffsets.begin();
5911 
5912   if (CXXRec && CXXRec->isDynamicClass() &&
5913       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5914     if (FD) {
5915       S += "\"_vptr$";
5916       std::string recname = CXXRec->getNameAsString();
5917       if (recname.empty()) recname = "?";
5918       S += recname;
5919       S += '"';
5920     }
5921     S += "^^?";
5922 #ifndef NDEBUG
5923     CurOffs += getTypeSize(VoidPtrTy);
5924 #endif
5925   }
5926 
5927   if (!RDecl->hasFlexibleArrayMember()) {
5928     // Mark the end of the structure.
5929     uint64_t offs = toBits(size);
5930     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5931                               std::make_pair(offs, nullptr));
5932   }
5933 
5934   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5935 #ifndef NDEBUG
5936     assert(CurOffs <= CurLayObj->first);
5937     if (CurOffs < CurLayObj->first) {
5938       uint64_t padding = CurLayObj->first - CurOffs;
5939       // FIXME: There doesn't seem to be a way to indicate in the encoding that
5940       // packing/alignment of members is different that normal, in which case
5941       // the encoding will be out-of-sync with the real layout.
5942       // If the runtime switches to just consider the size of types without
5943       // taking into account alignment, we could make padding explicit in the
5944       // encoding (e.g. using arrays of chars). The encoding strings would be
5945       // longer then though.
5946       CurOffs += padding;
5947     }
5948 #endif
5949 
5950     NamedDecl *dcl = CurLayObj->second;
5951     if (!dcl)
5952       break; // reached end of structure.
5953 
5954     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5955       // We expand the bases without their virtual bases since those are going
5956       // in the initial structure. Note that this differs from gcc which
5957       // expands virtual bases each time one is encountered in the hierarchy,
5958       // making the encoding type bigger than it really is.
5959       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5960                                       NotEncodedT);
5961       assert(!base->isEmpty());
5962 #ifndef NDEBUG
5963       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5964 #endif
5965     } else {
5966       FieldDecl *field = cast<FieldDecl>(dcl);
5967       if (FD) {
5968         S += '"';
5969         S += field->getNameAsString();
5970         S += '"';
5971       }
5972 
5973       if (field->isBitField()) {
5974         EncodeBitField(this, S, field->getType(), field);
5975 #ifndef NDEBUG
5976         CurOffs += field->getBitWidthValue(*this);
5977 #endif
5978       } else {
5979         QualType qt = field->getType();
5980         getLegacyIntegralTypeEncoding(qt);
5981         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5982                                    /*OutermostType*/false,
5983                                    /*EncodingProperty*/false,
5984                                    /*StructField*/true,
5985                                    false, false, false, NotEncodedT);
5986 #ifndef NDEBUG
5987         CurOffs += getTypeSize(field->getType());
5988 #endif
5989       }
5990     }
5991   }
5992 }
5993 
5994 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5995                                                  std::string& S) const {
5996   if (QT & Decl::OBJC_TQ_In)
5997     S += 'n';
5998   if (QT & Decl::OBJC_TQ_Inout)
5999     S += 'N';
6000   if (QT & Decl::OBJC_TQ_Out)
6001     S += 'o';
6002   if (QT & Decl::OBJC_TQ_Bycopy)
6003     S += 'O';
6004   if (QT & Decl::OBJC_TQ_Byref)
6005     S += 'R';
6006   if (QT & Decl::OBJC_TQ_Oneway)
6007     S += 'V';
6008 }
6009 
6010 TypedefDecl *ASTContext::getObjCIdDecl() const {
6011   if (!ObjCIdDecl) {
6012     QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6013     T = getObjCObjectPointerType(T);
6014     ObjCIdDecl = buildImplicitTypedef(T, "id");
6015   }
6016   return ObjCIdDecl;
6017 }
6018 
6019 TypedefDecl *ASTContext::getObjCSelDecl() const {
6020   if (!ObjCSelDecl) {
6021     QualType T = getPointerType(ObjCBuiltinSelTy);
6022     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6023   }
6024   return ObjCSelDecl;
6025 }
6026 
6027 TypedefDecl *ASTContext::getObjCClassDecl() const {
6028   if (!ObjCClassDecl) {
6029     QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6030     T = getObjCObjectPointerType(T);
6031     ObjCClassDecl = buildImplicitTypedef(T, "Class");
6032   }
6033   return ObjCClassDecl;
6034 }
6035 
6036 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6037   if (!ObjCProtocolClassDecl) {
6038     ObjCProtocolClassDecl
6039       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6040                                   SourceLocation(),
6041                                   &Idents.get("Protocol"),
6042                                   /*typeParamList=*/nullptr,
6043                                   /*PrevDecl=*/nullptr,
6044                                   SourceLocation(), true);
6045   }
6046 
6047   return ObjCProtocolClassDecl;
6048 }
6049 
6050 //===----------------------------------------------------------------------===//
6051 // __builtin_va_list Construction Functions
6052 //===----------------------------------------------------------------------===//
6053 
6054 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6055                                                  StringRef Name) {
6056   // typedef char* __builtin[_ms]_va_list;
6057   QualType T = Context->getPointerType(Context->CharTy);
6058   return Context->buildImplicitTypedef(T, Name);
6059 }
6060 
6061 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6062   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6063 }
6064 
6065 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6066   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6067 }
6068 
6069 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6070   // typedef void* __builtin_va_list;
6071   QualType T = Context->getPointerType(Context->VoidTy);
6072   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6073 }
6074 
6075 static TypedefDecl *
6076 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6077   // struct __va_list
6078   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6079   if (Context->getLangOpts().CPlusPlus) {
6080     // namespace std { struct __va_list {
6081     NamespaceDecl *NS;
6082     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6083                                Context->getTranslationUnitDecl(),
6084                                /*Inline*/ false, SourceLocation(),
6085                                SourceLocation(), &Context->Idents.get("std"),
6086                                /*PrevDecl*/ nullptr);
6087     NS->setImplicit();
6088     VaListTagDecl->setDeclContext(NS);
6089   }
6090 
6091   VaListTagDecl->startDefinition();
6092 
6093   const size_t NumFields = 5;
6094   QualType FieldTypes[NumFields];
6095   const char *FieldNames[NumFields];
6096 
6097   // void *__stack;
6098   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6099   FieldNames[0] = "__stack";
6100 
6101   // void *__gr_top;
6102   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6103   FieldNames[1] = "__gr_top";
6104 
6105   // void *__vr_top;
6106   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6107   FieldNames[2] = "__vr_top";
6108 
6109   // int __gr_offs;
6110   FieldTypes[3] = Context->IntTy;
6111   FieldNames[3] = "__gr_offs";
6112 
6113   // int __vr_offs;
6114   FieldTypes[4] = Context->IntTy;
6115   FieldNames[4] = "__vr_offs";
6116 
6117   // Create fields
6118   for (unsigned i = 0; i < NumFields; ++i) {
6119     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6120                                          VaListTagDecl,
6121                                          SourceLocation(),
6122                                          SourceLocation(),
6123                                          &Context->Idents.get(FieldNames[i]),
6124                                          FieldTypes[i], /*TInfo=*/nullptr,
6125                                          /*BitWidth=*/nullptr,
6126                                          /*Mutable=*/false,
6127                                          ICIS_NoInit);
6128     Field->setAccess(AS_public);
6129     VaListTagDecl->addDecl(Field);
6130   }
6131   VaListTagDecl->completeDefinition();
6132   Context->VaListTagDecl = VaListTagDecl;
6133   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6134 
6135   // } __builtin_va_list;
6136   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6137 }
6138 
6139 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6140   // typedef struct __va_list_tag {
6141   RecordDecl *VaListTagDecl;
6142 
6143   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6144   VaListTagDecl->startDefinition();
6145 
6146   const size_t NumFields = 5;
6147   QualType FieldTypes[NumFields];
6148   const char *FieldNames[NumFields];
6149 
6150   //   unsigned char gpr;
6151   FieldTypes[0] = Context->UnsignedCharTy;
6152   FieldNames[0] = "gpr";
6153 
6154   //   unsigned char fpr;
6155   FieldTypes[1] = Context->UnsignedCharTy;
6156   FieldNames[1] = "fpr";
6157 
6158   //   unsigned short reserved;
6159   FieldTypes[2] = Context->UnsignedShortTy;
6160   FieldNames[2] = "reserved";
6161 
6162   //   void* overflow_arg_area;
6163   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6164   FieldNames[3] = "overflow_arg_area";
6165 
6166   //   void* reg_save_area;
6167   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6168   FieldNames[4] = "reg_save_area";
6169 
6170   // Create fields
6171   for (unsigned i = 0; i < NumFields; ++i) {
6172     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6173                                          SourceLocation(),
6174                                          SourceLocation(),
6175                                          &Context->Idents.get(FieldNames[i]),
6176                                          FieldTypes[i], /*TInfo=*/nullptr,
6177                                          /*BitWidth=*/nullptr,
6178                                          /*Mutable=*/false,
6179                                          ICIS_NoInit);
6180     Field->setAccess(AS_public);
6181     VaListTagDecl->addDecl(Field);
6182   }
6183   VaListTagDecl->completeDefinition();
6184   Context->VaListTagDecl = VaListTagDecl;
6185   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6186 
6187   // } __va_list_tag;
6188   TypedefDecl *VaListTagTypedefDecl =
6189       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6190 
6191   QualType VaListTagTypedefType =
6192     Context->getTypedefType(VaListTagTypedefDecl);
6193 
6194   // typedef __va_list_tag __builtin_va_list[1];
6195   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6196   QualType VaListTagArrayType
6197     = Context->getConstantArrayType(VaListTagTypedefType,
6198                                     Size, ArrayType::Normal, 0);
6199   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6200 }
6201 
6202 static TypedefDecl *
6203 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6204   // struct __va_list_tag {
6205   RecordDecl *VaListTagDecl;
6206   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6207   VaListTagDecl->startDefinition();
6208 
6209   const size_t NumFields = 4;
6210   QualType FieldTypes[NumFields];
6211   const char *FieldNames[NumFields];
6212 
6213   //   unsigned gp_offset;
6214   FieldTypes[0] = Context->UnsignedIntTy;
6215   FieldNames[0] = "gp_offset";
6216 
6217   //   unsigned fp_offset;
6218   FieldTypes[1] = Context->UnsignedIntTy;
6219   FieldNames[1] = "fp_offset";
6220 
6221   //   void* overflow_arg_area;
6222   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6223   FieldNames[2] = "overflow_arg_area";
6224 
6225   //   void* reg_save_area;
6226   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6227   FieldNames[3] = "reg_save_area";
6228 
6229   // Create fields
6230   for (unsigned i = 0; i < NumFields; ++i) {
6231     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6232                                          VaListTagDecl,
6233                                          SourceLocation(),
6234                                          SourceLocation(),
6235                                          &Context->Idents.get(FieldNames[i]),
6236                                          FieldTypes[i], /*TInfo=*/nullptr,
6237                                          /*BitWidth=*/nullptr,
6238                                          /*Mutable=*/false,
6239                                          ICIS_NoInit);
6240     Field->setAccess(AS_public);
6241     VaListTagDecl->addDecl(Field);
6242   }
6243   VaListTagDecl->completeDefinition();
6244   Context->VaListTagDecl = VaListTagDecl;
6245   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6246 
6247   // };
6248 
6249   // typedef struct __va_list_tag __builtin_va_list[1];
6250   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6251   QualType VaListTagArrayType =
6252       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6253   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6254 }
6255 
6256 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6257   // typedef int __builtin_va_list[4];
6258   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6259   QualType IntArrayType
6260     = Context->getConstantArrayType(Context->IntTy,
6261 				    Size, ArrayType::Normal, 0);
6262   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6263 }
6264 
6265 static TypedefDecl *
6266 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6267   // struct __va_list
6268   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6269   if (Context->getLangOpts().CPlusPlus) {
6270     // namespace std { struct __va_list {
6271     NamespaceDecl *NS;
6272     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6273                                Context->getTranslationUnitDecl(),
6274                                /*Inline*/false, SourceLocation(),
6275                                SourceLocation(), &Context->Idents.get("std"),
6276                                /*PrevDecl*/ nullptr);
6277     NS->setImplicit();
6278     VaListDecl->setDeclContext(NS);
6279   }
6280 
6281   VaListDecl->startDefinition();
6282 
6283   // void * __ap;
6284   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6285                                        VaListDecl,
6286                                        SourceLocation(),
6287                                        SourceLocation(),
6288                                        &Context->Idents.get("__ap"),
6289                                        Context->getPointerType(Context->VoidTy),
6290                                        /*TInfo=*/nullptr,
6291                                        /*BitWidth=*/nullptr,
6292                                        /*Mutable=*/false,
6293                                        ICIS_NoInit);
6294   Field->setAccess(AS_public);
6295   VaListDecl->addDecl(Field);
6296 
6297   // };
6298   VaListDecl->completeDefinition();
6299 
6300   // typedef struct __va_list __builtin_va_list;
6301   QualType T = Context->getRecordType(VaListDecl);
6302   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6303 }
6304 
6305 static TypedefDecl *
6306 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6307   // struct __va_list_tag {
6308   RecordDecl *VaListTagDecl;
6309   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6310   VaListTagDecl->startDefinition();
6311 
6312   const size_t NumFields = 4;
6313   QualType FieldTypes[NumFields];
6314   const char *FieldNames[NumFields];
6315 
6316   //   long __gpr;
6317   FieldTypes[0] = Context->LongTy;
6318   FieldNames[0] = "__gpr";
6319 
6320   //   long __fpr;
6321   FieldTypes[1] = Context->LongTy;
6322   FieldNames[1] = "__fpr";
6323 
6324   //   void *__overflow_arg_area;
6325   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6326   FieldNames[2] = "__overflow_arg_area";
6327 
6328   //   void *__reg_save_area;
6329   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6330   FieldNames[3] = "__reg_save_area";
6331 
6332   // Create fields
6333   for (unsigned i = 0; i < NumFields; ++i) {
6334     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6335                                          VaListTagDecl,
6336                                          SourceLocation(),
6337                                          SourceLocation(),
6338                                          &Context->Idents.get(FieldNames[i]),
6339                                          FieldTypes[i], /*TInfo=*/nullptr,
6340                                          /*BitWidth=*/nullptr,
6341                                          /*Mutable=*/false,
6342                                          ICIS_NoInit);
6343     Field->setAccess(AS_public);
6344     VaListTagDecl->addDecl(Field);
6345   }
6346   VaListTagDecl->completeDefinition();
6347   Context->VaListTagDecl = VaListTagDecl;
6348   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6349 
6350   // };
6351 
6352   // typedef __va_list_tag __builtin_va_list[1];
6353   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6354   QualType VaListTagArrayType =
6355       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6356 
6357   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6358 }
6359 
6360 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6361                                      TargetInfo::BuiltinVaListKind Kind) {
6362   switch (Kind) {
6363   case TargetInfo::CharPtrBuiltinVaList:
6364     return CreateCharPtrBuiltinVaListDecl(Context);
6365   case TargetInfo::VoidPtrBuiltinVaList:
6366     return CreateVoidPtrBuiltinVaListDecl(Context);
6367   case TargetInfo::AArch64ABIBuiltinVaList:
6368     return CreateAArch64ABIBuiltinVaListDecl(Context);
6369   case TargetInfo::PowerABIBuiltinVaList:
6370     return CreatePowerABIBuiltinVaListDecl(Context);
6371   case TargetInfo::X86_64ABIBuiltinVaList:
6372     return CreateX86_64ABIBuiltinVaListDecl(Context);
6373   case TargetInfo::PNaClABIBuiltinVaList:
6374     return CreatePNaClABIBuiltinVaListDecl(Context);
6375   case TargetInfo::AAPCSABIBuiltinVaList:
6376     return CreateAAPCSABIBuiltinVaListDecl(Context);
6377   case TargetInfo::SystemZBuiltinVaList:
6378     return CreateSystemZBuiltinVaListDecl(Context);
6379   }
6380 
6381   llvm_unreachable("Unhandled __builtin_va_list type kind");
6382 }
6383 
6384 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6385   if (!BuiltinVaListDecl) {
6386     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6387     assert(BuiltinVaListDecl->isImplicit());
6388   }
6389 
6390   return BuiltinVaListDecl;
6391 }
6392 
6393 Decl *ASTContext::getVaListTagDecl() const {
6394   // Force the creation of VaListTagDecl by building the __builtin_va_list
6395   // declaration.
6396   if (!VaListTagDecl)
6397     (void)getBuiltinVaListDecl();
6398 
6399   return VaListTagDecl;
6400 }
6401 
6402 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6403   if (!BuiltinMSVaListDecl)
6404     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6405 
6406   return BuiltinMSVaListDecl;
6407 }
6408 
6409 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6410   assert(ObjCConstantStringType.isNull() &&
6411          "'NSConstantString' type already set!");
6412 
6413   ObjCConstantStringType = getObjCInterfaceType(Decl);
6414 }
6415 
6416 /// \brief Retrieve the template name that corresponds to a non-empty
6417 /// lookup.
6418 TemplateName
6419 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6420                                       UnresolvedSetIterator End) const {
6421   unsigned size = End - Begin;
6422   assert(size > 1 && "set is not overloaded!");
6423 
6424   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6425                           size * sizeof(FunctionTemplateDecl*));
6426   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6427 
6428   NamedDecl **Storage = OT->getStorage();
6429   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6430     NamedDecl *D = *I;
6431     assert(isa<FunctionTemplateDecl>(D) ||
6432            (isa<UsingShadowDecl>(D) &&
6433             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6434     *Storage++ = D;
6435   }
6436 
6437   return TemplateName(OT);
6438 }
6439 
6440 /// \brief Retrieve the template name that represents a qualified
6441 /// template name such as \c std::vector.
6442 TemplateName
6443 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6444                                      bool TemplateKeyword,
6445                                      TemplateDecl *Template) const {
6446   assert(NNS && "Missing nested-name-specifier in qualified template name");
6447 
6448   // FIXME: Canonicalization?
6449   llvm::FoldingSetNodeID ID;
6450   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6451 
6452   void *InsertPos = nullptr;
6453   QualifiedTemplateName *QTN =
6454     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6455   if (!QTN) {
6456     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6457         QualifiedTemplateName(NNS, TemplateKeyword, Template);
6458     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6459   }
6460 
6461   return TemplateName(QTN);
6462 }
6463 
6464 /// \brief Retrieve the template name that represents a dependent
6465 /// template name such as \c MetaFun::template apply.
6466 TemplateName
6467 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6468                                      const IdentifierInfo *Name) const {
6469   assert((!NNS || NNS->isDependent()) &&
6470          "Nested name specifier must be dependent");
6471 
6472   llvm::FoldingSetNodeID ID;
6473   DependentTemplateName::Profile(ID, NNS, Name);
6474 
6475   void *InsertPos = nullptr;
6476   DependentTemplateName *QTN =
6477     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6478 
6479   if (QTN)
6480     return TemplateName(QTN);
6481 
6482   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6483   if (CanonNNS == NNS) {
6484     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6485         DependentTemplateName(NNS, Name);
6486   } else {
6487     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6488     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6489         DependentTemplateName(NNS, Name, Canon);
6490     DependentTemplateName *CheckQTN =
6491       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6492     assert(!CheckQTN && "Dependent type name canonicalization broken");
6493     (void)CheckQTN;
6494   }
6495 
6496   DependentTemplateNames.InsertNode(QTN, InsertPos);
6497   return TemplateName(QTN);
6498 }
6499 
6500 /// \brief Retrieve the template name that represents a dependent
6501 /// template name such as \c MetaFun::template operator+.
6502 TemplateName
6503 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6504                                      OverloadedOperatorKind Operator) const {
6505   assert((!NNS || NNS->isDependent()) &&
6506          "Nested name specifier must be dependent");
6507 
6508   llvm::FoldingSetNodeID ID;
6509   DependentTemplateName::Profile(ID, NNS, Operator);
6510 
6511   void *InsertPos = nullptr;
6512   DependentTemplateName *QTN
6513     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6514 
6515   if (QTN)
6516     return TemplateName(QTN);
6517 
6518   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6519   if (CanonNNS == NNS) {
6520     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6521         DependentTemplateName(NNS, Operator);
6522   } else {
6523     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6524     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6525         DependentTemplateName(NNS, Operator, Canon);
6526 
6527     DependentTemplateName *CheckQTN
6528       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6529     assert(!CheckQTN && "Dependent template name canonicalization broken");
6530     (void)CheckQTN;
6531   }
6532 
6533   DependentTemplateNames.InsertNode(QTN, InsertPos);
6534   return TemplateName(QTN);
6535 }
6536 
6537 TemplateName
6538 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6539                                          TemplateName replacement) const {
6540   llvm::FoldingSetNodeID ID;
6541   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6542 
6543   void *insertPos = nullptr;
6544   SubstTemplateTemplateParmStorage *subst
6545     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6546 
6547   if (!subst) {
6548     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6549     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6550   }
6551 
6552   return TemplateName(subst);
6553 }
6554 
6555 TemplateName
6556 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6557                                        const TemplateArgument &ArgPack) const {
6558   ASTContext &Self = const_cast<ASTContext &>(*this);
6559   llvm::FoldingSetNodeID ID;
6560   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6561 
6562   void *InsertPos = nullptr;
6563   SubstTemplateTemplateParmPackStorage *Subst
6564     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6565 
6566   if (!Subst) {
6567     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6568                                                            ArgPack.pack_size(),
6569                                                          ArgPack.pack_begin());
6570     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6571   }
6572 
6573   return TemplateName(Subst);
6574 }
6575 
6576 /// getFromTargetType - Given one of the integer types provided by
6577 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6578 /// is actually a value of type @c TargetInfo::IntType.
6579 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6580   switch (Type) {
6581   case TargetInfo::NoInt: return CanQualType();
6582   case TargetInfo::SignedChar: return SignedCharTy;
6583   case TargetInfo::UnsignedChar: return UnsignedCharTy;
6584   case TargetInfo::SignedShort: return ShortTy;
6585   case TargetInfo::UnsignedShort: return UnsignedShortTy;
6586   case TargetInfo::SignedInt: return IntTy;
6587   case TargetInfo::UnsignedInt: return UnsignedIntTy;
6588   case TargetInfo::SignedLong: return LongTy;
6589   case TargetInfo::UnsignedLong: return UnsignedLongTy;
6590   case TargetInfo::SignedLongLong: return LongLongTy;
6591   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6592   }
6593 
6594   llvm_unreachable("Unhandled TargetInfo::IntType value");
6595 }
6596 
6597 //===----------------------------------------------------------------------===//
6598 //                        Type Predicates.
6599 //===----------------------------------------------------------------------===//
6600 
6601 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6602 /// garbage collection attribute.
6603 ///
6604 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6605   if (getLangOpts().getGC() == LangOptions::NonGC)
6606     return Qualifiers::GCNone;
6607 
6608   assert(getLangOpts().ObjC1);
6609   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6610 
6611   // Default behaviour under objective-C's gc is for ObjC pointers
6612   // (or pointers to them) be treated as though they were declared
6613   // as __strong.
6614   if (GCAttrs == Qualifiers::GCNone) {
6615     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6616       return Qualifiers::Strong;
6617     else if (Ty->isPointerType())
6618       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6619   } else {
6620     // It's not valid to set GC attributes on anything that isn't a
6621     // pointer.
6622 #ifndef NDEBUG
6623     QualType CT = Ty->getCanonicalTypeInternal();
6624     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6625       CT = AT->getElementType();
6626     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6627 #endif
6628   }
6629   return GCAttrs;
6630 }
6631 
6632 //===----------------------------------------------------------------------===//
6633 //                        Type Compatibility Testing
6634 //===----------------------------------------------------------------------===//
6635 
6636 /// areCompatVectorTypes - Return true if the two specified vector types are
6637 /// compatible.
6638 static bool areCompatVectorTypes(const VectorType *LHS,
6639                                  const VectorType *RHS) {
6640   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6641   return LHS->getElementType() == RHS->getElementType() &&
6642          LHS->getNumElements() == RHS->getNumElements();
6643 }
6644 
6645 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6646                                           QualType SecondVec) {
6647   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6648   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6649 
6650   if (hasSameUnqualifiedType(FirstVec, SecondVec))
6651     return true;
6652 
6653   // Treat Neon vector types and most AltiVec vector types as if they are the
6654   // equivalent GCC vector types.
6655   const VectorType *First = FirstVec->getAs<VectorType>();
6656   const VectorType *Second = SecondVec->getAs<VectorType>();
6657   if (First->getNumElements() == Second->getNumElements() &&
6658       hasSameType(First->getElementType(), Second->getElementType()) &&
6659       First->getVectorKind() != VectorType::AltiVecPixel &&
6660       First->getVectorKind() != VectorType::AltiVecBool &&
6661       Second->getVectorKind() != VectorType::AltiVecPixel &&
6662       Second->getVectorKind() != VectorType::AltiVecBool)
6663     return true;
6664 
6665   return false;
6666 }
6667 
6668 //===----------------------------------------------------------------------===//
6669 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6670 //===----------------------------------------------------------------------===//
6671 
6672 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6673 /// inheritance hierarchy of 'rProto'.
6674 bool
6675 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6676                                            ObjCProtocolDecl *rProto) const {
6677   if (declaresSameEntity(lProto, rProto))
6678     return true;
6679   for (auto *PI : rProto->protocols())
6680     if (ProtocolCompatibleWithProtocol(lProto, PI))
6681       return true;
6682   return false;
6683 }
6684 
6685 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
6686 /// Class<pr1, ...>.
6687 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6688                                                       QualType rhs) {
6689   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6690   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6691   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6692 
6693   for (auto *lhsProto : lhsQID->quals()) {
6694     bool match = false;
6695     for (auto *rhsProto : rhsOPT->quals()) {
6696       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6697         match = true;
6698         break;
6699       }
6700     }
6701     if (!match)
6702       return false;
6703   }
6704   return true;
6705 }
6706 
6707 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6708 /// ObjCQualifiedIDType.
6709 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6710                                                    bool compare) {
6711   // Allow id<P..> and an 'id' or void* type in all cases.
6712   if (lhs->isVoidPointerType() ||
6713       lhs->isObjCIdType() || lhs->isObjCClassType())
6714     return true;
6715   else if (rhs->isVoidPointerType() ||
6716            rhs->isObjCIdType() || rhs->isObjCClassType())
6717     return true;
6718 
6719   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6720     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6721 
6722     if (!rhsOPT) return false;
6723 
6724     if (rhsOPT->qual_empty()) {
6725       // If the RHS is a unqualified interface pointer "NSString*",
6726       // make sure we check the class hierarchy.
6727       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6728         for (auto *I : lhsQID->quals()) {
6729           // when comparing an id<P> on lhs with a static type on rhs,
6730           // see if static class implements all of id's protocols, directly or
6731           // through its super class and categories.
6732           if (!rhsID->ClassImplementsProtocol(I, true))
6733             return false;
6734         }
6735       }
6736       // If there are no qualifiers and no interface, we have an 'id'.
6737       return true;
6738     }
6739     // Both the right and left sides have qualifiers.
6740     for (auto *lhsProto : lhsQID->quals()) {
6741       bool match = false;
6742 
6743       // when comparing an id<P> on lhs with a static type on rhs,
6744       // see if static class implements all of id's protocols, directly or
6745       // through its super class and categories.
6746       for (auto *rhsProto : rhsOPT->quals()) {
6747         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6748             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6749           match = true;
6750           break;
6751         }
6752       }
6753       // If the RHS is a qualified interface pointer "NSString<P>*",
6754       // make sure we check the class hierarchy.
6755       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6756         for (auto *I : lhsQID->quals()) {
6757           // when comparing an id<P> on lhs with a static type on rhs,
6758           // see if static class implements all of id's protocols, directly or
6759           // through its super class and categories.
6760           if (rhsID->ClassImplementsProtocol(I, true)) {
6761             match = true;
6762             break;
6763           }
6764         }
6765       }
6766       if (!match)
6767         return false;
6768     }
6769 
6770     return true;
6771   }
6772 
6773   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6774   assert(rhsQID && "One of the LHS/RHS should be id<x>");
6775 
6776   if (const ObjCObjectPointerType *lhsOPT =
6777         lhs->getAsObjCInterfacePointerType()) {
6778     // If both the right and left sides have qualifiers.
6779     for (auto *lhsProto : lhsOPT->quals()) {
6780       bool match = false;
6781 
6782       // when comparing an id<P> on rhs with a static type on lhs,
6783       // see if static class implements all of id's protocols, directly or
6784       // through its super class and categories.
6785       // First, lhs protocols in the qualifier list must be found, direct
6786       // or indirect in rhs's qualifier list or it is a mismatch.
6787       for (auto *rhsProto : rhsQID->quals()) {
6788         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6789             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6790           match = true;
6791           break;
6792         }
6793       }
6794       if (!match)
6795         return false;
6796     }
6797 
6798     // Static class's protocols, or its super class or category protocols
6799     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6800     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6801       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6802       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6803       // This is rather dubious but matches gcc's behavior. If lhs has
6804       // no type qualifier and its class has no static protocol(s)
6805       // assume that it is mismatch.
6806       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6807         return false;
6808       for (auto *lhsProto : LHSInheritedProtocols) {
6809         bool match = false;
6810         for (auto *rhsProto : rhsQID->quals()) {
6811           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6812               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6813             match = true;
6814             break;
6815           }
6816         }
6817         if (!match)
6818           return false;
6819       }
6820     }
6821     return true;
6822   }
6823   return false;
6824 }
6825 
6826 /// canAssignObjCInterfaces - Return true if the two interface types are
6827 /// compatible for assignment from RHS to LHS.  This handles validation of any
6828 /// protocol qualifiers on the LHS or RHS.
6829 ///
6830 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6831                                          const ObjCObjectPointerType *RHSOPT) {
6832   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6833   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6834 
6835   // If either type represents the built-in 'id' or 'Class' types, return true.
6836   if (LHS->isObjCUnqualifiedIdOrClass() ||
6837       RHS->isObjCUnqualifiedIdOrClass())
6838     return true;
6839 
6840   // Function object that propagates a successful result or handles
6841   // __kindof types.
6842   auto finish = [&](bool succeeded) -> bool {
6843     if (succeeded)
6844       return true;
6845 
6846     if (!RHS->isKindOfType())
6847       return false;
6848 
6849     // Strip off __kindof and protocol qualifiers, then check whether
6850     // we can assign the other way.
6851     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6852                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6853   };
6854 
6855   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6856     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6857                                                     QualType(RHSOPT,0),
6858                                                     false));
6859   }
6860 
6861   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6862     return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6863                                                        QualType(RHSOPT,0)));
6864   }
6865 
6866   // If we have 2 user-defined types, fall into that path.
6867   if (LHS->getInterface() && RHS->getInterface()) {
6868     return finish(canAssignObjCInterfaces(LHS, RHS));
6869   }
6870 
6871   return false;
6872 }
6873 
6874 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6875 /// for providing type-safety for objective-c pointers used to pass/return
6876 /// arguments in block literals. When passed as arguments, passing 'A*' where
6877 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6878 /// not OK. For the return type, the opposite is not OK.
6879 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6880                                          const ObjCObjectPointerType *LHSOPT,
6881                                          const ObjCObjectPointerType *RHSOPT,
6882                                          bool BlockReturnType) {
6883 
6884   // Function object that propagates a successful result or handles
6885   // __kindof types.
6886   auto finish = [&](bool succeeded) -> bool {
6887     if (succeeded)
6888       return true;
6889 
6890     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6891     if (!Expected->isKindOfType())
6892       return false;
6893 
6894     // Strip off __kindof and protocol qualifiers, then check whether
6895     // we can assign the other way.
6896     return canAssignObjCInterfacesInBlockPointer(
6897              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6898              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6899              BlockReturnType);
6900   };
6901 
6902   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6903     return true;
6904 
6905   if (LHSOPT->isObjCBuiltinType()) {
6906     return finish(RHSOPT->isObjCBuiltinType() ||
6907                   RHSOPT->isObjCQualifiedIdType());
6908   }
6909 
6910   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6911     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6912                                                     QualType(RHSOPT,0),
6913                                                     false));
6914 
6915   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6916   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6917   if (LHS && RHS)  { // We have 2 user-defined types.
6918     if (LHS != RHS) {
6919       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6920         return finish(BlockReturnType);
6921       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6922         return finish(!BlockReturnType);
6923     }
6924     else
6925       return true;
6926   }
6927   return false;
6928 }
6929 
6930 /// Comparison routine for Objective-C protocols to be used with
6931 /// llvm::array_pod_sort.
6932 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6933                                       ObjCProtocolDecl * const *rhs) {
6934   return (*lhs)->getName().compare((*rhs)->getName());
6935 
6936 }
6937 
6938 /// getIntersectionOfProtocols - This routine finds the intersection of set
6939 /// of protocols inherited from two distinct objective-c pointer objects with
6940 /// the given common base.
6941 /// It is used to build composite qualifier list of the composite type of
6942 /// the conditional expression involving two objective-c pointer objects.
6943 static
6944 void getIntersectionOfProtocols(ASTContext &Context,
6945                                 const ObjCInterfaceDecl *CommonBase,
6946                                 const ObjCObjectPointerType *LHSOPT,
6947                                 const ObjCObjectPointerType *RHSOPT,
6948       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
6949 
6950   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6951   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6952   assert(LHS->getInterface() && "LHS must have an interface base");
6953   assert(RHS->getInterface() && "RHS must have an interface base");
6954 
6955   // Add all of the protocols for the LHS.
6956   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6957 
6958   // Start with the protocol qualifiers.
6959   for (auto proto : LHS->quals()) {
6960     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
6961   }
6962 
6963   // Also add the protocols associated with the LHS interface.
6964   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6965 
6966   // Add all of the protocls for the RHS.
6967   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6968 
6969   // Start with the protocol qualifiers.
6970   for (auto proto : RHS->quals()) {
6971     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
6972   }
6973 
6974   // Also add the protocols associated with the RHS interface.
6975   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6976 
6977   // Compute the intersection of the collected protocol sets.
6978   for (auto proto : LHSProtocolSet) {
6979     if (RHSProtocolSet.count(proto))
6980       IntersectionSet.push_back(proto);
6981   }
6982 
6983   // Compute the set of protocols that is implied by either the common type or
6984   // the protocols within the intersection.
6985   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6986   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6987 
6988   // Remove any implied protocols from the list of inherited protocols.
6989   if (!ImpliedProtocols.empty()) {
6990     IntersectionSet.erase(
6991       std::remove_if(IntersectionSet.begin(),
6992                      IntersectionSet.end(),
6993                      [&](ObjCProtocolDecl *proto) -> bool {
6994                        return ImpliedProtocols.count(proto) > 0;
6995                      }),
6996       IntersectionSet.end());
6997   }
6998 
6999   // Sort the remaining protocols by name.
7000   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7001                        compareObjCProtocolsByName);
7002 }
7003 
7004 /// Determine whether the first type is a subtype of the second.
7005 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7006                                      QualType rhs) {
7007   // Common case: two object pointers.
7008   const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7009   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7010   if (lhsOPT && rhsOPT)
7011     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7012 
7013   // Two block pointers.
7014   const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7015   const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7016   if (lhsBlock && rhsBlock)
7017     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7018 
7019   // If either is an unqualified 'id' and the other is a block, it's
7020   // acceptable.
7021   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7022       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7023     return true;
7024 
7025   return false;
7026 }
7027 
7028 // Check that the given Objective-C type argument lists are equivalent.
7029 static bool sameObjCTypeArgs(ASTContext &ctx,
7030                              const ObjCInterfaceDecl *iface,
7031                              ArrayRef<QualType> lhsArgs,
7032                              ArrayRef<QualType> rhsArgs,
7033                              bool stripKindOf) {
7034   if (lhsArgs.size() != rhsArgs.size())
7035     return false;
7036 
7037   ObjCTypeParamList *typeParams = iface->getTypeParamList();
7038   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7039     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7040       continue;
7041 
7042     switch (typeParams->begin()[i]->getVariance()) {
7043     case ObjCTypeParamVariance::Invariant:
7044       if (!stripKindOf ||
7045           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7046                            rhsArgs[i].stripObjCKindOfType(ctx))) {
7047         return false;
7048       }
7049       break;
7050 
7051     case ObjCTypeParamVariance::Covariant:
7052       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7053         return false;
7054       break;
7055 
7056     case ObjCTypeParamVariance::Contravariant:
7057       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7058         return false;
7059       break;
7060     }
7061   }
7062 
7063   return true;
7064 }
7065 
7066 QualType ASTContext::areCommonBaseCompatible(
7067            const ObjCObjectPointerType *Lptr,
7068            const ObjCObjectPointerType *Rptr) {
7069   const ObjCObjectType *LHS = Lptr->getObjectType();
7070   const ObjCObjectType *RHS = Rptr->getObjectType();
7071   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7072   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7073 
7074   if (!LDecl || !RDecl)
7075     return QualType();
7076 
7077   // Follow the left-hand side up the class hierarchy until we either hit a
7078   // root or find the RHS. Record the ancestors in case we don't find it.
7079   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7080     LHSAncestors;
7081   while (true) {
7082     // Record this ancestor. We'll need this if the common type isn't in the
7083     // path from the LHS to the root.
7084     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7085 
7086     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7087       // Get the type arguments.
7088       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7089       bool anyChanges = false;
7090       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7091         // Both have type arguments, compare them.
7092         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7093                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7094                               /*stripKindOf=*/true))
7095           return QualType();
7096       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7097         // If only one has type arguments, the result will not have type
7098         // arguments.
7099         LHSTypeArgs = { };
7100         anyChanges = true;
7101       }
7102 
7103       // Compute the intersection of protocols.
7104       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7105       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7106                                  Protocols);
7107       if (!Protocols.empty())
7108         anyChanges = true;
7109 
7110       // If anything in the LHS will have changed, build a new result type.
7111       if (anyChanges) {
7112         QualType Result = getObjCInterfaceType(LHS->getInterface());
7113         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7114                                    LHS->isKindOfType());
7115         return getObjCObjectPointerType(Result);
7116       }
7117 
7118       return getObjCObjectPointerType(QualType(LHS, 0));
7119     }
7120 
7121     // Find the superclass.
7122     QualType LHSSuperType = LHS->getSuperClassType();
7123     if (LHSSuperType.isNull())
7124       break;
7125 
7126     LHS = LHSSuperType->castAs<ObjCObjectType>();
7127   }
7128 
7129   // We didn't find anything by following the LHS to its root; now check
7130   // the RHS against the cached set of ancestors.
7131   while (true) {
7132     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7133     if (KnownLHS != LHSAncestors.end()) {
7134       LHS = KnownLHS->second;
7135 
7136       // Get the type arguments.
7137       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7138       bool anyChanges = false;
7139       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7140         // Both have type arguments, compare them.
7141         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7142                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7143                               /*stripKindOf=*/true))
7144           return QualType();
7145       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7146         // If only one has type arguments, the result will not have type
7147         // arguments.
7148         RHSTypeArgs = { };
7149         anyChanges = true;
7150       }
7151 
7152       // Compute the intersection of protocols.
7153       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7154       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7155                                  Protocols);
7156       if (!Protocols.empty())
7157         anyChanges = true;
7158 
7159       if (anyChanges) {
7160         QualType Result = getObjCInterfaceType(RHS->getInterface());
7161         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7162                                    RHS->isKindOfType());
7163         return getObjCObjectPointerType(Result);
7164       }
7165 
7166       return getObjCObjectPointerType(QualType(RHS, 0));
7167     }
7168 
7169     // Find the superclass of the RHS.
7170     QualType RHSSuperType = RHS->getSuperClassType();
7171     if (RHSSuperType.isNull())
7172       break;
7173 
7174     RHS = RHSSuperType->castAs<ObjCObjectType>();
7175   }
7176 
7177   return QualType();
7178 }
7179 
7180 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7181                                          const ObjCObjectType *RHS) {
7182   assert(LHS->getInterface() && "LHS is not an interface type");
7183   assert(RHS->getInterface() && "RHS is not an interface type");
7184 
7185   // Verify that the base decls are compatible: the RHS must be a subclass of
7186   // the LHS.
7187   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7188   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7189   if (!IsSuperClass)
7190     return false;
7191 
7192   // If the LHS has protocol qualifiers, determine whether all of them are
7193   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7194   // LHS).
7195   if (LHS->getNumProtocols() > 0) {
7196     // OK if conversion of LHS to SuperClass results in narrowing of types
7197     // ; i.e., SuperClass may implement at least one of the protocols
7198     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7199     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7200     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7201     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7202     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7203     // qualifiers.
7204     for (auto *RHSPI : RHS->quals())
7205       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7206     // If there is no protocols associated with RHS, it is not a match.
7207     if (SuperClassInheritedProtocols.empty())
7208       return false;
7209 
7210     for (const auto *LHSProto : LHS->quals()) {
7211       bool SuperImplementsProtocol = false;
7212       for (auto *SuperClassProto : SuperClassInheritedProtocols)
7213         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7214           SuperImplementsProtocol = true;
7215           break;
7216         }
7217       if (!SuperImplementsProtocol)
7218         return false;
7219     }
7220   }
7221 
7222   // If the LHS is specialized, we may need to check type arguments.
7223   if (LHS->isSpecialized()) {
7224     // Follow the superclass chain until we've matched the LHS class in the
7225     // hierarchy. This substitutes type arguments through.
7226     const ObjCObjectType *RHSSuper = RHS;
7227     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7228       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7229 
7230     // If the RHS is specializd, compare type arguments.
7231     if (RHSSuper->isSpecialized() &&
7232         !sameObjCTypeArgs(*this, LHS->getInterface(),
7233                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7234                           /*stripKindOf=*/true)) {
7235       return false;
7236     }
7237   }
7238 
7239   return true;
7240 }
7241 
7242 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7243   // get the "pointed to" types
7244   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7245   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7246 
7247   if (!LHSOPT || !RHSOPT)
7248     return false;
7249 
7250   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7251          canAssignObjCInterfaces(RHSOPT, LHSOPT);
7252 }
7253 
7254 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7255   return canAssignObjCInterfaces(
7256                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7257                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7258 }
7259 
7260 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7261 /// both shall have the identically qualified version of a compatible type.
7262 /// C99 6.2.7p1: Two types have compatible types if their types are the
7263 /// same. See 6.7.[2,3,5] for additional rules.
7264 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7265                                     bool CompareUnqualified) {
7266   if (getLangOpts().CPlusPlus)
7267     return hasSameType(LHS, RHS);
7268 
7269   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7270 }
7271 
7272 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7273   return typesAreCompatible(LHS, RHS);
7274 }
7275 
7276 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7277   return !mergeTypes(LHS, RHS, true).isNull();
7278 }
7279 
7280 /// mergeTransparentUnionType - if T is a transparent union type and a member
7281 /// of T is compatible with SubType, return the merged type, else return
7282 /// QualType()
7283 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7284                                                bool OfBlockPointer,
7285                                                bool Unqualified) {
7286   if (const RecordType *UT = T->getAsUnionType()) {
7287     RecordDecl *UD = UT->getDecl();
7288     if (UD->hasAttr<TransparentUnionAttr>()) {
7289       for (const auto *I : UD->fields()) {
7290         QualType ET = I->getType().getUnqualifiedType();
7291         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7292         if (!MT.isNull())
7293           return MT;
7294       }
7295     }
7296   }
7297 
7298   return QualType();
7299 }
7300 
7301 /// mergeFunctionParameterTypes - merge two types which appear as function
7302 /// parameter types
7303 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7304                                                  bool OfBlockPointer,
7305                                                  bool Unqualified) {
7306   // GNU extension: two types are compatible if they appear as a function
7307   // argument, one of the types is a transparent union type and the other
7308   // type is compatible with a union member
7309   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7310                                               Unqualified);
7311   if (!lmerge.isNull())
7312     return lmerge;
7313 
7314   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7315                                               Unqualified);
7316   if (!rmerge.isNull())
7317     return rmerge;
7318 
7319   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7320 }
7321 
7322 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7323                                         bool OfBlockPointer,
7324                                         bool Unqualified) {
7325   const FunctionType *lbase = lhs->getAs<FunctionType>();
7326   const FunctionType *rbase = rhs->getAs<FunctionType>();
7327   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7328   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7329   bool allLTypes = true;
7330   bool allRTypes = true;
7331 
7332   // Check return type
7333   QualType retType;
7334   if (OfBlockPointer) {
7335     QualType RHS = rbase->getReturnType();
7336     QualType LHS = lbase->getReturnType();
7337     bool UnqualifiedResult = Unqualified;
7338     if (!UnqualifiedResult)
7339       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7340     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7341   }
7342   else
7343     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7344                          Unqualified);
7345   if (retType.isNull()) return QualType();
7346 
7347   if (Unqualified)
7348     retType = retType.getUnqualifiedType();
7349 
7350   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7351   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7352   if (Unqualified) {
7353     LRetType = LRetType.getUnqualifiedType();
7354     RRetType = RRetType.getUnqualifiedType();
7355   }
7356 
7357   if (getCanonicalType(retType) != LRetType)
7358     allLTypes = false;
7359   if (getCanonicalType(retType) != RRetType)
7360     allRTypes = false;
7361 
7362   // FIXME: double check this
7363   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7364   //                           rbase->getRegParmAttr() != 0 &&
7365   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7366   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7367   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7368 
7369   // Compatible functions must have compatible calling conventions
7370   if (lbaseInfo.getCC() != rbaseInfo.getCC())
7371     return QualType();
7372 
7373   // Regparm is part of the calling convention.
7374   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7375     return QualType();
7376   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7377     return QualType();
7378 
7379   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7380     return QualType();
7381 
7382   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7383   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7384 
7385   if (lbaseInfo.getNoReturn() != NoReturn)
7386     allLTypes = false;
7387   if (rbaseInfo.getNoReturn() != NoReturn)
7388     allRTypes = false;
7389 
7390   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7391 
7392   if (lproto && rproto) { // two C99 style function prototypes
7393     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7394            "C++ shouldn't be here");
7395     // Compatible functions must have the same number of parameters
7396     if (lproto->getNumParams() != rproto->getNumParams())
7397       return QualType();
7398 
7399     // Variadic and non-variadic functions aren't compatible
7400     if (lproto->isVariadic() != rproto->isVariadic())
7401       return QualType();
7402 
7403     if (lproto->getTypeQuals() != rproto->getTypeQuals())
7404       return QualType();
7405 
7406     if (LangOpts.ObjCAutoRefCount &&
7407         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7408       return QualType();
7409 
7410     // Check parameter type compatibility
7411     SmallVector<QualType, 10> types;
7412     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7413       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7414       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7415       QualType paramType = mergeFunctionParameterTypes(
7416           lParamType, rParamType, OfBlockPointer, Unqualified);
7417       if (paramType.isNull())
7418         return QualType();
7419 
7420       if (Unqualified)
7421         paramType = paramType.getUnqualifiedType();
7422 
7423       types.push_back(paramType);
7424       if (Unqualified) {
7425         lParamType = lParamType.getUnqualifiedType();
7426         rParamType = rParamType.getUnqualifiedType();
7427       }
7428 
7429       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7430         allLTypes = false;
7431       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7432         allRTypes = false;
7433     }
7434 
7435     if (allLTypes) return lhs;
7436     if (allRTypes) return rhs;
7437 
7438     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7439     EPI.ExtInfo = einfo;
7440     return getFunctionType(retType, types, EPI);
7441   }
7442 
7443   if (lproto) allRTypes = false;
7444   if (rproto) allLTypes = false;
7445 
7446   const FunctionProtoType *proto = lproto ? lproto : rproto;
7447   if (proto) {
7448     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7449     if (proto->isVariadic()) return QualType();
7450     // Check that the types are compatible with the types that
7451     // would result from default argument promotions (C99 6.7.5.3p15).
7452     // The only types actually affected are promotable integer
7453     // types and floats, which would be passed as a different
7454     // type depending on whether the prototype is visible.
7455     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7456       QualType paramTy = proto->getParamType(i);
7457 
7458       // Look at the converted type of enum types, since that is the type used
7459       // to pass enum values.
7460       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7461         paramTy = Enum->getDecl()->getIntegerType();
7462         if (paramTy.isNull())
7463           return QualType();
7464       }
7465 
7466       if (paramTy->isPromotableIntegerType() ||
7467           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7468         return QualType();
7469     }
7470 
7471     if (allLTypes) return lhs;
7472     if (allRTypes) return rhs;
7473 
7474     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7475     EPI.ExtInfo = einfo;
7476     return getFunctionType(retType, proto->getParamTypes(), EPI);
7477   }
7478 
7479   if (allLTypes) return lhs;
7480   if (allRTypes) return rhs;
7481   return getFunctionNoProtoType(retType, einfo);
7482 }
7483 
7484 /// Given that we have an enum type and a non-enum type, try to merge them.
7485 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7486                                      QualType other, bool isBlockReturnType) {
7487   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7488   // a signed integer type, or an unsigned integer type.
7489   // Compatibility is based on the underlying type, not the promotion
7490   // type.
7491   QualType underlyingType = ET->getDecl()->getIntegerType();
7492   if (underlyingType.isNull()) return QualType();
7493   if (Context.hasSameType(underlyingType, other))
7494     return other;
7495 
7496   // In block return types, we're more permissive and accept any
7497   // integral type of the same size.
7498   if (isBlockReturnType && other->isIntegerType() &&
7499       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7500     return other;
7501 
7502   return QualType();
7503 }
7504 
7505 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7506                                 bool OfBlockPointer,
7507                                 bool Unqualified, bool BlockReturnType) {
7508   // C++ [expr]: If an expression initially has the type "reference to T", the
7509   // type is adjusted to "T" prior to any further analysis, the expression
7510   // designates the object or function denoted by the reference, and the
7511   // expression is an lvalue unless the reference is an rvalue reference and
7512   // the expression is a function call (possibly inside parentheses).
7513   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7514   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7515 
7516   if (Unqualified) {
7517     LHS = LHS.getUnqualifiedType();
7518     RHS = RHS.getUnqualifiedType();
7519   }
7520 
7521   QualType LHSCan = getCanonicalType(LHS),
7522            RHSCan = getCanonicalType(RHS);
7523 
7524   // If two types are identical, they are compatible.
7525   if (LHSCan == RHSCan)
7526     return LHS;
7527 
7528   // If the qualifiers are different, the types aren't compatible... mostly.
7529   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7530   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7531   if (LQuals != RQuals) {
7532     // If any of these qualifiers are different, we have a type
7533     // mismatch.
7534     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7535         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7536         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7537       return QualType();
7538 
7539     // Exactly one GC qualifier difference is allowed: __strong is
7540     // okay if the other type has no GC qualifier but is an Objective
7541     // C object pointer (i.e. implicitly strong by default).  We fix
7542     // this by pretending that the unqualified type was actually
7543     // qualified __strong.
7544     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7545     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7546     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7547 
7548     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7549       return QualType();
7550 
7551     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7552       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7553     }
7554     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7555       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7556     }
7557     return QualType();
7558   }
7559 
7560   // Okay, qualifiers are equal.
7561 
7562   Type::TypeClass LHSClass = LHSCan->getTypeClass();
7563   Type::TypeClass RHSClass = RHSCan->getTypeClass();
7564 
7565   // We want to consider the two function types to be the same for these
7566   // comparisons, just force one to the other.
7567   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7568   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7569 
7570   // Same as above for arrays
7571   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7572     LHSClass = Type::ConstantArray;
7573   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7574     RHSClass = Type::ConstantArray;
7575 
7576   // ObjCInterfaces are just specialized ObjCObjects.
7577   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7578   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7579 
7580   // Canonicalize ExtVector -> Vector.
7581   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7582   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7583 
7584   // If the canonical type classes don't match.
7585   if (LHSClass != RHSClass) {
7586     // Note that we only have special rules for turning block enum
7587     // returns into block int returns, not vice-versa.
7588     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7589       return mergeEnumWithInteger(*this, ETy, RHS, false);
7590     }
7591     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7592       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7593     }
7594     // allow block pointer type to match an 'id' type.
7595     if (OfBlockPointer && !BlockReturnType) {
7596        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7597          return LHS;
7598       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7599         return RHS;
7600     }
7601 
7602     return QualType();
7603   }
7604 
7605   // The canonical type classes match.
7606   switch (LHSClass) {
7607 #define TYPE(Class, Base)
7608 #define ABSTRACT_TYPE(Class, Base)
7609 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7610 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7611 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7612 #include "clang/AST/TypeNodes.def"
7613     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7614 
7615   case Type::Auto:
7616   case Type::LValueReference:
7617   case Type::RValueReference:
7618   case Type::MemberPointer:
7619     llvm_unreachable("C++ should never be in mergeTypes");
7620 
7621   case Type::ObjCInterface:
7622   case Type::IncompleteArray:
7623   case Type::VariableArray:
7624   case Type::FunctionProto:
7625   case Type::ExtVector:
7626     llvm_unreachable("Types are eliminated above");
7627 
7628   case Type::Pointer:
7629   {
7630     // Merge two pointer types, while trying to preserve typedef info
7631     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7632     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7633     if (Unqualified) {
7634       LHSPointee = LHSPointee.getUnqualifiedType();
7635       RHSPointee = RHSPointee.getUnqualifiedType();
7636     }
7637     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7638                                      Unqualified);
7639     if (ResultType.isNull()) return QualType();
7640     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7641       return LHS;
7642     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7643       return RHS;
7644     return getPointerType(ResultType);
7645   }
7646   case Type::BlockPointer:
7647   {
7648     // Merge two block pointer types, while trying to preserve typedef info
7649     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7650     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7651     if (Unqualified) {
7652       LHSPointee = LHSPointee.getUnqualifiedType();
7653       RHSPointee = RHSPointee.getUnqualifiedType();
7654     }
7655     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7656                                      Unqualified);
7657     if (ResultType.isNull()) return QualType();
7658     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7659       return LHS;
7660     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7661       return RHS;
7662     return getBlockPointerType(ResultType);
7663   }
7664   case Type::Atomic:
7665   {
7666     // Merge two pointer types, while trying to preserve typedef info
7667     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7668     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7669     if (Unqualified) {
7670       LHSValue = LHSValue.getUnqualifiedType();
7671       RHSValue = RHSValue.getUnqualifiedType();
7672     }
7673     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7674                                      Unqualified);
7675     if (ResultType.isNull()) return QualType();
7676     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7677       return LHS;
7678     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7679       return RHS;
7680     return getAtomicType(ResultType);
7681   }
7682   case Type::ConstantArray:
7683   {
7684     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7685     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7686     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7687       return QualType();
7688 
7689     QualType LHSElem = getAsArrayType(LHS)->getElementType();
7690     QualType RHSElem = getAsArrayType(RHS)->getElementType();
7691     if (Unqualified) {
7692       LHSElem = LHSElem.getUnqualifiedType();
7693       RHSElem = RHSElem.getUnqualifiedType();
7694     }
7695 
7696     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7697     if (ResultType.isNull()) return QualType();
7698     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7699       return LHS;
7700     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7701       return RHS;
7702     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7703                                           ArrayType::ArraySizeModifier(), 0);
7704     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7705                                           ArrayType::ArraySizeModifier(), 0);
7706     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7707     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7708     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7709       return LHS;
7710     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7711       return RHS;
7712     if (LVAT) {
7713       // FIXME: This isn't correct! But tricky to implement because
7714       // the array's size has to be the size of LHS, but the type
7715       // has to be different.
7716       return LHS;
7717     }
7718     if (RVAT) {
7719       // FIXME: This isn't correct! But tricky to implement because
7720       // the array's size has to be the size of RHS, but the type
7721       // has to be different.
7722       return RHS;
7723     }
7724     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7725     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7726     return getIncompleteArrayType(ResultType,
7727                                   ArrayType::ArraySizeModifier(), 0);
7728   }
7729   case Type::FunctionNoProto:
7730     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7731   case Type::Record:
7732   case Type::Enum:
7733     return QualType();
7734   case Type::Builtin:
7735     // Only exactly equal builtin types are compatible, which is tested above.
7736     return QualType();
7737   case Type::Complex:
7738     // Distinct complex types are incompatible.
7739     return QualType();
7740   case Type::Vector:
7741     // FIXME: The merged type should be an ExtVector!
7742     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7743                              RHSCan->getAs<VectorType>()))
7744       return LHS;
7745     return QualType();
7746   case Type::ObjCObject: {
7747     // Check if the types are assignment compatible.
7748     // FIXME: This should be type compatibility, e.g. whether
7749     // "LHS x; RHS x;" at global scope is legal.
7750     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7751     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7752     if (canAssignObjCInterfaces(LHSIface, RHSIface))
7753       return LHS;
7754 
7755     return QualType();
7756   }
7757   case Type::ObjCObjectPointer: {
7758     if (OfBlockPointer) {
7759       if (canAssignObjCInterfacesInBlockPointer(
7760                                           LHS->getAs<ObjCObjectPointerType>(),
7761                                           RHS->getAs<ObjCObjectPointerType>(),
7762                                           BlockReturnType))
7763         return LHS;
7764       return QualType();
7765     }
7766     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7767                                 RHS->getAs<ObjCObjectPointerType>()))
7768       return LHS;
7769 
7770     return QualType();
7771   }
7772   }
7773 
7774   llvm_unreachable("Invalid Type::Class!");
7775 }
7776 
7777 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7778                    const FunctionProtoType *FromFunctionType,
7779                    const FunctionProtoType *ToFunctionType) {
7780   if (FromFunctionType->hasAnyConsumedParams() !=
7781       ToFunctionType->hasAnyConsumedParams())
7782     return false;
7783   FunctionProtoType::ExtProtoInfo FromEPI =
7784     FromFunctionType->getExtProtoInfo();
7785   FunctionProtoType::ExtProtoInfo ToEPI =
7786     ToFunctionType->getExtProtoInfo();
7787   if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7788     for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7789       if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7790         return false;
7791     }
7792   return true;
7793 }
7794 
7795 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7796 /// 'RHS' attributes and returns the merged version; including for function
7797 /// return types.
7798 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7799   QualType LHSCan = getCanonicalType(LHS),
7800   RHSCan = getCanonicalType(RHS);
7801   // If two types are identical, they are compatible.
7802   if (LHSCan == RHSCan)
7803     return LHS;
7804   if (RHSCan->isFunctionType()) {
7805     if (!LHSCan->isFunctionType())
7806       return QualType();
7807     QualType OldReturnType =
7808         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7809     QualType NewReturnType =
7810         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7811     QualType ResReturnType =
7812       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7813     if (ResReturnType.isNull())
7814       return QualType();
7815     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7816       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7817       // In either case, use OldReturnType to build the new function type.
7818       const FunctionType *F = LHS->getAs<FunctionType>();
7819       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7820         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7821         EPI.ExtInfo = getFunctionExtInfo(LHS);
7822         QualType ResultType =
7823             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7824         return ResultType;
7825       }
7826     }
7827     return QualType();
7828   }
7829 
7830   // If the qualifiers are different, the types can still be merged.
7831   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7832   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7833   if (LQuals != RQuals) {
7834     // If any of these qualifiers are different, we have a type mismatch.
7835     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7836         LQuals.getAddressSpace() != RQuals.getAddressSpace())
7837       return QualType();
7838 
7839     // Exactly one GC qualifier difference is allowed: __strong is
7840     // okay if the other type has no GC qualifier but is an Objective
7841     // C object pointer (i.e. implicitly strong by default).  We fix
7842     // this by pretending that the unqualified type was actually
7843     // qualified __strong.
7844     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7845     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7846     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7847 
7848     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7849       return QualType();
7850 
7851     if (GC_L == Qualifiers::Strong)
7852       return LHS;
7853     if (GC_R == Qualifiers::Strong)
7854       return RHS;
7855     return QualType();
7856   }
7857 
7858   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7859     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7860     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7861     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7862     if (ResQT == LHSBaseQT)
7863       return LHS;
7864     if (ResQT == RHSBaseQT)
7865       return RHS;
7866   }
7867   return QualType();
7868 }
7869 
7870 //===----------------------------------------------------------------------===//
7871 //                         Integer Predicates
7872 //===----------------------------------------------------------------------===//
7873 
7874 unsigned ASTContext::getIntWidth(QualType T) const {
7875   if (const EnumType *ET = T->getAs<EnumType>())
7876     T = ET->getDecl()->getIntegerType();
7877   if (T->isBooleanType())
7878     return 1;
7879   // For builtin types, just use the standard type sizing method
7880   return (unsigned)getTypeSize(T);
7881 }
7882 
7883 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7884   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7885 
7886   // Turn <4 x signed int> -> <4 x unsigned int>
7887   if (const VectorType *VTy = T->getAs<VectorType>())
7888     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7889                          VTy->getNumElements(), VTy->getVectorKind());
7890 
7891   // For enums, we return the unsigned version of the base type.
7892   if (const EnumType *ETy = T->getAs<EnumType>())
7893     T = ETy->getDecl()->getIntegerType();
7894 
7895   const BuiltinType *BTy = T->getAs<BuiltinType>();
7896   assert(BTy && "Unexpected signed integer type");
7897   switch (BTy->getKind()) {
7898   case BuiltinType::Char_S:
7899   case BuiltinType::SChar:
7900     return UnsignedCharTy;
7901   case BuiltinType::Short:
7902     return UnsignedShortTy;
7903   case BuiltinType::Int:
7904     return UnsignedIntTy;
7905   case BuiltinType::Long:
7906     return UnsignedLongTy;
7907   case BuiltinType::LongLong:
7908     return UnsignedLongLongTy;
7909   case BuiltinType::Int128:
7910     return UnsignedInt128Ty;
7911   default:
7912     llvm_unreachable("Unexpected signed integer type");
7913   }
7914 }
7915 
7916 ASTMutationListener::~ASTMutationListener() { }
7917 
7918 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7919                                             QualType ReturnType) {}
7920 
7921 //===----------------------------------------------------------------------===//
7922 //                          Builtin Type Computation
7923 //===----------------------------------------------------------------------===//
7924 
7925 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7926 /// pointer over the consumed characters.  This returns the resultant type.  If
7927 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7928 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
7929 /// a vector of "i*".
7930 ///
7931 /// RequiresICE is filled in on return to indicate whether the value is required
7932 /// to be an Integer Constant Expression.
7933 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7934                                   ASTContext::GetBuiltinTypeError &Error,
7935                                   bool &RequiresICE,
7936                                   bool AllowTypeModifiers) {
7937   // Modifiers.
7938   int HowLong = 0;
7939   bool Signed = false, Unsigned = false;
7940   RequiresICE = false;
7941 
7942   // Read the prefixed modifiers first.
7943   bool Done = false;
7944   while (!Done) {
7945     switch (*Str++) {
7946     default: Done = true; --Str; break;
7947     case 'I':
7948       RequiresICE = true;
7949       break;
7950     case 'S':
7951       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7952       assert(!Signed && "Can't use 'S' modifier multiple times!");
7953       Signed = true;
7954       break;
7955     case 'U':
7956       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7957       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
7958       Unsigned = true;
7959       break;
7960     case 'L':
7961       assert(HowLong <= 2 && "Can't have LLLL modifier");
7962       ++HowLong;
7963       break;
7964     case 'W':
7965       // This modifier represents int64 type.
7966       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7967       switch (Context.getTargetInfo().getInt64Type()) {
7968       default:
7969         llvm_unreachable("Unexpected integer type");
7970       case TargetInfo::SignedLong:
7971         HowLong = 1;
7972         break;
7973       case TargetInfo::SignedLongLong:
7974         HowLong = 2;
7975         break;
7976       }
7977     }
7978   }
7979 
7980   QualType Type;
7981 
7982   // Read the base type.
7983   switch (*Str++) {
7984   default: llvm_unreachable("Unknown builtin type letter!");
7985   case 'v':
7986     assert(HowLong == 0 && !Signed && !Unsigned &&
7987            "Bad modifiers used with 'v'!");
7988     Type = Context.VoidTy;
7989     break;
7990   case 'h':
7991     assert(HowLong == 0 && !Signed && !Unsigned &&
7992            "Bad modifiers used with 'h'!");
7993     Type = Context.HalfTy;
7994     break;
7995   case 'f':
7996     assert(HowLong == 0 && !Signed && !Unsigned &&
7997            "Bad modifiers used with 'f'!");
7998     Type = Context.FloatTy;
7999     break;
8000   case 'd':
8001     assert(HowLong < 2 && !Signed && !Unsigned &&
8002            "Bad modifiers used with 'd'!");
8003     if (HowLong)
8004       Type = Context.LongDoubleTy;
8005     else
8006       Type = Context.DoubleTy;
8007     break;
8008   case 's':
8009     assert(HowLong == 0 && "Bad modifiers used with 's'!");
8010     if (Unsigned)
8011       Type = Context.UnsignedShortTy;
8012     else
8013       Type = Context.ShortTy;
8014     break;
8015   case 'i':
8016     if (HowLong == 3)
8017       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8018     else if (HowLong == 2)
8019       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8020     else if (HowLong == 1)
8021       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8022     else
8023       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8024     break;
8025   case 'c':
8026     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8027     if (Signed)
8028       Type = Context.SignedCharTy;
8029     else if (Unsigned)
8030       Type = Context.UnsignedCharTy;
8031     else
8032       Type = Context.CharTy;
8033     break;
8034   case 'b': // boolean
8035     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8036     Type = Context.BoolTy;
8037     break;
8038   case 'z':  // size_t.
8039     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8040     Type = Context.getSizeType();
8041     break;
8042   case 'F':
8043     Type = Context.getCFConstantStringType();
8044     break;
8045   case 'G':
8046     Type = Context.getObjCIdType();
8047     break;
8048   case 'H':
8049     Type = Context.getObjCSelType();
8050     break;
8051   case 'M':
8052     Type = Context.getObjCSuperType();
8053     break;
8054   case 'a':
8055     Type = Context.getBuiltinVaListType();
8056     assert(!Type.isNull() && "builtin va list type not initialized!");
8057     break;
8058   case 'A':
8059     // This is a "reference" to a va_list; however, what exactly
8060     // this means depends on how va_list is defined. There are two
8061     // different kinds of va_list: ones passed by value, and ones
8062     // passed by reference.  An example of a by-value va_list is
8063     // x86, where va_list is a char*. An example of by-ref va_list
8064     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8065     // we want this argument to be a char*&; for x86-64, we want
8066     // it to be a __va_list_tag*.
8067     Type = Context.getBuiltinVaListType();
8068     assert(!Type.isNull() && "builtin va list type not initialized!");
8069     if (Type->isArrayType())
8070       Type = Context.getArrayDecayedType(Type);
8071     else
8072       Type = Context.getLValueReferenceType(Type);
8073     break;
8074   case 'V': {
8075     char *End;
8076     unsigned NumElements = strtoul(Str, &End, 10);
8077     assert(End != Str && "Missing vector size");
8078     Str = End;
8079 
8080     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8081                                              RequiresICE, false);
8082     assert(!RequiresICE && "Can't require vector ICE");
8083 
8084     // TODO: No way to make AltiVec vectors in builtins yet.
8085     Type = Context.getVectorType(ElementType, NumElements,
8086                                  VectorType::GenericVector);
8087     break;
8088   }
8089   case 'E': {
8090     char *End;
8091 
8092     unsigned NumElements = strtoul(Str, &End, 10);
8093     assert(End != Str && "Missing vector size");
8094 
8095     Str = End;
8096 
8097     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8098                                              false);
8099     Type = Context.getExtVectorType(ElementType, NumElements);
8100     break;
8101   }
8102   case 'X': {
8103     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8104                                              false);
8105     assert(!RequiresICE && "Can't require complex ICE");
8106     Type = Context.getComplexType(ElementType);
8107     break;
8108   }
8109   case 'Y' : {
8110     Type = Context.getPointerDiffType();
8111     break;
8112   }
8113   case 'P':
8114     Type = Context.getFILEType();
8115     if (Type.isNull()) {
8116       Error = ASTContext::GE_Missing_stdio;
8117       return QualType();
8118     }
8119     break;
8120   case 'J':
8121     if (Signed)
8122       Type = Context.getsigjmp_bufType();
8123     else
8124       Type = Context.getjmp_bufType();
8125 
8126     if (Type.isNull()) {
8127       Error = ASTContext::GE_Missing_setjmp;
8128       return QualType();
8129     }
8130     break;
8131   case 'K':
8132     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8133     Type = Context.getucontext_tType();
8134 
8135     if (Type.isNull()) {
8136       Error = ASTContext::GE_Missing_ucontext;
8137       return QualType();
8138     }
8139     break;
8140   case 'p':
8141     Type = Context.getProcessIDType();
8142     break;
8143   }
8144 
8145   // If there are modifiers and if we're allowed to parse them, go for it.
8146   Done = !AllowTypeModifiers;
8147   while (!Done) {
8148     switch (char c = *Str++) {
8149     default: Done = true; --Str; break;
8150     case '*':
8151     case '&': {
8152       // Both pointers and references can have their pointee types
8153       // qualified with an address space.
8154       char *End;
8155       unsigned AddrSpace = strtoul(Str, &End, 10);
8156       if (End != Str && AddrSpace != 0) {
8157         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8158         Str = End;
8159       }
8160       if (c == '*')
8161         Type = Context.getPointerType(Type);
8162       else
8163         Type = Context.getLValueReferenceType(Type);
8164       break;
8165     }
8166     // FIXME: There's no way to have a built-in with an rvalue ref arg.
8167     case 'C':
8168       Type = Type.withConst();
8169       break;
8170     case 'D':
8171       Type = Context.getVolatileType(Type);
8172       break;
8173     case 'R':
8174       Type = Type.withRestrict();
8175       break;
8176     }
8177   }
8178 
8179   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8180          "Integer constant 'I' type must be an integer");
8181 
8182   return Type;
8183 }
8184 
8185 /// GetBuiltinType - Return the type for the specified builtin.
8186 QualType ASTContext::GetBuiltinType(unsigned Id,
8187                                     GetBuiltinTypeError &Error,
8188                                     unsigned *IntegerConstantArgs) const {
8189   const char *TypeStr = BuiltinInfo.getTypeString(Id);
8190 
8191   SmallVector<QualType, 8> ArgTypes;
8192 
8193   bool RequiresICE = false;
8194   Error = GE_None;
8195   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8196                                        RequiresICE, true);
8197   if (Error != GE_None)
8198     return QualType();
8199 
8200   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8201 
8202   while (TypeStr[0] && TypeStr[0] != '.') {
8203     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8204     if (Error != GE_None)
8205       return QualType();
8206 
8207     // If this argument is required to be an IntegerConstantExpression and the
8208     // caller cares, fill in the bitmask we return.
8209     if (RequiresICE && IntegerConstantArgs)
8210       *IntegerConstantArgs |= 1 << ArgTypes.size();
8211 
8212     // Do array -> pointer decay.  The builtin should use the decayed type.
8213     if (Ty->isArrayType())
8214       Ty = getArrayDecayedType(Ty);
8215 
8216     ArgTypes.push_back(Ty);
8217   }
8218 
8219   if (Id == Builtin::BI__GetExceptionInfo)
8220     return QualType();
8221 
8222   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8223          "'.' should only occur at end of builtin type list!");
8224 
8225   FunctionType::ExtInfo EI(CC_C);
8226   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8227 
8228   bool Variadic = (TypeStr[0] == '.');
8229 
8230   // We really shouldn't be making a no-proto type here, especially in C++.
8231   if (ArgTypes.empty() && Variadic)
8232     return getFunctionNoProtoType(ResType, EI);
8233 
8234   FunctionProtoType::ExtProtoInfo EPI;
8235   EPI.ExtInfo = EI;
8236   EPI.Variadic = Variadic;
8237 
8238   return getFunctionType(ResType, ArgTypes, EPI);
8239 }
8240 
8241 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8242                                              const FunctionDecl *FD) {
8243   if (!FD->isExternallyVisible())
8244     return GVA_Internal;
8245 
8246   GVALinkage External = GVA_StrongExternal;
8247   switch (FD->getTemplateSpecializationKind()) {
8248   case TSK_Undeclared:
8249   case TSK_ExplicitSpecialization:
8250     External = GVA_StrongExternal;
8251     break;
8252 
8253   case TSK_ExplicitInstantiationDefinition:
8254     return GVA_StrongODR;
8255 
8256   // C++11 [temp.explicit]p10:
8257   //   [ Note: The intent is that an inline function that is the subject of
8258   //   an explicit instantiation declaration will still be implicitly
8259   //   instantiated when used so that the body can be considered for
8260   //   inlining, but that no out-of-line copy of the inline function would be
8261   //   generated in the translation unit. -- end note ]
8262   case TSK_ExplicitInstantiationDeclaration:
8263     return GVA_AvailableExternally;
8264 
8265   case TSK_ImplicitInstantiation:
8266     External = GVA_DiscardableODR;
8267     break;
8268   }
8269 
8270   if (!FD->isInlined())
8271     return External;
8272 
8273   if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8274        !FD->hasAttr<DLLExportAttr>()) ||
8275       FD->hasAttr<GNUInlineAttr>()) {
8276     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8277 
8278     // GNU or C99 inline semantics. Determine whether this symbol should be
8279     // externally visible.
8280     if (FD->isInlineDefinitionExternallyVisible())
8281       return External;
8282 
8283     // C99 inline semantics, where the symbol is not externally visible.
8284     return GVA_AvailableExternally;
8285   }
8286 
8287   // Functions specified with extern and inline in -fms-compatibility mode
8288   // forcibly get emitted.  While the body of the function cannot be later
8289   // replaced, the function definition cannot be discarded.
8290   if (FD->isMSExternInline())
8291     return GVA_StrongODR;
8292 
8293   return GVA_DiscardableODR;
8294 }
8295 
8296 static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
8297   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8298   // dllexport/dllimport on inline functions.
8299   if (D->hasAttr<DLLImportAttr>()) {
8300     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8301       return GVA_AvailableExternally;
8302   } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
8303     if (L == GVA_DiscardableODR)
8304       return GVA_StrongODR;
8305   }
8306   return L;
8307 }
8308 
8309 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8310   return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8311                                        FD);
8312 }
8313 
8314 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8315                                              const VarDecl *VD) {
8316   if (!VD->isExternallyVisible())
8317     return GVA_Internal;
8318 
8319   if (VD->isStaticLocal()) {
8320     GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8321     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8322     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8323       LexicalContext = LexicalContext->getLexicalParent();
8324 
8325     // Let the static local variable inherit its linkage from the nearest
8326     // enclosing function.
8327     if (LexicalContext)
8328       StaticLocalLinkage =
8329           Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8330 
8331     // GVA_StrongODR function linkage is stronger than what we need,
8332     // downgrade to GVA_DiscardableODR.
8333     // This allows us to discard the variable if we never end up needing it.
8334     return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8335                                                : StaticLocalLinkage;
8336   }
8337 
8338   // MSVC treats in-class initialized static data members as definitions.
8339   // By giving them non-strong linkage, out-of-line definitions won't
8340   // cause link errors.
8341   if (Context.isMSStaticDataMemberInlineDefinition(VD))
8342     return GVA_DiscardableODR;
8343 
8344   switch (VD->getTemplateSpecializationKind()) {
8345   case TSK_Undeclared:
8346     return GVA_StrongExternal;
8347 
8348   case TSK_ExplicitSpecialization:
8349     return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8350                ? GVA_StrongODR
8351                : GVA_StrongExternal;
8352 
8353   case TSK_ExplicitInstantiationDefinition:
8354     return GVA_StrongODR;
8355 
8356   case TSK_ExplicitInstantiationDeclaration:
8357     return GVA_AvailableExternally;
8358 
8359   case TSK_ImplicitInstantiation:
8360     return GVA_DiscardableODR;
8361   }
8362 
8363   llvm_unreachable("Invalid Linkage!");
8364 }
8365 
8366 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8367   return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8368                                        VD);
8369 }
8370 
8371 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8372   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8373     if (!VD->isFileVarDecl())
8374       return false;
8375     // Global named register variables (GNU extension) are never emitted.
8376     if (VD->getStorageClass() == SC_Register)
8377       return false;
8378     if (VD->getDescribedVarTemplate() ||
8379         isa<VarTemplatePartialSpecializationDecl>(VD))
8380       return false;
8381   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8382     // We never need to emit an uninstantiated function template.
8383     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8384       return false;
8385   } else if (isa<OMPThreadPrivateDecl>(D))
8386     return true;
8387   else
8388     return false;
8389 
8390   // If this is a member of a class template, we do not need to emit it.
8391   if (D->getDeclContext()->isDependentContext())
8392     return false;
8393 
8394   // Weak references don't produce any output by themselves.
8395   if (D->hasAttr<WeakRefAttr>())
8396     return false;
8397 
8398   // Aliases and used decls are required.
8399   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8400     return true;
8401 
8402   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8403     // Forward declarations aren't required.
8404     if (!FD->doesThisDeclarationHaveABody())
8405       return FD->doesDeclarationForceExternallyVisibleDefinition();
8406 
8407     // Constructors and destructors are required.
8408     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8409       return true;
8410 
8411     // The key function for a class is required.  This rule only comes
8412     // into play when inline functions can be key functions, though.
8413     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8414       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8415         const CXXRecordDecl *RD = MD->getParent();
8416         if (MD->isOutOfLine() && RD->isDynamicClass()) {
8417           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8418           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8419             return true;
8420         }
8421       }
8422     }
8423 
8424     GVALinkage Linkage = GetGVALinkageForFunction(FD);
8425 
8426     // static, static inline, always_inline, and extern inline functions can
8427     // always be deferred.  Normal inline functions can be deferred in C99/C++.
8428     // Implicit template instantiations can also be deferred in C++.
8429     if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8430         Linkage == GVA_DiscardableODR)
8431       return false;
8432     return true;
8433   }
8434 
8435   const VarDecl *VD = cast<VarDecl>(D);
8436   assert(VD->isFileVarDecl() && "Expected file scoped var");
8437 
8438   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8439       !isMSStaticDataMemberInlineDefinition(VD))
8440     return false;
8441 
8442   // Variables that can be needed in other TUs are required.
8443   GVALinkage L = GetGVALinkageForVariable(VD);
8444   if (L != GVA_Internal && L != GVA_AvailableExternally &&
8445       L != GVA_DiscardableODR)
8446     return true;
8447 
8448   // Variables that have destruction with side-effects are required.
8449   if (VD->getType().isDestructedType())
8450     return true;
8451 
8452   // Variables that have initialization with side-effects are required.
8453   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8454       !VD->evaluateValue())
8455     return true;
8456 
8457   return false;
8458 }
8459 
8460 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8461                                                     bool IsCXXMethod) const {
8462   // Pass through to the C++ ABI object
8463   if (IsCXXMethod)
8464     return ABI->getDefaultMethodCallConv(IsVariadic);
8465 
8466   if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8467 
8468   return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8469 }
8470 
8471 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8472   // Pass through to the C++ ABI object
8473   return ABI->isNearlyEmpty(RD);
8474 }
8475 
8476 VTableContextBase *ASTContext::getVTableContext() {
8477   if (!VTContext.get()) {
8478     if (Target->getCXXABI().isMicrosoft())
8479       VTContext.reset(new MicrosoftVTableContext(*this));
8480     else
8481       VTContext.reset(new ItaniumVTableContext(*this));
8482   }
8483   return VTContext.get();
8484 }
8485 
8486 MangleContext *ASTContext::createMangleContext() {
8487   switch (Target->getCXXABI().getKind()) {
8488   case TargetCXXABI::GenericAArch64:
8489   case TargetCXXABI::GenericItanium:
8490   case TargetCXXABI::GenericARM:
8491   case TargetCXXABI::GenericMIPS:
8492   case TargetCXXABI::iOS:
8493   case TargetCXXABI::iOS64:
8494   case TargetCXXABI::WebAssembly:
8495     return ItaniumMangleContext::create(*this, getDiagnostics());
8496   case TargetCXXABI::Microsoft:
8497     return MicrosoftMangleContext::create(*this, getDiagnostics());
8498   }
8499   llvm_unreachable("Unsupported ABI");
8500 }
8501 
8502 CXXABI::~CXXABI() {}
8503 
8504 size_t ASTContext::getSideTableAllocatedMemory() const {
8505   return ASTRecordLayouts.getMemorySize() +
8506          llvm::capacity_in_bytes(ObjCLayouts) +
8507          llvm::capacity_in_bytes(KeyFunctions) +
8508          llvm::capacity_in_bytes(ObjCImpls) +
8509          llvm::capacity_in_bytes(BlockVarCopyInits) +
8510          llvm::capacity_in_bytes(DeclAttrs) +
8511          llvm::capacity_in_bytes(TemplateOrInstantiation) +
8512          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8513          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8514          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8515          llvm::capacity_in_bytes(OverriddenMethods) +
8516          llvm::capacity_in_bytes(Types) +
8517          llvm::capacity_in_bytes(VariableArrayTypes) +
8518          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8519 }
8520 
8521 /// getIntTypeForBitwidth -
8522 /// sets integer QualTy according to specified details:
8523 /// bitwidth, signed/unsigned.
8524 /// Returns empty type if there is no appropriate target types.
8525 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8526                                            unsigned Signed) const {
8527   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8528   CanQualType QualTy = getFromTargetType(Ty);
8529   if (!QualTy && DestWidth == 128)
8530     return Signed ? Int128Ty : UnsignedInt128Ty;
8531   return QualTy;
8532 }
8533 
8534 /// getRealTypeForBitwidth -
8535 /// sets floating point QualTy according to specified bitwidth.
8536 /// Returns empty type if there is no appropriate target types.
8537 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8538   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8539   switch (Ty) {
8540   case TargetInfo::Float:
8541     return FloatTy;
8542   case TargetInfo::Double:
8543     return DoubleTy;
8544   case TargetInfo::LongDouble:
8545     return LongDoubleTy;
8546   case TargetInfo::NoFloat:
8547     return QualType();
8548   }
8549 
8550   llvm_unreachable("Unhandled TargetInfo::RealType value");
8551 }
8552 
8553 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8554   if (Number > 1)
8555     MangleNumbers[ND] = Number;
8556 }
8557 
8558 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8559   llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8560     MangleNumbers.find(ND);
8561   return I != MangleNumbers.end() ? I->second : 1;
8562 }
8563 
8564 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8565   if (Number > 1)
8566     StaticLocalNumbers[VD] = Number;
8567 }
8568 
8569 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8570   llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8571       StaticLocalNumbers.find(VD);
8572   return I != StaticLocalNumbers.end() ? I->second : 1;
8573 }
8574 
8575 MangleNumberingContext &
8576 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8577   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
8578   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8579   if (!MCtx)
8580     MCtx = createMangleNumberingContext();
8581   return *MCtx;
8582 }
8583 
8584 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8585   return ABI->createMangleNumberingContext();
8586 }
8587 
8588 const CXXConstructorDecl *
8589 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8590   return ABI->getCopyConstructorForExceptionObject(
8591       cast<CXXRecordDecl>(RD->getFirstDecl()));
8592 }
8593 
8594 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8595                                                       CXXConstructorDecl *CD) {
8596   return ABI->addCopyConstructorForExceptionObject(
8597       cast<CXXRecordDecl>(RD->getFirstDecl()),
8598       cast<CXXConstructorDecl>(CD->getFirstDecl()));
8599 }
8600 
8601 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8602                                                  unsigned ParmIdx, Expr *DAE) {
8603   ABI->addDefaultArgExprForConstructor(
8604       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8605 }
8606 
8607 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8608                                                   unsigned ParmIdx) {
8609   return ABI->getDefaultArgExprForConstructor(
8610       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8611 }
8612 
8613 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8614                                                  TypedefNameDecl *DD) {
8615   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8616 }
8617 
8618 TypedefNameDecl *
8619 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8620   return ABI->getTypedefNameForUnnamedTagDecl(TD);
8621 }
8622 
8623 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8624                                                 DeclaratorDecl *DD) {
8625   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8626 }
8627 
8628 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8629   return ABI->getDeclaratorForUnnamedTagDecl(TD);
8630 }
8631 
8632 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8633   ParamIndices[D] = index;
8634 }
8635 
8636 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8637   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8638   assert(I != ParamIndices.end() &&
8639          "ParmIndices lacks entry set by ParmVarDecl");
8640   return I->second;
8641 }
8642 
8643 APValue *
8644 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8645                                           bool MayCreate) {
8646   assert(E && E->getStorageDuration() == SD_Static &&
8647          "don't need to cache the computed value for this temporary");
8648   if (MayCreate) {
8649     APValue *&MTVI = MaterializedTemporaryValues[E];
8650     if (!MTVI)
8651       MTVI = new (*this) APValue;
8652     return MTVI;
8653   }
8654 
8655   return MaterializedTemporaryValues.lookup(E);
8656 }
8657 
8658 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8659   const llvm::Triple &T = getTargetInfo().getTriple();
8660   if (!T.isOSDarwin())
8661     return false;
8662 
8663   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8664       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8665     return false;
8666 
8667   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8668   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8669   uint64_t Size = sizeChars.getQuantity();
8670   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8671   unsigned Align = alignChars.getQuantity();
8672   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8673   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8674 }
8675 
8676 namespace {
8677 
8678   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8679   /// parents as defined by the \c RecursiveASTVisitor.
8680   ///
8681   /// Note that the relationship described here is purely in terms of AST
8682   /// traversal - there are other relationships (for example declaration context)
8683   /// in the AST that are better modeled by special matchers.
8684   ///
8685   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8686   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8687 
8688   public:
8689     /// \brief Builds and returns the translation unit's parent map.
8690     ///
8691     ///  The caller takes ownership of the returned \c ParentMap.
8692     static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8693       ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8694       Visitor.TraverseDecl(&TU);
8695       return Visitor.Parents;
8696     }
8697 
8698   private:
8699     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8700 
8701     ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8702     }
8703 
8704     bool shouldVisitTemplateInstantiations() const {
8705       return true;
8706     }
8707     bool shouldVisitImplicitCode() const {
8708       return true;
8709     }
8710     // Disables data recursion. We intercept Traverse* methods in the RAV, which
8711     // are not triggered during data recursion.
8712     bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8713       return false;
8714     }
8715 
8716     template <typename T>
8717     bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8718       if (!Node)
8719         return true;
8720       if (ParentStack.size() > 0) {
8721         // FIXME: Currently we add the same parent multiple times, but only
8722         // when no memoization data is available for the type.
8723         // For example when we visit all subexpressions of template
8724         // instantiations; this is suboptimal, but benign: the only way to
8725         // visit those is with hasAncestor / hasParent, and those do not create
8726         // new matches.
8727         // The plan is to enable DynTypedNode to be storable in a map or hash
8728         // map. The main problem there is to implement hash functions /
8729         // comparison operators for all types that DynTypedNode supports that
8730         // do not have pointer identity.
8731         auto &NodeOrVector = (*Parents)[Node];
8732         if (NodeOrVector.isNull()) {
8733           NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8734         } else {
8735           if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8736             auto *Node =
8737                 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8738             auto *Vector = new ASTContext::ParentVector(1, *Node);
8739             NodeOrVector = Vector;
8740             delete Node;
8741           }
8742           assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8743 
8744           auto *Vector =
8745               NodeOrVector.template get<ASTContext::ParentVector *>();
8746           // Skip duplicates for types that have memoization data.
8747           // We must check that the type has memoization data before calling
8748           // std::find() because DynTypedNode::operator== can't compare all
8749           // types.
8750           bool Found = ParentStack.back().getMemoizationData() &&
8751                        std::find(Vector->begin(), Vector->end(),
8752                                  ParentStack.back()) != Vector->end();
8753           if (!Found)
8754             Vector->push_back(ParentStack.back());
8755         }
8756       }
8757       ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8758       bool Result = (this ->* traverse) (Node);
8759       ParentStack.pop_back();
8760       return Result;
8761     }
8762 
8763     bool TraverseDecl(Decl *DeclNode) {
8764       return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8765     }
8766 
8767     bool TraverseStmt(Stmt *StmtNode) {
8768       return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8769     }
8770 
8771     ASTContext::ParentMap *Parents;
8772     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8773 
8774     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8775   };
8776 
8777 } // end namespace
8778 
8779 ArrayRef<ast_type_traits::DynTypedNode>
8780 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8781   assert(Node.getMemoizationData() &&
8782          "Invariant broken: only nodes that support memoization may be "
8783          "used in the parent map.");
8784   if (!AllParents) {
8785     // We always need to run over the whole translation unit, as
8786     // hasAncestor can escape any subtree.
8787     AllParents.reset(
8788         ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8789   }
8790   ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8791   if (I == AllParents->end()) {
8792     return None;
8793   }
8794   if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8795     return llvm::makeArrayRef(N, 1);
8796   }
8797   return *I->second.get<ParentVector *>();
8798 }
8799 
8800 bool
8801 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8802                                 const ObjCMethodDecl *MethodImpl) {
8803   // No point trying to match an unavailable/deprecated mothod.
8804   if (MethodDecl->hasAttr<UnavailableAttr>()
8805       || MethodDecl->hasAttr<DeprecatedAttr>())
8806     return false;
8807   if (MethodDecl->getObjCDeclQualifier() !=
8808       MethodImpl->getObjCDeclQualifier())
8809     return false;
8810   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8811     return false;
8812 
8813   if (MethodDecl->param_size() != MethodImpl->param_size())
8814     return false;
8815 
8816   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8817        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8818        EF = MethodDecl->param_end();
8819        IM != EM && IF != EF; ++IM, ++IF) {
8820     const ParmVarDecl *DeclVar = (*IF);
8821     const ParmVarDecl *ImplVar = (*IM);
8822     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8823       return false;
8824     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8825       return false;
8826   }
8827   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8828 
8829 }
8830 
8831 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8832 // doesn't include ASTContext.h
8833 template
8834 clang::LazyGenerationalUpdatePtr<
8835     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8836 clang::LazyGenerationalUpdatePtr<
8837     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8838         const clang::ASTContext &Ctx, Decl *Value);
8839