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