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