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