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