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