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