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