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