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