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