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