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