1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the ASTContext interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "CXXABI.h"
15 #include "Interp/Context.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Comment.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclContextInternals.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/DeclarationName.h"
32 #include "clang/AST/DependenceFlags.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/ExprConcepts.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/IdentifierTable.h"
55 #include "clang/Basic/LLVM.h"
56 #include "clang/Basic/LangOptions.h"
57 #include "clang/Basic/Linkage.h"
58 #include "clang/Basic/Module.h"
59 #include "clang/Basic/NoSanitizeList.h"
60 #include "clang/Basic/ObjCRuntime.h"
61 #include "clang/Basic/SourceLocation.h"
62 #include "clang/Basic/SourceManager.h"
63 #include "clang/Basic/Specifiers.h"
64 #include "clang/Basic/TargetCXXABI.h"
65 #include "clang/Basic/TargetInfo.h"
66 #include "clang/Basic/XRayLists.h"
67 #include "llvm/ADT/APFixedPoint.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/ArrayRef.h"
71 #include "llvm/ADT/DenseMap.h"
72 #include "llvm/ADT/DenseSet.h"
73 #include "llvm/ADT/FoldingSet.h"
74 #include "llvm/ADT/None.h"
75 #include "llvm/ADT/Optional.h"
76 #include "llvm/ADT/PointerUnion.h"
77 #include "llvm/ADT/STLExtras.h"
78 #include "llvm/ADT/SmallPtrSet.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringExtras.h"
81 #include "llvm/ADT/StringRef.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/Support/Capacity.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/MD5.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstdint>
94 #include <cstdlib>
95 #include <map>
96 #include <memory>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 
103 enum FloatingRank {
104   BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
105 };
106 
107 /// \returns location that is relevant when searching for Doc comments related
108 /// to \p D.
109 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
110                                                  SourceManager &SourceMgr) {
111   assert(D);
112 
113   // User can not attach documentation to implicit declarations.
114   if (D->isImplicit())
115     return {};
116 
117   // User can not attach documentation to implicit instantiations.
118   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
119     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
120       return {};
121   }
122 
123   if (const auto *VD = dyn_cast<VarDecl>(D)) {
124     if (VD->isStaticDataMember() &&
125         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
126       return {};
127   }
128 
129   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
130     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131       return {};
132   }
133 
134   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
135     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
136     if (TSK == TSK_ImplicitInstantiation ||
137         TSK == TSK_Undeclared)
138       return {};
139   }
140 
141   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
142     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
143       return {};
144   }
145   if (const auto *TD = dyn_cast<TagDecl>(D)) {
146     // When tag declaration (but not definition!) is part of the
147     // decl-specifier-seq of some other declaration, it doesn't get comment
148     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
149       return {};
150   }
151   // TODO: handle comments for function parameters properly.
152   if (isa<ParmVarDecl>(D))
153     return {};
154 
155   // TODO: we could look up template parameter documentation in the template
156   // documentation.
157   if (isa<TemplateTypeParmDecl>(D) ||
158       isa<NonTypeTemplateParmDecl>(D) ||
159       isa<TemplateTemplateParmDecl>(D))
160     return {};
161 
162   // Find declaration location.
163   // For Objective-C declarations we generally don't expect to have multiple
164   // declarators, thus use declaration starting location as the "declaration
165   // location".
166   // For all other declarations multiple declarators are used quite frequently,
167   // so we use the location of the identifier as the "declaration location".
168   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
169       isa<ObjCPropertyDecl>(D) ||
170       isa<RedeclarableTemplateDecl>(D) ||
171       isa<ClassTemplateSpecializationDecl>(D) ||
172       // Allow association with Y across {} in `typedef struct X {} Y`.
173       isa<TypedefDecl>(D))
174     return D->getBeginLoc();
175   else {
176     const SourceLocation DeclLoc = D->getLocation();
177     if (DeclLoc.isMacroID()) {
178       if (isa<TypedefDecl>(D)) {
179         // If location of the typedef name is in a macro, it is because being
180         // declared via a macro. Try using declaration's starting location as
181         // the "declaration location".
182         return D->getBeginLoc();
183       } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
184         // If location of the tag decl is inside a macro, but the spelling of
185         // the tag name comes from a macro argument, it looks like a special
186         // macro like NS_ENUM is being used to define the tag decl.  In that
187         // case, adjust the source location to the expansion loc so that we can
188         // attach the comment to the tag decl.
189         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
190             TD->isCompleteDefinition())
191           return SourceMgr.getExpansionLoc(DeclLoc);
192       }
193     }
194     return DeclLoc;
195   }
196 
197   return {};
198 }
199 
200 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
201     const Decl *D, const SourceLocation RepresentativeLocForDecl,
202     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
203   // If the declaration doesn't map directly to a location in a file, we
204   // can't find the comment.
205   if (RepresentativeLocForDecl.isInvalid() ||
206       !RepresentativeLocForDecl.isFileID())
207     return nullptr;
208 
209   // If there are no comments anywhere, we won't find anything.
210   if (CommentsInTheFile.empty())
211     return nullptr;
212 
213   // Decompose the location for the declaration and find the beginning of the
214   // file buffer.
215   const std::pair<FileID, unsigned> DeclLocDecomp =
216       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
217 
218   // Slow path.
219   auto OffsetCommentBehindDecl =
220       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
221 
222   // First check whether we have a trailing comment.
223   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
224     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
225     if ((CommentBehindDecl->isDocumentation() ||
226          LangOpts.CommentOpts.ParseAllComments) &&
227         CommentBehindDecl->isTrailingComment() &&
228         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
229          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
230 
231       // Check that Doxygen trailing comment comes after the declaration, starts
232       // on the same line and in the same file as the declaration.
233       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
234           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
235                                        OffsetCommentBehindDecl->first)) {
236         return CommentBehindDecl;
237       }
238     }
239   }
240 
241   // The comment just after the declaration was not a trailing comment.
242   // Let's look at the previous comment.
243   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
244     return nullptr;
245 
246   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
247   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
248 
249   // Check that we actually have a non-member Doxygen comment.
250   if (!(CommentBeforeDecl->isDocumentation() ||
251         LangOpts.CommentOpts.ParseAllComments) ||
252       CommentBeforeDecl->isTrailingComment())
253     return nullptr;
254 
255   // Decompose the end of the comment.
256   const unsigned CommentEndOffset =
257       Comments.getCommentEndOffset(CommentBeforeDecl);
258 
259   // Get the corresponding buffer.
260   bool Invalid = false;
261   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
262                                                &Invalid).data();
263   if (Invalid)
264     return nullptr;
265 
266   // Extract text between the comment and declaration.
267   StringRef Text(Buffer + CommentEndOffset,
268                  DeclLocDecomp.second - CommentEndOffset);
269 
270   // There should be no other declarations or preprocessor directives between
271   // comment and declaration.
272   if (Text.find_first_of(";{}#@") != StringRef::npos)
273     return nullptr;
274 
275   return CommentBeforeDecl;
276 }
277 
278 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
279   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
280 
281   // If the declaration doesn't map directly to a location in a file, we
282   // can't find the comment.
283   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
284     return nullptr;
285 
286   if (ExternalSource && !CommentsLoaded) {
287     ExternalSource->ReadComments();
288     CommentsLoaded = true;
289   }
290 
291   if (Comments.empty())
292     return nullptr;
293 
294   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
295   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
296   if (!CommentsInThisFile || CommentsInThisFile->empty())
297     return nullptr;
298 
299   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
300 }
301 
302 void ASTContext::addComment(const RawComment &RC) {
303   assert(LangOpts.RetainCommentsFromSystemHeaders ||
304          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
305   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
306 }
307 
308 /// If we have a 'templated' declaration for a template, adjust 'D' to
309 /// refer to the actual template.
310 /// If we have an implicit instantiation, adjust 'D' to refer to template.
311 static const Decl &adjustDeclToTemplate(const Decl &D) {
312   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
313     // Is this function declaration part of a function template?
314     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
315       return *FTD;
316 
317     // Nothing to do if function is not an implicit instantiation.
318     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
319       return D;
320 
321     // Function is an implicit instantiation of a function template?
322     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
323       return *FTD;
324 
325     // Function is instantiated from a member definition of a class template?
326     if (const FunctionDecl *MemberDecl =
327             FD->getInstantiatedFromMemberFunction())
328       return *MemberDecl;
329 
330     return D;
331   }
332   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
333     // Static data member is instantiated from a member definition of a class
334     // template?
335     if (VD->isStaticDataMember())
336       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
337         return *MemberDecl;
338 
339     return D;
340   }
341   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
342     // Is this class declaration part of a class template?
343     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
344       return *CTD;
345 
346     // Class is an implicit instantiation of a class template or partial
347     // specialization?
348     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
349       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
350         return D;
351       llvm::PointerUnion<ClassTemplateDecl *,
352                          ClassTemplatePartialSpecializationDecl *>
353           PU = CTSD->getSpecializedTemplateOrPartial();
354       return PU.is<ClassTemplateDecl *>()
355                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
356                  : *static_cast<const Decl *>(
357                        PU.get<ClassTemplatePartialSpecializationDecl *>());
358     }
359 
360     // Class is instantiated from a member definition of a class template?
361     if (const MemberSpecializationInfo *Info =
362             CRD->getMemberSpecializationInfo())
363       return *Info->getInstantiatedFrom();
364 
365     return D;
366   }
367   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
368     // Enum is instantiated from a member definition of a class template?
369     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
370       return *MemberDecl;
371 
372     return D;
373   }
374   // FIXME: Adjust alias templates?
375   return D;
376 }
377 
378 const RawComment *ASTContext::getRawCommentForAnyRedecl(
379                                                 const Decl *D,
380                                                 const Decl **OriginalDecl) const {
381   if (!D) {
382     if (OriginalDecl)
383       OriginalDecl = nullptr;
384     return nullptr;
385   }
386 
387   D = &adjustDeclToTemplate(*D);
388 
389   // Any comment directly attached to D?
390   {
391     auto DeclComment = DeclRawComments.find(D);
392     if (DeclComment != DeclRawComments.end()) {
393       if (OriginalDecl)
394         *OriginalDecl = D;
395       return DeclComment->second;
396     }
397   }
398 
399   // Any comment attached to any redeclaration of D?
400   const Decl *CanonicalD = D->getCanonicalDecl();
401   if (!CanonicalD)
402     return nullptr;
403 
404   {
405     auto RedeclComment = RedeclChainComments.find(CanonicalD);
406     if (RedeclComment != RedeclChainComments.end()) {
407       if (OriginalDecl)
408         *OriginalDecl = RedeclComment->second;
409       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
410       assert(CommentAtRedecl != DeclRawComments.end() &&
411              "This decl is supposed to have comment attached.");
412       return CommentAtRedecl->second;
413     }
414   }
415 
416   // Any redeclarations of D that we haven't checked for comments yet?
417   // We can't use DenseMap::iterator directly since it'd get invalid.
418   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
419     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
420     if (LookupRes != CommentlessRedeclChains.end())
421       return LookupRes->second;
422     return nullptr;
423   }();
424 
425   for (const auto Redecl : D->redecls()) {
426     assert(Redecl);
427     // Skip all redeclarations that have been checked previously.
428     if (LastCheckedRedecl) {
429       if (LastCheckedRedecl == Redecl) {
430         LastCheckedRedecl = nullptr;
431       }
432       continue;
433     }
434     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
435     if (RedeclComment) {
436       cacheRawCommentForDecl(*Redecl, *RedeclComment);
437       if (OriginalDecl)
438         *OriginalDecl = Redecl;
439       return RedeclComment;
440     }
441     CommentlessRedeclChains[CanonicalD] = Redecl;
442   }
443 
444   if (OriginalDecl)
445     *OriginalDecl = nullptr;
446   return nullptr;
447 }
448 
449 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
450                                         const RawComment &Comment) const {
451   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
452   DeclRawComments.try_emplace(&OriginalD, &Comment);
453   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
454   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
455   CommentlessRedeclChains.erase(CanonicalDecl);
456 }
457 
458 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
459                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
460   const DeclContext *DC = ObjCMethod->getDeclContext();
461   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
462     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
463     if (!ID)
464       return;
465     // Add redeclared method here.
466     for (const auto *Ext : ID->known_extensions()) {
467       if (ObjCMethodDecl *RedeclaredMethod =
468             Ext->getMethod(ObjCMethod->getSelector(),
469                                   ObjCMethod->isInstanceMethod()))
470         Redeclared.push_back(RedeclaredMethod);
471     }
472   }
473 }
474 
475 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
476                                                  const Preprocessor *PP) {
477   if (Comments.empty() || Decls.empty())
478     return;
479 
480   FileID File;
481   for (Decl *D : Decls) {
482     SourceLocation Loc = D->getLocation();
483     if (Loc.isValid()) {
484       // See if there are any new comments that are not attached to a decl.
485       // The location doesn't have to be precise - we care only about the file.
486       File = SourceMgr.getDecomposedLoc(Loc).first;
487       break;
488     }
489   }
490 
491   if (File.isInvalid())
492     return;
493 
494   auto CommentsInThisFile = Comments.getCommentsInFile(File);
495   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
496       CommentsInThisFile->rbegin()->second->isAttached())
497     return;
498 
499   // There is at least one comment not attached to a decl.
500   // Maybe it should be attached to one of Decls?
501   //
502   // Note that this way we pick up not only comments that precede the
503   // declaration, but also comments that *follow* the declaration -- thanks to
504   // the lookahead in the lexer: we've consumed the semicolon and looked
505   // ahead through comments.
506 
507   for (const Decl *D : Decls) {
508     assert(D);
509     if (D->isInvalidDecl())
510       continue;
511 
512     D = &adjustDeclToTemplate(*D);
513 
514     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
515 
516     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
517       continue;
518 
519     if (DeclRawComments.count(D) > 0)
520       continue;
521 
522     if (RawComment *const DocComment =
523             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
524       cacheRawCommentForDecl(*D, *DocComment);
525       comments::FullComment *FC = DocComment->parse(*this, PP, D);
526       ParsedComments[D->getCanonicalDecl()] = FC;
527     }
528   }
529 }
530 
531 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
532                                                     const Decl *D) const {
533   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
534   ThisDeclInfo->CommentDecl = D;
535   ThisDeclInfo->IsFilled = false;
536   ThisDeclInfo->fill();
537   ThisDeclInfo->CommentDecl = FC->getDecl();
538   if (!ThisDeclInfo->TemplateParameters)
539     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
540   comments::FullComment *CFC =
541     new (*this) comments::FullComment(FC->getBlocks(),
542                                       ThisDeclInfo);
543   return CFC;
544 }
545 
546 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
547   const RawComment *RC = getRawCommentForDeclNoCache(D);
548   return RC ? RC->parse(*this, nullptr, D) : nullptr;
549 }
550 
551 comments::FullComment *ASTContext::getCommentForDecl(
552                                               const Decl *D,
553                                               const Preprocessor *PP) const {
554   if (!D || D->isInvalidDecl())
555     return nullptr;
556   D = &adjustDeclToTemplate(*D);
557 
558   const Decl *Canonical = D->getCanonicalDecl();
559   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
560       ParsedComments.find(Canonical);
561 
562   if (Pos != ParsedComments.end()) {
563     if (Canonical != D) {
564       comments::FullComment *FC = Pos->second;
565       comments::FullComment *CFC = cloneFullComment(FC, D);
566       return CFC;
567     }
568     return Pos->second;
569   }
570 
571   const Decl *OriginalDecl = nullptr;
572 
573   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
574   if (!RC) {
575     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
576       SmallVector<const NamedDecl*, 8> Overridden;
577       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
578       if (OMD && OMD->isPropertyAccessor())
579         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
580           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
581             return cloneFullComment(FC, D);
582       if (OMD)
583         addRedeclaredMethods(OMD, Overridden);
584       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
585       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
586         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
587           return cloneFullComment(FC, D);
588     }
589     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
590       // Attach any tag type's documentation to its typedef if latter
591       // does not have one of its own.
592       QualType QT = TD->getUnderlyingType();
593       if (const auto *TT = QT->getAs<TagType>())
594         if (const Decl *TD = TT->getDecl())
595           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
596             return cloneFullComment(FC, D);
597     }
598     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
599       while (IC->getSuperClass()) {
600         IC = IC->getSuperClass();
601         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
602           return cloneFullComment(FC, D);
603       }
604     }
605     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
606       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
607         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608           return cloneFullComment(FC, D);
609     }
610     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
611       if (!(RD = RD->getDefinition()))
612         return nullptr;
613       // Check non-virtual bases.
614       for (const auto &I : RD->bases()) {
615         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
616           continue;
617         QualType Ty = I.getType();
618         if (Ty.isNull())
619           continue;
620         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
621           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
622             continue;
623 
624           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
625             return cloneFullComment(FC, D);
626         }
627       }
628       // Check virtual bases.
629       for (const auto &I : RD->vbases()) {
630         if (I.getAccessSpecifier() != AS_public)
631           continue;
632         QualType Ty = I.getType();
633         if (Ty.isNull())
634           continue;
635         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
636           if (!(VirtualBase= VirtualBase->getDefinition()))
637             continue;
638           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
639             return cloneFullComment(FC, D);
640         }
641       }
642     }
643     return nullptr;
644   }
645 
646   // If the RawComment was attached to other redeclaration of this Decl, we
647   // should parse the comment in context of that other Decl.  This is important
648   // because comments can contain references to parameter names which can be
649   // different across redeclarations.
650   if (D != OriginalDecl && OriginalDecl)
651     return getCommentForDecl(OriginalDecl, PP);
652 
653   comments::FullComment *FC = RC->parse(*this, PP, D);
654   ParsedComments[Canonical] = FC;
655   return FC;
656 }
657 
658 void
659 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
660                                                    const ASTContext &C,
661                                                TemplateTemplateParmDecl *Parm) {
662   ID.AddInteger(Parm->getDepth());
663   ID.AddInteger(Parm->getPosition());
664   ID.AddBoolean(Parm->isParameterPack());
665 
666   TemplateParameterList *Params = Parm->getTemplateParameters();
667   ID.AddInteger(Params->size());
668   for (TemplateParameterList::const_iterator P = Params->begin(),
669                                           PEnd = Params->end();
670        P != PEnd; ++P) {
671     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
672       ID.AddInteger(0);
673       ID.AddBoolean(TTP->isParameterPack());
674       const TypeConstraint *TC = TTP->getTypeConstraint();
675       ID.AddBoolean(TC != nullptr);
676       if (TC)
677         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
678                                                         /*Canonical=*/true);
679       if (TTP->isExpandedParameterPack()) {
680         ID.AddBoolean(true);
681         ID.AddInteger(TTP->getNumExpansionParameters());
682       } else
683         ID.AddBoolean(false);
684       continue;
685     }
686 
687     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
688       ID.AddInteger(1);
689       ID.AddBoolean(NTTP->isParameterPack());
690       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
691       if (NTTP->isExpandedParameterPack()) {
692         ID.AddBoolean(true);
693         ID.AddInteger(NTTP->getNumExpansionTypes());
694         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
695           QualType T = NTTP->getExpansionType(I);
696           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
697         }
698       } else
699         ID.AddBoolean(false);
700       continue;
701     }
702 
703     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
704     ID.AddInteger(2);
705     Profile(ID, C, TTP);
706   }
707   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
708   ID.AddBoolean(RequiresClause != nullptr);
709   if (RequiresClause)
710     RequiresClause->Profile(ID, C, /*Canonical=*/true);
711 }
712 
713 static Expr *
714 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
715                                           QualType ConstrainedType) {
716   // This is a bit ugly - we need to form a new immediately-declared
717   // constraint that references the new parameter; this would ideally
718   // require semantic analysis (e.g. template<C T> struct S {}; - the
719   // converted arguments of C<T> could be an argument pack if C is
720   // declared as template<typename... T> concept C = ...).
721   // We don't have semantic analysis here so we dig deep into the
722   // ready-made constraint expr and change the thing manually.
723   ConceptSpecializationExpr *CSE;
724   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
725     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
726   else
727     CSE = cast<ConceptSpecializationExpr>(IDC);
728   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
729   SmallVector<TemplateArgument, 3> NewConverted;
730   NewConverted.reserve(OldConverted.size());
731   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
732     // The case:
733     // template<typename... T> concept C = true;
734     // template<C<int> T> struct S; -> constraint is C<{T, int}>
735     NewConverted.push_back(ConstrainedType);
736     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
737       NewConverted.push_back(Arg);
738     TemplateArgument NewPack(NewConverted);
739 
740     NewConverted.clear();
741     NewConverted.push_back(NewPack);
742     assert(OldConverted.size() == 1 &&
743            "Template parameter pack should be the last parameter");
744   } else {
745     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
746            "Unexpected first argument kind for immediately-declared "
747            "constraint");
748     NewConverted.push_back(ConstrainedType);
749     for (auto &Arg : OldConverted.drop_front(1))
750       NewConverted.push_back(Arg);
751   }
752   Expr *NewIDC = ConceptSpecializationExpr::Create(
753       C, CSE->getNamedConcept(), NewConverted, nullptr,
754       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
755 
756   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
757     NewIDC = new (C) CXXFoldExpr(
758         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
759         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
760         SourceLocation(), /*NumExpansions=*/None);
761   return NewIDC;
762 }
763 
764 TemplateTemplateParmDecl *
765 ASTContext::getCanonicalTemplateTemplateParmDecl(
766                                           TemplateTemplateParmDecl *TTP) const {
767   // Check if we already have a canonical template template parameter.
768   llvm::FoldingSetNodeID ID;
769   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
770   void *InsertPos = nullptr;
771   CanonicalTemplateTemplateParm *Canonical
772     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
773   if (Canonical)
774     return Canonical->getParam();
775 
776   // Build a canonical template parameter list.
777   TemplateParameterList *Params = TTP->getTemplateParameters();
778   SmallVector<NamedDecl *, 4> CanonParams;
779   CanonParams.reserve(Params->size());
780   for (TemplateParameterList::const_iterator P = Params->begin(),
781                                           PEnd = Params->end();
782        P != PEnd; ++P) {
783     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
784       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
785           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
786           TTP->getDepth(), TTP->getIndex(), nullptr, false,
787           TTP->isParameterPack(), TTP->hasTypeConstraint(),
788           TTP->isExpandedParameterPack() ?
789           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
790       if (const auto *TC = TTP->getTypeConstraint()) {
791         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
792         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
793                 *this, TC->getImmediatelyDeclaredConstraint(),
794                 ParamAsArgument);
795         TemplateArgumentListInfo CanonArgsAsWritten;
796         if (auto *Args = TC->getTemplateArgsAsWritten())
797           for (const auto &ArgLoc : Args->arguments())
798             CanonArgsAsWritten.addArgument(
799                 TemplateArgumentLoc(ArgLoc.getArgument(),
800                                     TemplateArgumentLocInfo()));
801         NewTTP->setTypeConstraint(
802             NestedNameSpecifierLoc(),
803             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
804                                 SourceLocation()), /*FoundDecl=*/nullptr,
805             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
806             // simply omit the ArgsAsWritten
807             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
808       }
809       CanonParams.push_back(NewTTP);
810     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
811       QualType T = getCanonicalType(NTTP->getType());
812       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
813       NonTypeTemplateParmDecl *Param;
814       if (NTTP->isExpandedParameterPack()) {
815         SmallVector<QualType, 2> ExpandedTypes;
816         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
817         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
818           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
819           ExpandedTInfos.push_back(
820                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
821         }
822 
823         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
824                                                 SourceLocation(),
825                                                 SourceLocation(),
826                                                 NTTP->getDepth(),
827                                                 NTTP->getPosition(), nullptr,
828                                                 T,
829                                                 TInfo,
830                                                 ExpandedTypes,
831                                                 ExpandedTInfos);
832       } else {
833         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
834                                                 SourceLocation(),
835                                                 SourceLocation(),
836                                                 NTTP->getDepth(),
837                                                 NTTP->getPosition(), nullptr,
838                                                 T,
839                                                 NTTP->isParameterPack(),
840                                                 TInfo);
841       }
842       if (AutoType *AT = T->getContainedAutoType()) {
843         if (AT->isConstrained()) {
844           Param->setPlaceholderTypeConstraint(
845               canonicalizeImmediatelyDeclaredConstraint(
846                   *this, NTTP->getPlaceholderTypeConstraint(), T));
847         }
848       }
849       CanonParams.push_back(Param);
850 
851     } else
852       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
853                                            cast<TemplateTemplateParmDecl>(*P)));
854   }
855 
856   Expr *CanonRequiresClause = nullptr;
857   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
858     CanonRequiresClause = RequiresClause;
859 
860   TemplateTemplateParmDecl *CanonTTP
861     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
862                                        SourceLocation(), TTP->getDepth(),
863                                        TTP->getPosition(),
864                                        TTP->isParameterPack(),
865                                        nullptr,
866                          TemplateParameterList::Create(*this, SourceLocation(),
867                                                        SourceLocation(),
868                                                        CanonParams,
869                                                        SourceLocation(),
870                                                        CanonRequiresClause));
871 
872   // Get the new insert position for the node we care about.
873   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
874   assert(!Canonical && "Shouldn't be in the map!");
875   (void)Canonical;
876 
877   // Create the canonical template template parameter entry.
878   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
879   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
880   return CanonTTP;
881 }
882 
883 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884   if (!LangOpts.CPlusPlus) return nullptr;
885 
886   switch (T.getCXXABI().getKind()) {
887   case TargetCXXABI::AppleARM64:
888   case TargetCXXABI::Fuchsia:
889   case TargetCXXABI::GenericARM: // Same as Itanium at this level
890   case TargetCXXABI::iOS:
891   case TargetCXXABI::WatchOS:
892   case TargetCXXABI::GenericAArch64:
893   case TargetCXXABI::GenericMIPS:
894   case TargetCXXABI::GenericItanium:
895   case TargetCXXABI::WebAssembly:
896   case TargetCXXABI::XL:
897     return CreateItaniumCXXABI(*this);
898   case TargetCXXABI::Microsoft:
899     return CreateMicrosoftCXXABI(*this);
900   }
901   llvm_unreachable("Invalid CXXABI type!");
902 }
903 
904 interp::Context &ASTContext::getInterpContext() {
905   if (!InterpContext) {
906     InterpContext.reset(new interp::Context(*this));
907   }
908   return *InterpContext.get();
909 }
910 
911 ParentMapContext &ASTContext::getParentMapContext() {
912   if (!ParentMapCtx)
913     ParentMapCtx.reset(new ParentMapContext(*this));
914   return *ParentMapCtx.get();
915 }
916 
917 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
918                                            const LangOptions &LOpts) {
919   if (LOpts.FakeAddressSpaceMap) {
920     // The fake address space map must have a distinct entry for each
921     // language-specific address space.
922     static const unsigned FakeAddrSpaceMap[] = {
923         0,  // Default
924         1,  // opencl_global
925         3,  // opencl_local
926         2,  // opencl_constant
927         0,  // opencl_private
928         4,  // opencl_generic
929         5,  // opencl_global_device
930         6,  // opencl_global_host
931         7,  // cuda_device
932         8,  // cuda_constant
933         9,  // cuda_shared
934         10, // ptr32_sptr
935         11, // ptr32_uptr
936         12  // ptr64
937     };
938     return &FakeAddrSpaceMap;
939   } else {
940     return &T.getAddressSpaceMap();
941   }
942 }
943 
944 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
945                                           const LangOptions &LangOpts) {
946   switch (LangOpts.getAddressSpaceMapMangling()) {
947   case LangOptions::ASMM_Target:
948     return TI.useAddressSpaceMapMangling();
949   case LangOptions::ASMM_On:
950     return true;
951   case LangOptions::ASMM_Off:
952     return false;
953   }
954   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
955 }
956 
957 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
958                        IdentifierTable &idents, SelectorTable &sels,
959                        Builtin::Context &builtins)
960     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
961       TemplateSpecializationTypes(this_()),
962       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
963       SubstTemplateTemplateParmPacks(this_()),
964       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
965       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
966       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
967                                         LangOpts.XRayNeverInstrumentFiles,
968                                         LangOpts.XRayAttrListFiles, SM)),
969       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
970       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
971       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
972       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
973       CompCategories(this_()), LastSDM(nullptr, 0) {
974   TUDecl = TranslationUnitDecl::Create(*this);
975   TraversalScope = {TUDecl};
976 }
977 
978 ASTContext::~ASTContext() {
979   // Release the DenseMaps associated with DeclContext objects.
980   // FIXME: Is this the ideal solution?
981   ReleaseDeclContextMaps();
982 
983   // Call all of the deallocation functions on all of their targets.
984   for (auto &Pair : Deallocations)
985     (Pair.first)(Pair.second);
986 
987   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
988   // because they can contain DenseMaps.
989   for (llvm::DenseMap<const ObjCContainerDecl*,
990        const ASTRecordLayout*>::iterator
991        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
992     // Increment in loop to prevent using deallocated memory.
993     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
994       R->Destroy(*this);
995 
996   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
997        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
998     // Increment in loop to prevent using deallocated memory.
999     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1000       R->Destroy(*this);
1001   }
1002 
1003   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1004                                                     AEnd = DeclAttrs.end();
1005        A != AEnd; ++A)
1006     A->second->~AttrVec();
1007 
1008   for (const auto &Value : ModuleInitializers)
1009     Value.second->~PerModuleInitializers();
1010 }
1011 
1012 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1013   TraversalScope = TopLevelDecls;
1014   getParentMapContext().clear();
1015 }
1016 
1017 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1018   Deallocations.push_back({Callback, Data});
1019 }
1020 
1021 void
1022 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1023   ExternalSource = std::move(Source);
1024 }
1025 
1026 void ASTContext::PrintStats() const {
1027   llvm::errs() << "\n*** AST Context Stats:\n";
1028   llvm::errs() << "  " << Types.size() << " types total.\n";
1029 
1030   unsigned counts[] = {
1031 #define TYPE(Name, Parent) 0,
1032 #define ABSTRACT_TYPE(Name, Parent)
1033 #include "clang/AST/TypeNodes.inc"
1034     0 // Extra
1035   };
1036 
1037   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1038     Type *T = Types[i];
1039     counts[(unsigned)T->getTypeClass()]++;
1040   }
1041 
1042   unsigned Idx = 0;
1043   unsigned TotalBytes = 0;
1044 #define TYPE(Name, Parent)                                              \
1045   if (counts[Idx])                                                      \
1046     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1047                  << " types, " << sizeof(Name##Type) << " each "        \
1048                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1049                  << " bytes)\n";                                        \
1050   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1051   ++Idx;
1052 #define ABSTRACT_TYPE(Name, Parent)
1053 #include "clang/AST/TypeNodes.inc"
1054 
1055   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1056 
1057   // Implicit special member functions.
1058   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1059                << NumImplicitDefaultConstructors
1060                << " implicit default constructors created\n";
1061   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1062                << NumImplicitCopyConstructors
1063                << " implicit copy constructors created\n";
1064   if (getLangOpts().CPlusPlus)
1065     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1066                  << NumImplicitMoveConstructors
1067                  << " implicit move constructors created\n";
1068   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1069                << NumImplicitCopyAssignmentOperators
1070                << " implicit copy assignment operators created\n";
1071   if (getLangOpts().CPlusPlus)
1072     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1073                  << NumImplicitMoveAssignmentOperators
1074                  << " implicit move assignment operators created\n";
1075   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1076                << NumImplicitDestructors
1077                << " implicit destructors created\n";
1078 
1079   if (ExternalSource) {
1080     llvm::errs() << "\n";
1081     ExternalSource->PrintStats();
1082   }
1083 
1084   BumpAlloc.PrintStats();
1085 }
1086 
1087 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1088                                            bool NotifyListeners) {
1089   if (NotifyListeners)
1090     if (auto *Listener = getASTMutationListener())
1091       Listener->RedefinedHiddenDefinition(ND, M);
1092 
1093   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1094 }
1095 
1096 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1097   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1098   if (It == MergedDefModules.end())
1099     return;
1100 
1101   auto &Merged = It->second;
1102   llvm::DenseSet<Module*> Found;
1103   for (Module *&M : Merged)
1104     if (!Found.insert(M).second)
1105       M = nullptr;
1106   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1107 }
1108 
1109 ArrayRef<Module *>
1110 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1111   auto MergedIt =
1112       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1113   if (MergedIt == MergedDefModules.end())
1114     return None;
1115   return MergedIt->second;
1116 }
1117 
1118 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1119   if (LazyInitializers.empty())
1120     return;
1121 
1122   auto *Source = Ctx.getExternalSource();
1123   assert(Source && "lazy initializers but no external source");
1124 
1125   auto LazyInits = std::move(LazyInitializers);
1126   LazyInitializers.clear();
1127 
1128   for (auto ID : LazyInits)
1129     Initializers.push_back(Source->GetExternalDecl(ID));
1130 
1131   assert(LazyInitializers.empty() &&
1132          "GetExternalDecl for lazy module initializer added more inits");
1133 }
1134 
1135 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1136   // One special case: if we add a module initializer that imports another
1137   // module, and that module's only initializer is an ImportDecl, simplify.
1138   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1139     auto It = ModuleInitializers.find(ID->getImportedModule());
1140 
1141     // Maybe the ImportDecl does nothing at all. (Common case.)
1142     if (It == ModuleInitializers.end())
1143       return;
1144 
1145     // Maybe the ImportDecl only imports another ImportDecl.
1146     auto &Imported = *It->second;
1147     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1148       Imported.resolve(*this);
1149       auto *OnlyDecl = Imported.Initializers.front();
1150       if (isa<ImportDecl>(OnlyDecl))
1151         D = OnlyDecl;
1152     }
1153   }
1154 
1155   auto *&Inits = ModuleInitializers[M];
1156   if (!Inits)
1157     Inits = new (*this) PerModuleInitializers;
1158   Inits->Initializers.push_back(D);
1159 }
1160 
1161 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1162   auto *&Inits = ModuleInitializers[M];
1163   if (!Inits)
1164     Inits = new (*this) PerModuleInitializers;
1165   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1166                                  IDs.begin(), IDs.end());
1167 }
1168 
1169 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1170   auto It = ModuleInitializers.find(M);
1171   if (It == ModuleInitializers.end())
1172     return None;
1173 
1174   auto *Inits = It->second;
1175   Inits->resolve(*this);
1176   return Inits->Initializers;
1177 }
1178 
1179 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1180   if (!ExternCContext)
1181     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1182 
1183   return ExternCContext;
1184 }
1185 
1186 BuiltinTemplateDecl *
1187 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1188                                      const IdentifierInfo *II) const {
1189   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1190   BuiltinTemplate->setImplicit();
1191   TUDecl->addDecl(BuiltinTemplate);
1192 
1193   return BuiltinTemplate;
1194 }
1195 
1196 BuiltinTemplateDecl *
1197 ASTContext::getMakeIntegerSeqDecl() const {
1198   if (!MakeIntegerSeqDecl)
1199     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1200                                                   getMakeIntegerSeqName());
1201   return MakeIntegerSeqDecl;
1202 }
1203 
1204 BuiltinTemplateDecl *
1205 ASTContext::getTypePackElementDecl() const {
1206   if (!TypePackElementDecl)
1207     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1208                                                    getTypePackElementName());
1209   return TypePackElementDecl;
1210 }
1211 
1212 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1213                                             RecordDecl::TagKind TK) const {
1214   SourceLocation Loc;
1215   RecordDecl *NewDecl;
1216   if (getLangOpts().CPlusPlus)
1217     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1218                                     Loc, &Idents.get(Name));
1219   else
1220     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1221                                  &Idents.get(Name));
1222   NewDecl->setImplicit();
1223   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1224       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1225   return NewDecl;
1226 }
1227 
1228 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1229                                               StringRef Name) const {
1230   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1231   TypedefDecl *NewDecl = TypedefDecl::Create(
1232       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1233       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1234   NewDecl->setImplicit();
1235   return NewDecl;
1236 }
1237 
1238 TypedefDecl *ASTContext::getInt128Decl() const {
1239   if (!Int128Decl)
1240     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1241   return Int128Decl;
1242 }
1243 
1244 TypedefDecl *ASTContext::getUInt128Decl() const {
1245   if (!UInt128Decl)
1246     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1247   return UInt128Decl;
1248 }
1249 
1250 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1251   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1252   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1253   Types.push_back(Ty);
1254 }
1255 
1256 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1257                                   const TargetInfo *AuxTarget) {
1258   assert((!this->Target || this->Target == &Target) &&
1259          "Incorrect target reinitialization");
1260   assert(VoidTy.isNull() && "Context reinitialized?");
1261 
1262   this->Target = &Target;
1263   this->AuxTarget = AuxTarget;
1264 
1265   ABI.reset(createCXXABI(Target));
1266   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1267   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1268 
1269   // C99 6.2.5p19.
1270   InitBuiltinType(VoidTy,              BuiltinType::Void);
1271 
1272   // C99 6.2.5p2.
1273   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1274   // C99 6.2.5p3.
1275   if (LangOpts.CharIsSigned)
1276     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1277   else
1278     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1279   // C99 6.2.5p4.
1280   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1281   InitBuiltinType(ShortTy,             BuiltinType::Short);
1282   InitBuiltinType(IntTy,               BuiltinType::Int);
1283   InitBuiltinType(LongTy,              BuiltinType::Long);
1284   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1285 
1286   // C99 6.2.5p6.
1287   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1288   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1289   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1290   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1291   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1292 
1293   // C99 6.2.5p10.
1294   InitBuiltinType(FloatTy,             BuiltinType::Float);
1295   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1296   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1297 
1298   // GNU extension, __float128 for IEEE quadruple precision
1299   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1300 
1301   // C11 extension ISO/IEC TS 18661-3
1302   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1303 
1304   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1305   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1306   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1307   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1308   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1309   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1310   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1311   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1312   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1313   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1314   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1315   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1316   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1317   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1318   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1319   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1320   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1321   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1322   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1323   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1324   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1325   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1326   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1327   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1328   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1329 
1330   // GNU extension, 128-bit integers.
1331   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1332   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1333 
1334   // C++ 3.9.1p5
1335   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1336     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1337   else  // -fshort-wchar makes wchar_t be unsigned.
1338     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1339   if (LangOpts.CPlusPlus && LangOpts.WChar)
1340     WideCharTy = WCharTy;
1341   else {
1342     // C99 (or C++ using -fno-wchar).
1343     WideCharTy = getFromTargetType(Target.getWCharType());
1344   }
1345 
1346   WIntTy = getFromTargetType(Target.getWIntType());
1347 
1348   // C++20 (proposed)
1349   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1350 
1351   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1352     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1353   else // C99
1354     Char16Ty = getFromTargetType(Target.getChar16Type());
1355 
1356   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1357     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1358   else // C99
1359     Char32Ty = getFromTargetType(Target.getChar32Type());
1360 
1361   // Placeholder type for type-dependent expressions whose type is
1362   // completely unknown. No code should ever check a type against
1363   // DependentTy and users should never see it; however, it is here to
1364   // help diagnose failures to properly check for type-dependent
1365   // expressions.
1366   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1367 
1368   // Placeholder type for functions.
1369   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1370 
1371   // Placeholder type for bound members.
1372   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1373 
1374   // Placeholder type for pseudo-objects.
1375   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1376 
1377   // "any" type; useful for debugger-like clients.
1378   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1379 
1380   // Placeholder type for unbridged ARC casts.
1381   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1382 
1383   // Placeholder type for builtin functions.
1384   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1385 
1386   // Placeholder type for OMP array sections.
1387   if (LangOpts.OpenMP) {
1388     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1389     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1390     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1391   }
1392   if (LangOpts.MatrixTypes)
1393     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1394 
1395   // C99 6.2.5p11.
1396   FloatComplexTy      = getComplexType(FloatTy);
1397   DoubleComplexTy     = getComplexType(DoubleTy);
1398   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1399   Float128ComplexTy   = getComplexType(Float128Ty);
1400 
1401   // Builtin types for 'id', 'Class', and 'SEL'.
1402   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1403   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1404   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1405 
1406   if (LangOpts.OpenCL) {
1407 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1408     InitBuiltinType(SingletonId, BuiltinType::Id);
1409 #include "clang/Basic/OpenCLImageTypes.def"
1410 
1411     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1412     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1413     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1414     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1415     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1416 
1417 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1418     InitBuiltinType(Id##Ty, BuiltinType::Id);
1419 #include "clang/Basic/OpenCLExtensionTypes.def"
1420   }
1421 
1422   if (Target.hasAArch64SVETypes()) {
1423 #define SVE_TYPE(Name, Id, SingletonId) \
1424     InitBuiltinType(SingletonId, BuiltinType::Id);
1425 #include "clang/Basic/AArch64SVEACLETypes.def"
1426   }
1427 
1428   if (Target.getTriple().isPPC64() &&
1429       Target.hasFeature("paired-vector-memops")) {
1430     if (Target.hasFeature("mma")) {
1431 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1432       InitBuiltinType(Id##Ty, BuiltinType::Id);
1433 #include "clang/Basic/PPCTypes.def"
1434     }
1435 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1436     InitBuiltinType(Id##Ty, BuiltinType::Id);
1437 #include "clang/Basic/PPCTypes.def"
1438   }
1439 
1440   if (Target.hasRISCVVTypes()) {
1441 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1442   InitBuiltinType(SingletonId, BuiltinType::Id);
1443 #include "clang/Basic/RISCVVTypes.def"
1444   }
1445 
1446   // Builtin type for __objc_yes and __objc_no
1447   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1448                        SignedCharTy : BoolTy);
1449 
1450   ObjCConstantStringType = QualType();
1451 
1452   ObjCSuperType = QualType();
1453 
1454   // void * type
1455   if (LangOpts.OpenCLGenericAddressSpace) {
1456     auto Q = VoidTy.getQualifiers();
1457     Q.setAddressSpace(LangAS::opencl_generic);
1458     VoidPtrTy = getPointerType(getCanonicalType(
1459         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1460   } else {
1461     VoidPtrTy = getPointerType(VoidTy);
1462   }
1463 
1464   // nullptr type (C++0x 2.14.7)
1465   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1466 
1467   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1468   InitBuiltinType(HalfTy, BuiltinType::Half);
1469 
1470   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1471 
1472   // Builtin type used to help define __builtin_va_list.
1473   VaListTagDecl = nullptr;
1474 
1475   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1476   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1477     MSGuidTagDecl = buildImplicitRecord("_GUID");
1478     TUDecl->addDecl(MSGuidTagDecl);
1479   }
1480 }
1481 
1482 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1483   return SourceMgr.getDiagnostics();
1484 }
1485 
1486 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1487   AttrVec *&Result = DeclAttrs[D];
1488   if (!Result) {
1489     void *Mem = Allocate(sizeof(AttrVec));
1490     Result = new (Mem) AttrVec;
1491   }
1492 
1493   return *Result;
1494 }
1495 
1496 /// Erase the attributes corresponding to the given declaration.
1497 void ASTContext::eraseDeclAttrs(const Decl *D) {
1498   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1499   if (Pos != DeclAttrs.end()) {
1500     Pos->second->~AttrVec();
1501     DeclAttrs.erase(Pos);
1502   }
1503 }
1504 
1505 // FIXME: Remove ?
1506 MemberSpecializationInfo *
1507 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1508   assert(Var->isStaticDataMember() && "Not a static data member");
1509   return getTemplateOrSpecializationInfo(Var)
1510       .dyn_cast<MemberSpecializationInfo *>();
1511 }
1512 
1513 ASTContext::TemplateOrSpecializationInfo
1514 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1515   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1516       TemplateOrInstantiation.find(Var);
1517   if (Pos == TemplateOrInstantiation.end())
1518     return {};
1519 
1520   return Pos->second;
1521 }
1522 
1523 void
1524 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1525                                                 TemplateSpecializationKind TSK,
1526                                           SourceLocation PointOfInstantiation) {
1527   assert(Inst->isStaticDataMember() && "Not a static data member");
1528   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1529   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1530                                             Tmpl, TSK, PointOfInstantiation));
1531 }
1532 
1533 void
1534 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1535                                             TemplateOrSpecializationInfo TSI) {
1536   assert(!TemplateOrInstantiation[Inst] &&
1537          "Already noted what the variable was instantiated from");
1538   TemplateOrInstantiation[Inst] = TSI;
1539 }
1540 
1541 NamedDecl *
1542 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1543   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1544   if (Pos == InstantiatedFromUsingDecl.end())
1545     return nullptr;
1546 
1547   return Pos->second;
1548 }
1549 
1550 void
1551 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1552   assert((isa<UsingDecl>(Pattern) ||
1553           isa<UnresolvedUsingValueDecl>(Pattern) ||
1554           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1555          "pattern decl is not a using decl");
1556   assert((isa<UsingDecl>(Inst) ||
1557           isa<UnresolvedUsingValueDecl>(Inst) ||
1558           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1559          "instantiation did not produce a using decl");
1560   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1561   InstantiatedFromUsingDecl[Inst] = Pattern;
1562 }
1563 
1564 UsingShadowDecl *
1565 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1566   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1567     = InstantiatedFromUsingShadowDecl.find(Inst);
1568   if (Pos == InstantiatedFromUsingShadowDecl.end())
1569     return nullptr;
1570 
1571   return Pos->second;
1572 }
1573 
1574 void
1575 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1576                                                UsingShadowDecl *Pattern) {
1577   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1578   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1579 }
1580 
1581 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1582   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1583     = InstantiatedFromUnnamedFieldDecl.find(Field);
1584   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1585     return nullptr;
1586 
1587   return Pos->second;
1588 }
1589 
1590 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1591                                                      FieldDecl *Tmpl) {
1592   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1593   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1594   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1595          "Already noted what unnamed field was instantiated from");
1596 
1597   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1598 }
1599 
1600 ASTContext::overridden_cxx_method_iterator
1601 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1602   return overridden_methods(Method).begin();
1603 }
1604 
1605 ASTContext::overridden_cxx_method_iterator
1606 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1607   return overridden_methods(Method).end();
1608 }
1609 
1610 unsigned
1611 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1612   auto Range = overridden_methods(Method);
1613   return Range.end() - Range.begin();
1614 }
1615 
1616 ASTContext::overridden_method_range
1617 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1618   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1619       OverriddenMethods.find(Method->getCanonicalDecl());
1620   if (Pos == OverriddenMethods.end())
1621     return overridden_method_range(nullptr, nullptr);
1622   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1623 }
1624 
1625 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1626                                      const CXXMethodDecl *Overridden) {
1627   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1628   OverriddenMethods[Method].push_back(Overridden);
1629 }
1630 
1631 void ASTContext::getOverriddenMethods(
1632                       const NamedDecl *D,
1633                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1634   assert(D);
1635 
1636   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1637     Overridden.append(overridden_methods_begin(CXXMethod),
1638                       overridden_methods_end(CXXMethod));
1639     return;
1640   }
1641 
1642   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1643   if (!Method)
1644     return;
1645 
1646   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1647   Method->getOverriddenMethods(OverDecls);
1648   Overridden.append(OverDecls.begin(), OverDecls.end());
1649 }
1650 
1651 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1652   assert(!Import->getNextLocalImport() &&
1653          "Import declaration already in the chain");
1654   assert(!Import->isFromASTFile() && "Non-local import declaration");
1655   if (!FirstLocalImport) {
1656     FirstLocalImport = Import;
1657     LastLocalImport = Import;
1658     return;
1659   }
1660 
1661   LastLocalImport->setNextLocalImport(Import);
1662   LastLocalImport = Import;
1663 }
1664 
1665 //===----------------------------------------------------------------------===//
1666 //                         Type Sizing and Analysis
1667 //===----------------------------------------------------------------------===//
1668 
1669 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1670 /// scalar floating point type.
1671 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1672   switch (T->castAs<BuiltinType>()->getKind()) {
1673   default:
1674     llvm_unreachable("Not a floating point type!");
1675   case BuiltinType::BFloat16:
1676     return Target->getBFloat16Format();
1677   case BuiltinType::Float16:
1678   case BuiltinType::Half:
1679     return Target->getHalfFormat();
1680   case BuiltinType::Float:      return Target->getFloatFormat();
1681   case BuiltinType::Double:     return Target->getDoubleFormat();
1682   case BuiltinType::LongDouble:
1683     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1684       return AuxTarget->getLongDoubleFormat();
1685     return Target->getLongDoubleFormat();
1686   case BuiltinType::Float128:
1687     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1688       return AuxTarget->getFloat128Format();
1689     return Target->getFloat128Format();
1690   }
1691 }
1692 
1693 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1694   unsigned Align = Target->getCharWidth();
1695 
1696   bool UseAlignAttrOnly = false;
1697   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1698     Align = AlignFromAttr;
1699 
1700     // __attribute__((aligned)) can increase or decrease alignment
1701     // *except* on a struct or struct member, where it only increases
1702     // alignment unless 'packed' is also specified.
1703     //
1704     // It is an error for alignas to decrease alignment, so we can
1705     // ignore that possibility;  Sema should diagnose it.
1706     if (isa<FieldDecl>(D)) {
1707       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1708         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1709     } else {
1710       UseAlignAttrOnly = true;
1711     }
1712   }
1713   else if (isa<FieldDecl>(D))
1714       UseAlignAttrOnly =
1715         D->hasAttr<PackedAttr>() ||
1716         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1717 
1718   // If we're using the align attribute only, just ignore everything
1719   // else about the declaration and its type.
1720   if (UseAlignAttrOnly) {
1721     // do nothing
1722   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1723     QualType T = VD->getType();
1724     if (const auto *RT = T->getAs<ReferenceType>()) {
1725       if (ForAlignof)
1726         T = RT->getPointeeType();
1727       else
1728         T = getPointerType(RT->getPointeeType());
1729     }
1730     QualType BaseT = getBaseElementType(T);
1731     if (T->isFunctionType())
1732       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1733     else if (!BaseT->isIncompleteType()) {
1734       // Adjust alignments of declarations with array type by the
1735       // large-array alignment on the target.
1736       if (const ArrayType *arrayType = getAsArrayType(T)) {
1737         unsigned MinWidth = Target->getLargeArrayMinWidth();
1738         if (!ForAlignof && MinWidth) {
1739           if (isa<VariableArrayType>(arrayType))
1740             Align = std::max(Align, Target->getLargeArrayAlign());
1741           else if (isa<ConstantArrayType>(arrayType) &&
1742                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1743             Align = std::max(Align, Target->getLargeArrayAlign());
1744         }
1745       }
1746       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1747       if (BaseT.getQualifiers().hasUnaligned())
1748         Align = Target->getCharWidth();
1749       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1750         if (VD->hasGlobalStorage() && !ForAlignof) {
1751           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1752           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1753         }
1754       }
1755     }
1756 
1757     // Fields can be subject to extra alignment constraints, like if
1758     // the field is packed, the struct is packed, or the struct has a
1759     // a max-field-alignment constraint (#pragma pack).  So calculate
1760     // the actual alignment of the field within the struct, and then
1761     // (as we're expected to) constrain that by the alignment of the type.
1762     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1763       const RecordDecl *Parent = Field->getParent();
1764       // We can only produce a sensible answer if the record is valid.
1765       if (!Parent->isInvalidDecl()) {
1766         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1767 
1768         // Start with the record's overall alignment.
1769         unsigned FieldAlign = toBits(Layout.getAlignment());
1770 
1771         // Use the GCD of that and the offset within the record.
1772         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1773         if (Offset > 0) {
1774           // Alignment is always a power of 2, so the GCD will be a power of 2,
1775           // which means we get to do this crazy thing instead of Euclid's.
1776           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1777           if (LowBitOfOffset < FieldAlign)
1778             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1779         }
1780 
1781         Align = std::min(Align, FieldAlign);
1782       }
1783     }
1784   }
1785 
1786   return toCharUnitsFromBits(Align);
1787 }
1788 
1789 CharUnits ASTContext::getExnObjectAlignment() const {
1790   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1791 }
1792 
1793 // getTypeInfoDataSizeInChars - Return the size of a type, in
1794 // chars. If the type is a record, its data size is returned.  This is
1795 // the size of the memcpy that's performed when assigning this type
1796 // using a trivial copy/move assignment operator.
1797 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1798   TypeInfoChars Info = getTypeInfoInChars(T);
1799 
1800   // In C++, objects can sometimes be allocated into the tail padding
1801   // of a base-class subobject.  We decide whether that's possible
1802   // during class layout, so here we can just trust the layout results.
1803   if (getLangOpts().CPlusPlus) {
1804     if (const auto *RT = T->getAs<RecordType>()) {
1805       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1806       Info.Width = layout.getDataSize();
1807     }
1808   }
1809 
1810   return Info;
1811 }
1812 
1813 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1814 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1815 TypeInfoChars
1816 static getConstantArrayInfoInChars(const ASTContext &Context,
1817                                    const ConstantArrayType *CAT) {
1818   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1819   uint64_t Size = CAT->getSize().getZExtValue();
1820   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1821               (uint64_t)(-1)/Size) &&
1822          "Overflow in array type char size evaluation");
1823   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1824   unsigned Align = EltInfo.Align.getQuantity();
1825   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1826       Context.getTargetInfo().getPointerWidth(0) == 64)
1827     Width = llvm::alignTo(Width, Align);
1828   return TypeInfoChars(CharUnits::fromQuantity(Width),
1829                        CharUnits::fromQuantity(Align),
1830                        EltInfo.AlignIsRequired);
1831 }
1832 
1833 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1834   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1835     return getConstantArrayInfoInChars(*this, CAT);
1836   TypeInfo Info = getTypeInfo(T);
1837   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1838                        toCharUnitsFromBits(Info.Align),
1839                        Info.AlignIsRequired);
1840 }
1841 
1842 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1843   return getTypeInfoInChars(T.getTypePtr());
1844 }
1845 
1846 bool ASTContext::isAlignmentRequired(const Type *T) const {
1847   return getTypeInfo(T).AlignIsRequired;
1848 }
1849 
1850 bool ASTContext::isAlignmentRequired(QualType T) const {
1851   return isAlignmentRequired(T.getTypePtr());
1852 }
1853 
1854 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1855                                          bool NeedsPreferredAlignment) const {
1856   // An alignment on a typedef overrides anything else.
1857   if (const auto *TT = T->getAs<TypedefType>())
1858     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1859       return Align;
1860 
1861   // If we have an (array of) complete type, we're done.
1862   T = getBaseElementType(T);
1863   if (!T->isIncompleteType())
1864     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1865 
1866   // If we had an array type, its element type might be a typedef
1867   // type with an alignment attribute.
1868   if (const auto *TT = T->getAs<TypedefType>())
1869     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1870       return Align;
1871 
1872   // Otherwise, see if the declaration of the type had an attribute.
1873   if (const auto *TT = T->getAs<TagType>())
1874     return TT->getDecl()->getMaxAlignment();
1875 
1876   return 0;
1877 }
1878 
1879 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1880   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1881   if (I != MemoizedTypeInfo.end())
1882     return I->second;
1883 
1884   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1885   TypeInfo TI = getTypeInfoImpl(T);
1886   MemoizedTypeInfo[T] = TI;
1887   return TI;
1888 }
1889 
1890 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1891 /// method does not work on incomplete types.
1892 ///
1893 /// FIXME: Pointers into different addr spaces could have different sizes and
1894 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1895 /// should take a QualType, &c.
1896 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1897   uint64_t Width = 0;
1898   unsigned Align = 8;
1899   bool AlignIsRequired = false;
1900   unsigned AS = 0;
1901   switch (T->getTypeClass()) {
1902 #define TYPE(Class, Base)
1903 #define ABSTRACT_TYPE(Class, Base)
1904 #define NON_CANONICAL_TYPE(Class, Base)
1905 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1906 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1907   case Type::Class:                                                            \
1908   assert(!T->isDependentType() && "should not see dependent types here");      \
1909   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1910 #include "clang/AST/TypeNodes.inc"
1911     llvm_unreachable("Should not see dependent types");
1912 
1913   case Type::FunctionNoProto:
1914   case Type::FunctionProto:
1915     // GCC extension: alignof(function) = 32 bits
1916     Width = 0;
1917     Align = 32;
1918     break;
1919 
1920   case Type::IncompleteArray:
1921   case Type::VariableArray:
1922   case Type::ConstantArray: {
1923     // Model non-constant sized arrays as size zero, but track the alignment.
1924     uint64_t Size = 0;
1925     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1926       Size = CAT->getSize().getZExtValue();
1927 
1928     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1929     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1930            "Overflow in array type bit size evaluation");
1931     Width = EltInfo.Width * Size;
1932     Align = EltInfo.Align;
1933     AlignIsRequired = EltInfo.AlignIsRequired;
1934     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1935         getTargetInfo().getPointerWidth(0) == 64)
1936       Width = llvm::alignTo(Width, Align);
1937     break;
1938   }
1939 
1940   case Type::ExtVector:
1941   case Type::Vector: {
1942     const auto *VT = cast<VectorType>(T);
1943     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1944     Width = EltInfo.Width * VT->getNumElements();
1945     Align = Width;
1946     // If the alignment is not a power of 2, round up to the next power of 2.
1947     // This happens for non-power-of-2 length vectors.
1948     if (Align & (Align-1)) {
1949       Align = llvm::NextPowerOf2(Align);
1950       Width = llvm::alignTo(Width, Align);
1951     }
1952     // Adjust the alignment based on the target max.
1953     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1954     if (TargetVectorAlign && TargetVectorAlign < Align)
1955       Align = TargetVectorAlign;
1956     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
1957       // Adjust the alignment for fixed-length SVE vectors. This is important
1958       // for non-power-of-2 vector lengths.
1959       Align = 128;
1960     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
1961       // Adjust the alignment for fixed-length SVE predicates.
1962       Align = 16;
1963     break;
1964   }
1965 
1966   case Type::ConstantMatrix: {
1967     const auto *MT = cast<ConstantMatrixType>(T);
1968     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1969     // The internal layout of a matrix value is implementation defined.
1970     // Initially be ABI compatible with arrays with respect to alignment and
1971     // size.
1972     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1973     Align = ElementInfo.Align;
1974     break;
1975   }
1976 
1977   case Type::Builtin:
1978     switch (cast<BuiltinType>(T)->getKind()) {
1979     default: llvm_unreachable("Unknown builtin type!");
1980     case BuiltinType::Void:
1981       // GCC extension: alignof(void) = 8 bits.
1982       Width = 0;
1983       Align = 8;
1984       break;
1985     case BuiltinType::Bool:
1986       Width = Target->getBoolWidth();
1987       Align = Target->getBoolAlign();
1988       break;
1989     case BuiltinType::Char_S:
1990     case BuiltinType::Char_U:
1991     case BuiltinType::UChar:
1992     case BuiltinType::SChar:
1993     case BuiltinType::Char8:
1994       Width = Target->getCharWidth();
1995       Align = Target->getCharAlign();
1996       break;
1997     case BuiltinType::WChar_S:
1998     case BuiltinType::WChar_U:
1999       Width = Target->getWCharWidth();
2000       Align = Target->getWCharAlign();
2001       break;
2002     case BuiltinType::Char16:
2003       Width = Target->getChar16Width();
2004       Align = Target->getChar16Align();
2005       break;
2006     case BuiltinType::Char32:
2007       Width = Target->getChar32Width();
2008       Align = Target->getChar32Align();
2009       break;
2010     case BuiltinType::UShort:
2011     case BuiltinType::Short:
2012       Width = Target->getShortWidth();
2013       Align = Target->getShortAlign();
2014       break;
2015     case BuiltinType::UInt:
2016     case BuiltinType::Int:
2017       Width = Target->getIntWidth();
2018       Align = Target->getIntAlign();
2019       break;
2020     case BuiltinType::ULong:
2021     case BuiltinType::Long:
2022       Width = Target->getLongWidth();
2023       Align = Target->getLongAlign();
2024       break;
2025     case BuiltinType::ULongLong:
2026     case BuiltinType::LongLong:
2027       Width = Target->getLongLongWidth();
2028       Align = Target->getLongLongAlign();
2029       break;
2030     case BuiltinType::Int128:
2031     case BuiltinType::UInt128:
2032       Width = 128;
2033       Align = 128; // int128_t is 128-bit aligned on all targets.
2034       break;
2035     case BuiltinType::ShortAccum:
2036     case BuiltinType::UShortAccum:
2037     case BuiltinType::SatShortAccum:
2038     case BuiltinType::SatUShortAccum:
2039       Width = Target->getShortAccumWidth();
2040       Align = Target->getShortAccumAlign();
2041       break;
2042     case BuiltinType::Accum:
2043     case BuiltinType::UAccum:
2044     case BuiltinType::SatAccum:
2045     case BuiltinType::SatUAccum:
2046       Width = Target->getAccumWidth();
2047       Align = Target->getAccumAlign();
2048       break;
2049     case BuiltinType::LongAccum:
2050     case BuiltinType::ULongAccum:
2051     case BuiltinType::SatLongAccum:
2052     case BuiltinType::SatULongAccum:
2053       Width = Target->getLongAccumWidth();
2054       Align = Target->getLongAccumAlign();
2055       break;
2056     case BuiltinType::ShortFract:
2057     case BuiltinType::UShortFract:
2058     case BuiltinType::SatShortFract:
2059     case BuiltinType::SatUShortFract:
2060       Width = Target->getShortFractWidth();
2061       Align = Target->getShortFractAlign();
2062       break;
2063     case BuiltinType::Fract:
2064     case BuiltinType::UFract:
2065     case BuiltinType::SatFract:
2066     case BuiltinType::SatUFract:
2067       Width = Target->getFractWidth();
2068       Align = Target->getFractAlign();
2069       break;
2070     case BuiltinType::LongFract:
2071     case BuiltinType::ULongFract:
2072     case BuiltinType::SatLongFract:
2073     case BuiltinType::SatULongFract:
2074       Width = Target->getLongFractWidth();
2075       Align = Target->getLongFractAlign();
2076       break;
2077     case BuiltinType::BFloat16:
2078       Width = Target->getBFloat16Width();
2079       Align = Target->getBFloat16Align();
2080       break;
2081     case BuiltinType::Float16:
2082     case BuiltinType::Half:
2083       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2084           !getLangOpts().OpenMPIsDevice) {
2085         Width = Target->getHalfWidth();
2086         Align = Target->getHalfAlign();
2087       } else {
2088         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2089                "Expected OpenMP device compilation.");
2090         Width = AuxTarget->getHalfWidth();
2091         Align = AuxTarget->getHalfAlign();
2092       }
2093       break;
2094     case BuiltinType::Float:
2095       Width = Target->getFloatWidth();
2096       Align = Target->getFloatAlign();
2097       break;
2098     case BuiltinType::Double:
2099       Width = Target->getDoubleWidth();
2100       Align = Target->getDoubleAlign();
2101       break;
2102     case BuiltinType::LongDouble:
2103       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2104           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2105            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2106         Width = AuxTarget->getLongDoubleWidth();
2107         Align = AuxTarget->getLongDoubleAlign();
2108       } else {
2109         Width = Target->getLongDoubleWidth();
2110         Align = Target->getLongDoubleAlign();
2111       }
2112       break;
2113     case BuiltinType::Float128:
2114       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2115           !getLangOpts().OpenMPIsDevice) {
2116         Width = Target->getFloat128Width();
2117         Align = Target->getFloat128Align();
2118       } else {
2119         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2120                "Expected OpenMP device compilation.");
2121         Width = AuxTarget->getFloat128Width();
2122         Align = AuxTarget->getFloat128Align();
2123       }
2124       break;
2125     case BuiltinType::NullPtr:
2126       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2127       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2128       break;
2129     case BuiltinType::ObjCId:
2130     case BuiltinType::ObjCClass:
2131     case BuiltinType::ObjCSel:
2132       Width = Target->getPointerWidth(0);
2133       Align = Target->getPointerAlign(0);
2134       break;
2135     case BuiltinType::OCLSampler:
2136     case BuiltinType::OCLEvent:
2137     case BuiltinType::OCLClkEvent:
2138     case BuiltinType::OCLQueue:
2139     case BuiltinType::OCLReserveID:
2140 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2141     case BuiltinType::Id:
2142 #include "clang/Basic/OpenCLImageTypes.def"
2143 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2144   case BuiltinType::Id:
2145 #include "clang/Basic/OpenCLExtensionTypes.def"
2146       AS = getTargetAddressSpace(
2147           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2148       Width = Target->getPointerWidth(AS);
2149       Align = Target->getPointerAlign(AS);
2150       break;
2151     // The SVE types are effectively target-specific.  The length of an
2152     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2153     // of 128 bits.  There is one predicate bit for each vector byte, so the
2154     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2155     //
2156     // Because the length is only known at runtime, we use a dummy value
2157     // of 0 for the static length.  The alignment values are those defined
2158     // by the Procedure Call Standard for the Arm Architecture.
2159 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2160                         IsSigned, IsFP, IsBF)                                  \
2161   case BuiltinType::Id:                                                        \
2162     Width = 0;                                                                 \
2163     Align = 128;                                                               \
2164     break;
2165 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2166   case BuiltinType::Id:                                                        \
2167     Width = 0;                                                                 \
2168     Align = 16;                                                                \
2169     break;
2170 #include "clang/Basic/AArch64SVEACLETypes.def"
2171 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2172   case BuiltinType::Id:                                                        \
2173     Width = Size;                                                              \
2174     Align = Size;                                                              \
2175     break;
2176 #include "clang/Basic/PPCTypes.def"
2177 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2178                         IsFP)                                                  \
2179   case BuiltinType::Id:                                                        \
2180     Width = 0;                                                                 \
2181     Align = ElBits;                                                            \
2182     break;
2183 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2184   case BuiltinType::Id:                                                        \
2185     Width = 0;                                                                 \
2186     Align = 8;                                                                 \
2187     break;
2188 #include "clang/Basic/RISCVVTypes.def"
2189     }
2190     break;
2191   case Type::ObjCObjectPointer:
2192     Width = Target->getPointerWidth(0);
2193     Align = Target->getPointerAlign(0);
2194     break;
2195   case Type::BlockPointer:
2196     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2197     Width = Target->getPointerWidth(AS);
2198     Align = Target->getPointerAlign(AS);
2199     break;
2200   case Type::LValueReference:
2201   case Type::RValueReference:
2202     // alignof and sizeof should never enter this code path here, so we go
2203     // the pointer route.
2204     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2205     Width = Target->getPointerWidth(AS);
2206     Align = Target->getPointerAlign(AS);
2207     break;
2208   case Type::Pointer:
2209     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2210     Width = Target->getPointerWidth(AS);
2211     Align = Target->getPointerAlign(AS);
2212     break;
2213   case Type::MemberPointer: {
2214     const auto *MPT = cast<MemberPointerType>(T);
2215     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2216     Width = MPI.Width;
2217     Align = MPI.Align;
2218     break;
2219   }
2220   case Type::Complex: {
2221     // Complex types have the same alignment as their elements, but twice the
2222     // size.
2223     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2224     Width = EltInfo.Width * 2;
2225     Align = EltInfo.Align;
2226     break;
2227   }
2228   case Type::ObjCObject:
2229     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2230   case Type::Adjusted:
2231   case Type::Decayed:
2232     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2233   case Type::ObjCInterface: {
2234     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2235     if (ObjCI->getDecl()->isInvalidDecl()) {
2236       Width = 8;
2237       Align = 8;
2238       break;
2239     }
2240     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2241     Width = toBits(Layout.getSize());
2242     Align = toBits(Layout.getAlignment());
2243     break;
2244   }
2245   case Type::ExtInt: {
2246     const auto *EIT = cast<ExtIntType>(T);
2247     Align =
2248         std::min(static_cast<unsigned>(std::max(
2249                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2250                  Target->getLongLongAlign());
2251     Width = llvm::alignTo(EIT->getNumBits(), Align);
2252     break;
2253   }
2254   case Type::Record:
2255   case Type::Enum: {
2256     const auto *TT = cast<TagType>(T);
2257 
2258     if (TT->getDecl()->isInvalidDecl()) {
2259       Width = 8;
2260       Align = 8;
2261       break;
2262     }
2263 
2264     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2265       const EnumDecl *ED = ET->getDecl();
2266       TypeInfo Info =
2267           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2268       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2269         Info.Align = AttrAlign;
2270         Info.AlignIsRequired = true;
2271       }
2272       return Info;
2273     }
2274 
2275     const auto *RT = cast<RecordType>(TT);
2276     const RecordDecl *RD = RT->getDecl();
2277     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2278     Width = toBits(Layout.getSize());
2279     Align = toBits(Layout.getAlignment());
2280     AlignIsRequired = RD->hasAttr<AlignedAttr>();
2281     break;
2282   }
2283 
2284   case Type::SubstTemplateTypeParm:
2285     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2286                        getReplacementType().getTypePtr());
2287 
2288   case Type::Auto:
2289   case Type::DeducedTemplateSpecialization: {
2290     const auto *A = cast<DeducedType>(T);
2291     assert(!A->getDeducedType().isNull() &&
2292            "cannot request the size of an undeduced or dependent auto type");
2293     return getTypeInfo(A->getDeducedType().getTypePtr());
2294   }
2295 
2296   case Type::Paren:
2297     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2298 
2299   case Type::MacroQualified:
2300     return getTypeInfo(
2301         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2302 
2303   case Type::ObjCTypeParam:
2304     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2305 
2306   case Type::Typedef: {
2307     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2308     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2309     // If the typedef has an aligned attribute on it, it overrides any computed
2310     // alignment we have.  This violates the GCC documentation (which says that
2311     // attribute(aligned) can only round up) but matches its implementation.
2312     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2313       Align = AttrAlign;
2314       AlignIsRequired = true;
2315     } else {
2316       Align = Info.Align;
2317       AlignIsRequired = Info.AlignIsRequired;
2318     }
2319     Width = Info.Width;
2320     break;
2321   }
2322 
2323   case Type::Elaborated:
2324     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2325 
2326   case Type::Attributed:
2327     return getTypeInfo(
2328                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2329 
2330   case Type::Atomic: {
2331     // Start with the base type information.
2332     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2333     Width = Info.Width;
2334     Align = Info.Align;
2335 
2336     if (!Width) {
2337       // An otherwise zero-sized type should still generate an
2338       // atomic operation.
2339       Width = Target->getCharWidth();
2340       assert(Align);
2341     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2342       // If the size of the type doesn't exceed the platform's max
2343       // atomic promotion width, make the size and alignment more
2344       // favorable to atomic operations:
2345 
2346       // Round the size up to a power of 2.
2347       if (!llvm::isPowerOf2_64(Width))
2348         Width = llvm::NextPowerOf2(Width);
2349 
2350       // Set the alignment equal to the size.
2351       Align = static_cast<unsigned>(Width);
2352     }
2353   }
2354   break;
2355 
2356   case Type::Pipe:
2357     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2358     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2359     break;
2360   }
2361 
2362   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2363   return TypeInfo(Width, Align, AlignIsRequired);
2364 }
2365 
2366 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2367   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2368   if (I != MemoizedUnadjustedAlign.end())
2369     return I->second;
2370 
2371   unsigned UnadjustedAlign;
2372   if (const auto *RT = T->getAs<RecordType>()) {
2373     const RecordDecl *RD = RT->getDecl();
2374     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2375     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2376   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2377     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2378     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2379   } else {
2380     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2381   }
2382 
2383   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2384   return UnadjustedAlign;
2385 }
2386 
2387 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2388   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2389   return SimdAlign;
2390 }
2391 
2392 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2393 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2394   return CharUnits::fromQuantity(BitSize / getCharWidth());
2395 }
2396 
2397 /// toBits - Convert a size in characters to a size in characters.
2398 int64_t ASTContext::toBits(CharUnits CharSize) const {
2399   return CharSize.getQuantity() * getCharWidth();
2400 }
2401 
2402 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2403 /// This method does not work on incomplete types.
2404 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2405   return getTypeInfoInChars(T).Width;
2406 }
2407 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2408   return getTypeInfoInChars(T).Width;
2409 }
2410 
2411 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2412 /// characters. This method does not work on incomplete types.
2413 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2414   return toCharUnitsFromBits(getTypeAlign(T));
2415 }
2416 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2417   return toCharUnitsFromBits(getTypeAlign(T));
2418 }
2419 
2420 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2421 /// type, in characters, before alignment adustments. This method does
2422 /// not work on incomplete types.
2423 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2424   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2425 }
2426 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2427   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2428 }
2429 
2430 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2431 /// type for the current target in bits.  This can be different than the ABI
2432 /// alignment in cases where it is beneficial for performance or backwards
2433 /// compatibility preserving to overalign a data type. (Note: despite the name,
2434 /// the preferred alignment is ABI-impacting, and not an optimization.)
2435 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2436   TypeInfo TI = getTypeInfo(T);
2437   unsigned ABIAlign = TI.Align;
2438 
2439   T = T->getBaseElementTypeUnsafe();
2440 
2441   // The preferred alignment of member pointers is that of a pointer.
2442   if (T->isMemberPointerType())
2443     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2444 
2445   if (!Target->allowsLargerPreferedTypeAlignment())
2446     return ABIAlign;
2447 
2448   if (const auto *RT = T->getAs<RecordType>()) {
2449     if (TI.AlignIsRequired || RT->getDecl()->isInvalidDecl())
2450       return ABIAlign;
2451 
2452     unsigned PreferredAlign = static_cast<unsigned>(
2453         toBits(getASTRecordLayout(RT->getDecl()).PreferredAlignment));
2454     assert(PreferredAlign >= ABIAlign &&
2455            "PreferredAlign should be at least as large as ABIAlign.");
2456     return PreferredAlign;
2457   }
2458 
2459   // Double (and, for targets supporting AIX `power` alignment, long double) and
2460   // long long should be naturally aligned (despite requiring less alignment) if
2461   // possible.
2462   if (const auto *CT = T->getAs<ComplexType>())
2463     T = CT->getElementType().getTypePtr();
2464   if (const auto *ET = T->getAs<EnumType>())
2465     T = ET->getDecl()->getIntegerType().getTypePtr();
2466   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2467       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2468       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2469       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2470        Target->defaultsToAIXPowerAlignment()))
2471     // Don't increase the alignment if an alignment attribute was specified on a
2472     // typedef declaration.
2473     if (!TI.AlignIsRequired)
2474       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2475 
2476   return ABIAlign;
2477 }
2478 
2479 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2480 /// for __attribute__((aligned)) on this target, to be used if no alignment
2481 /// value is specified.
2482 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2483   return getTargetInfo().getDefaultAlignForAttributeAligned();
2484 }
2485 
2486 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2487 /// to a global variable of the specified type.
2488 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2489   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2490   return std::max(getPreferredTypeAlign(T),
2491                   getTargetInfo().getMinGlobalAlign(TypeSize));
2492 }
2493 
2494 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2495 /// should be given to a global variable of the specified type.
2496 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2497   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2498 }
2499 
2500 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2501   CharUnits Offset = CharUnits::Zero();
2502   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2503   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2504     Offset += Layout->getBaseClassOffset(Base);
2505     Layout = &getASTRecordLayout(Base);
2506   }
2507   return Offset;
2508 }
2509 
2510 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2511   const ValueDecl *MPD = MP.getMemberPointerDecl();
2512   CharUnits ThisAdjustment = CharUnits::Zero();
2513   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2514   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2515   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2516   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2517     const CXXRecordDecl *Base = RD;
2518     const CXXRecordDecl *Derived = Path[I];
2519     if (DerivedMember)
2520       std::swap(Base, Derived);
2521     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2522     RD = Path[I];
2523   }
2524   if (DerivedMember)
2525     ThisAdjustment = -ThisAdjustment;
2526   return ThisAdjustment;
2527 }
2528 
2529 /// DeepCollectObjCIvars -
2530 /// This routine first collects all declared, but not synthesized, ivars in
2531 /// super class and then collects all ivars, including those synthesized for
2532 /// current class. This routine is used for implementation of current class
2533 /// when all ivars, declared and synthesized are known.
2534 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2535                                       bool leafClass,
2536                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2537   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2538     DeepCollectObjCIvars(SuperClass, false, Ivars);
2539   if (!leafClass) {
2540     for (const auto *I : OI->ivars())
2541       Ivars.push_back(I);
2542   } else {
2543     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2544     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2545          Iv= Iv->getNextIvar())
2546       Ivars.push_back(Iv);
2547   }
2548 }
2549 
2550 /// CollectInheritedProtocols - Collect all protocols in current class and
2551 /// those inherited by it.
2552 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2553                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2554   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2555     // We can use protocol_iterator here instead of
2556     // all_referenced_protocol_iterator since we are walking all categories.
2557     for (auto *Proto : OI->all_referenced_protocols()) {
2558       CollectInheritedProtocols(Proto, Protocols);
2559     }
2560 
2561     // Categories of this Interface.
2562     for (const auto *Cat : OI->visible_categories())
2563       CollectInheritedProtocols(Cat, Protocols);
2564 
2565     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2566       while (SD) {
2567         CollectInheritedProtocols(SD, Protocols);
2568         SD = SD->getSuperClass();
2569       }
2570   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2571     for (auto *Proto : OC->protocols()) {
2572       CollectInheritedProtocols(Proto, Protocols);
2573     }
2574   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2575     // Insert the protocol.
2576     if (!Protocols.insert(
2577           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2578       return;
2579 
2580     for (auto *Proto : OP->protocols())
2581       CollectInheritedProtocols(Proto, Protocols);
2582   }
2583 }
2584 
2585 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2586                                                 const RecordDecl *RD) {
2587   assert(RD->isUnion() && "Must be union type");
2588   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2589 
2590   for (const auto *Field : RD->fields()) {
2591     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2592       return false;
2593     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2594     if (FieldSize != UnionSize)
2595       return false;
2596   }
2597   return !RD->field_empty();
2598 }
2599 
2600 static bool isStructEmpty(QualType Ty) {
2601   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2602 
2603   if (!RD->field_empty())
2604     return false;
2605 
2606   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2607     return ClassDecl->isEmpty();
2608 
2609   return true;
2610 }
2611 
2612 static llvm::Optional<int64_t>
2613 structHasUniqueObjectRepresentations(const ASTContext &Context,
2614                                      const RecordDecl *RD) {
2615   assert(!RD->isUnion() && "Must be struct/class type");
2616   const auto &Layout = Context.getASTRecordLayout(RD);
2617 
2618   int64_t CurOffsetInBits = 0;
2619   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2620     if (ClassDecl->isDynamicClass())
2621       return llvm::None;
2622 
2623     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2624     for (const auto &Base : ClassDecl->bases()) {
2625       // Empty types can be inherited from, and non-empty types can potentially
2626       // have tail padding, so just make sure there isn't an error.
2627       if (!isStructEmpty(Base.getType())) {
2628         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2629             Context, Base.getType()->castAs<RecordType>()->getDecl());
2630         if (!Size)
2631           return llvm::None;
2632         Bases.emplace_back(Base.getType(), Size.getValue());
2633       }
2634     }
2635 
2636     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2637                           const std::pair<QualType, int64_t> &R) {
2638       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2639              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2640     });
2641 
2642     for (const auto &Base : Bases) {
2643       int64_t BaseOffset = Context.toBits(
2644           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2645       int64_t BaseSize = Base.second;
2646       if (BaseOffset != CurOffsetInBits)
2647         return llvm::None;
2648       CurOffsetInBits = BaseOffset + BaseSize;
2649     }
2650   }
2651 
2652   for (const auto *Field : RD->fields()) {
2653     if (!Field->getType()->isReferenceType() &&
2654         !Context.hasUniqueObjectRepresentations(Field->getType()))
2655       return llvm::None;
2656 
2657     int64_t FieldSizeInBits =
2658         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2659     if (Field->isBitField()) {
2660       int64_t BitfieldSize = Field->getBitWidthValue(Context);
2661 
2662       if (BitfieldSize > FieldSizeInBits)
2663         return llvm::None;
2664       FieldSizeInBits = BitfieldSize;
2665     }
2666 
2667     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2668 
2669     if (FieldOffsetInBits != CurOffsetInBits)
2670       return llvm::None;
2671 
2672     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2673   }
2674 
2675   return CurOffsetInBits;
2676 }
2677 
2678 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2679   // C++17 [meta.unary.prop]:
2680   //   The predicate condition for a template specialization
2681   //   has_unique_object_representations<T> shall be
2682   //   satisfied if and only if:
2683   //     (9.1) - T is trivially copyable, and
2684   //     (9.2) - any two objects of type T with the same value have the same
2685   //     object representation, where two objects
2686   //   of array or non-union class type are considered to have the same value
2687   //   if their respective sequences of
2688   //   direct subobjects have the same values, and two objects of union type
2689   //   are considered to have the same
2690   //   value if they have the same active member and the corresponding members
2691   //   have the same value.
2692   //   The set of scalar types for which this condition holds is
2693   //   implementation-defined. [ Note: If a type has padding
2694   //   bits, the condition does not hold; otherwise, the condition holds true
2695   //   for unsigned integral types. -- end note ]
2696   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2697 
2698   // Arrays are unique only if their element type is unique.
2699   if (Ty->isArrayType())
2700     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2701 
2702   // (9.1) - T is trivially copyable...
2703   if (!Ty.isTriviallyCopyableType(*this))
2704     return false;
2705 
2706   // All integrals and enums are unique.
2707   if (Ty->isIntegralOrEnumerationType())
2708     return true;
2709 
2710   // All other pointers are unique.
2711   if (Ty->isPointerType())
2712     return true;
2713 
2714   if (Ty->isMemberPointerType()) {
2715     const auto *MPT = Ty->getAs<MemberPointerType>();
2716     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2717   }
2718 
2719   if (Ty->isRecordType()) {
2720     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2721 
2722     if (Record->isInvalidDecl())
2723       return false;
2724 
2725     if (Record->isUnion())
2726       return unionHasUniqueObjectRepresentations(*this, Record);
2727 
2728     Optional<int64_t> StructSize =
2729         structHasUniqueObjectRepresentations(*this, Record);
2730 
2731     return StructSize &&
2732            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2733   }
2734 
2735   // FIXME: More cases to handle here (list by rsmith):
2736   // vectors (careful about, eg, vector of 3 foo)
2737   // _Complex int and friends
2738   // _Atomic T
2739   // Obj-C block pointers
2740   // Obj-C object pointers
2741   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2742   // clk_event_t, queue_t, reserve_id_t)
2743   // There're also Obj-C class types and the Obj-C selector type, but I think it
2744   // makes sense for those to return false here.
2745 
2746   return false;
2747 }
2748 
2749 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2750   unsigned count = 0;
2751   // Count ivars declared in class extension.
2752   for (const auto *Ext : OI->known_extensions())
2753     count += Ext->ivar_size();
2754 
2755   // Count ivar defined in this class's implementation.  This
2756   // includes synthesized ivars.
2757   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2758     count += ImplDecl->ivar_size();
2759 
2760   return count;
2761 }
2762 
2763 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2764   if (!E)
2765     return false;
2766 
2767   // nullptr_t is always treated as null.
2768   if (E->getType()->isNullPtrType()) return true;
2769 
2770   if (E->getType()->isAnyPointerType() &&
2771       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2772                                                 Expr::NPC_ValueDependentIsNull))
2773     return true;
2774 
2775   // Unfortunately, __null has type 'int'.
2776   if (isa<GNUNullExpr>(E)) return true;
2777 
2778   return false;
2779 }
2780 
2781 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2782 /// exists.
2783 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2784   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2785     I = ObjCImpls.find(D);
2786   if (I != ObjCImpls.end())
2787     return cast<ObjCImplementationDecl>(I->second);
2788   return nullptr;
2789 }
2790 
2791 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2792 /// exists.
2793 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2794   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2795     I = ObjCImpls.find(D);
2796   if (I != ObjCImpls.end())
2797     return cast<ObjCCategoryImplDecl>(I->second);
2798   return nullptr;
2799 }
2800 
2801 /// Set the implementation of ObjCInterfaceDecl.
2802 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2803                            ObjCImplementationDecl *ImplD) {
2804   assert(IFaceD && ImplD && "Passed null params");
2805   ObjCImpls[IFaceD] = ImplD;
2806 }
2807 
2808 /// Set the implementation of ObjCCategoryDecl.
2809 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2810                            ObjCCategoryImplDecl *ImplD) {
2811   assert(CatD && ImplD && "Passed null params");
2812   ObjCImpls[CatD] = ImplD;
2813 }
2814 
2815 const ObjCMethodDecl *
2816 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2817   return ObjCMethodRedecls.lookup(MD);
2818 }
2819 
2820 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2821                                             const ObjCMethodDecl *Redecl) {
2822   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2823   ObjCMethodRedecls[MD] = Redecl;
2824 }
2825 
2826 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2827                                               const NamedDecl *ND) const {
2828   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2829     return ID;
2830   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2831     return CD->getClassInterface();
2832   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2833     return IMD->getClassInterface();
2834 
2835   return nullptr;
2836 }
2837 
2838 /// Get the copy initialization expression of VarDecl, or nullptr if
2839 /// none exists.
2840 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2841   assert(VD && "Passed null params");
2842   assert(VD->hasAttr<BlocksAttr>() &&
2843          "getBlockVarCopyInits - not __block var");
2844   auto I = BlockVarCopyInits.find(VD);
2845   if (I != BlockVarCopyInits.end())
2846     return I->second;
2847   return {nullptr, false};
2848 }
2849 
2850 /// Set the copy initialization expression of a block var decl.
2851 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2852                                      bool CanThrow) {
2853   assert(VD && CopyExpr && "Passed null params");
2854   assert(VD->hasAttr<BlocksAttr>() &&
2855          "setBlockVarCopyInits - not __block var");
2856   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2857 }
2858 
2859 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2860                                                  unsigned DataSize) const {
2861   if (!DataSize)
2862     DataSize = TypeLoc::getFullDataSizeForType(T);
2863   else
2864     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2865            "incorrect data size provided to CreateTypeSourceInfo!");
2866 
2867   auto *TInfo =
2868     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2869   new (TInfo) TypeSourceInfo(T);
2870   return TInfo;
2871 }
2872 
2873 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2874                                                      SourceLocation L) const {
2875   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2876   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2877   return DI;
2878 }
2879 
2880 const ASTRecordLayout &
2881 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2882   return getObjCLayout(D, nullptr);
2883 }
2884 
2885 const ASTRecordLayout &
2886 ASTContext::getASTObjCImplementationLayout(
2887                                         const ObjCImplementationDecl *D) const {
2888   return getObjCLayout(D->getClassInterface(), D);
2889 }
2890 
2891 //===----------------------------------------------------------------------===//
2892 //                   Type creation/memoization methods
2893 //===----------------------------------------------------------------------===//
2894 
2895 QualType
2896 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2897   unsigned fastQuals = quals.getFastQualifiers();
2898   quals.removeFastQualifiers();
2899 
2900   // Check if we've already instantiated this type.
2901   llvm::FoldingSetNodeID ID;
2902   ExtQuals::Profile(ID, baseType, quals);
2903   void *insertPos = nullptr;
2904   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2905     assert(eq->getQualifiers() == quals);
2906     return QualType(eq, fastQuals);
2907   }
2908 
2909   // If the base type is not canonical, make the appropriate canonical type.
2910   QualType canon;
2911   if (!baseType->isCanonicalUnqualified()) {
2912     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2913     canonSplit.Quals.addConsistentQualifiers(quals);
2914     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2915 
2916     // Re-find the insert position.
2917     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2918   }
2919 
2920   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2921   ExtQualNodes.InsertNode(eq, insertPos);
2922   return QualType(eq, fastQuals);
2923 }
2924 
2925 QualType ASTContext::getAddrSpaceQualType(QualType T,
2926                                           LangAS AddressSpace) const {
2927   QualType CanT = getCanonicalType(T);
2928   if (CanT.getAddressSpace() == AddressSpace)
2929     return T;
2930 
2931   // If we are composing extended qualifiers together, merge together
2932   // into one ExtQuals node.
2933   QualifierCollector Quals;
2934   const Type *TypeNode = Quals.strip(T);
2935 
2936   // If this type already has an address space specified, it cannot get
2937   // another one.
2938   assert(!Quals.hasAddressSpace() &&
2939          "Type cannot be in multiple addr spaces!");
2940   Quals.addAddressSpace(AddressSpace);
2941 
2942   return getExtQualType(TypeNode, Quals);
2943 }
2944 
2945 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2946   // If the type is not qualified with an address space, just return it
2947   // immediately.
2948   if (!T.hasAddressSpace())
2949     return T;
2950 
2951   // If we are composing extended qualifiers together, merge together
2952   // into one ExtQuals node.
2953   QualifierCollector Quals;
2954   const Type *TypeNode;
2955 
2956   while (T.hasAddressSpace()) {
2957     TypeNode = Quals.strip(T);
2958 
2959     // If the type no longer has an address space after stripping qualifiers,
2960     // jump out.
2961     if (!QualType(TypeNode, 0).hasAddressSpace())
2962       break;
2963 
2964     // There might be sugar in the way. Strip it and try again.
2965     T = T.getSingleStepDesugaredType(*this);
2966   }
2967 
2968   Quals.removeAddressSpace();
2969 
2970   // Removal of the address space can mean there are no longer any
2971   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2972   // or required.
2973   if (Quals.hasNonFastQualifiers())
2974     return getExtQualType(TypeNode, Quals);
2975   else
2976     return QualType(TypeNode, Quals.getFastQualifiers());
2977 }
2978 
2979 QualType ASTContext::getObjCGCQualType(QualType T,
2980                                        Qualifiers::GC GCAttr) const {
2981   QualType CanT = getCanonicalType(T);
2982   if (CanT.getObjCGCAttr() == GCAttr)
2983     return T;
2984 
2985   if (const auto *ptr = T->getAs<PointerType>()) {
2986     QualType Pointee = ptr->getPointeeType();
2987     if (Pointee->isAnyPointerType()) {
2988       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2989       return getPointerType(ResultType);
2990     }
2991   }
2992 
2993   // If we are composing extended qualifiers together, merge together
2994   // into one ExtQuals node.
2995   QualifierCollector Quals;
2996   const Type *TypeNode = Quals.strip(T);
2997 
2998   // If this type already has an ObjCGC specified, it cannot get
2999   // another one.
3000   assert(!Quals.hasObjCGCAttr() &&
3001          "Type cannot have multiple ObjCGCs!");
3002   Quals.addObjCGCAttr(GCAttr);
3003 
3004   return getExtQualType(TypeNode, Quals);
3005 }
3006 
3007 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3008   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3009     QualType Pointee = Ptr->getPointeeType();
3010     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3011       return getPointerType(removeAddrSpaceQualType(Pointee));
3012     }
3013   }
3014   return T;
3015 }
3016 
3017 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3018                                                    FunctionType::ExtInfo Info) {
3019   if (T->getExtInfo() == Info)
3020     return T;
3021 
3022   QualType Result;
3023   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3024     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3025   } else {
3026     const auto *FPT = cast<FunctionProtoType>(T);
3027     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3028     EPI.ExtInfo = Info;
3029     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3030   }
3031 
3032   return cast<FunctionType>(Result.getTypePtr());
3033 }
3034 
3035 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3036                                                  QualType ResultType) {
3037   FD = FD->getMostRecentDecl();
3038   while (true) {
3039     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3040     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3041     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3042     if (FunctionDecl *Next = FD->getPreviousDecl())
3043       FD = Next;
3044     else
3045       break;
3046   }
3047   if (ASTMutationListener *L = getASTMutationListener())
3048     L->DeducedReturnType(FD, ResultType);
3049 }
3050 
3051 /// Get a function type and produce the equivalent function type with the
3052 /// specified exception specification. Type sugar that can be present on a
3053 /// declaration of a function with an exception specification is permitted
3054 /// and preserved. Other type sugar (for instance, typedefs) is not.
3055 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3056     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3057   // Might have some parens.
3058   if (const auto *PT = dyn_cast<ParenType>(Orig))
3059     return getParenType(
3060         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3061 
3062   // Might be wrapped in a macro qualified type.
3063   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3064     return getMacroQualifiedType(
3065         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3066         MQT->getMacroIdentifier());
3067 
3068   // Might have a calling-convention attribute.
3069   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3070     return getAttributedType(
3071         AT->getAttrKind(),
3072         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3073         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3074 
3075   // Anything else must be a function type. Rebuild it with the new exception
3076   // specification.
3077   const auto *Proto = Orig->castAs<FunctionProtoType>();
3078   return getFunctionType(
3079       Proto->getReturnType(), Proto->getParamTypes(),
3080       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3081 }
3082 
3083 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3084                                                           QualType U) {
3085   return hasSameType(T, U) ||
3086          (getLangOpts().CPlusPlus17 &&
3087           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3088                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3089 }
3090 
3091 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3092   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3093     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3094     SmallVector<QualType, 16> Args(Proto->param_types());
3095     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3096       Args[i] = removePtrSizeAddrSpace(Args[i]);
3097     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3098   }
3099 
3100   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3101     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3102     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3103   }
3104 
3105   return T;
3106 }
3107 
3108 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3109   return hasSameType(T, U) ||
3110          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3111                      getFunctionTypeWithoutPtrSizes(U));
3112 }
3113 
3114 void ASTContext::adjustExceptionSpec(
3115     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3116     bool AsWritten) {
3117   // Update the type.
3118   QualType Updated =
3119       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3120   FD->setType(Updated);
3121 
3122   if (!AsWritten)
3123     return;
3124 
3125   // Update the type in the type source information too.
3126   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3127     // If the type and the type-as-written differ, we may need to update
3128     // the type-as-written too.
3129     if (TSInfo->getType() != FD->getType())
3130       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3131 
3132     // FIXME: When we get proper type location information for exceptions,
3133     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3134     // up the TypeSourceInfo;
3135     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3136                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3137            "TypeLoc size mismatch from updating exception specification");
3138     TSInfo->overrideType(Updated);
3139   }
3140 }
3141 
3142 /// getComplexType - Return the uniqued reference to the type for a complex
3143 /// number with the specified element type.
3144 QualType ASTContext::getComplexType(QualType T) const {
3145   // Unique pointers, to guarantee there is only one pointer of a particular
3146   // structure.
3147   llvm::FoldingSetNodeID ID;
3148   ComplexType::Profile(ID, T);
3149 
3150   void *InsertPos = nullptr;
3151   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3152     return QualType(CT, 0);
3153 
3154   // If the pointee type isn't canonical, this won't be a canonical type either,
3155   // so fill in the canonical type field.
3156   QualType Canonical;
3157   if (!T.isCanonical()) {
3158     Canonical = getComplexType(getCanonicalType(T));
3159 
3160     // Get the new insert position for the node we care about.
3161     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3162     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3163   }
3164   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3165   Types.push_back(New);
3166   ComplexTypes.InsertNode(New, InsertPos);
3167   return QualType(New, 0);
3168 }
3169 
3170 /// getPointerType - Return the uniqued reference to the type for a pointer to
3171 /// the specified type.
3172 QualType ASTContext::getPointerType(QualType T) const {
3173   // Unique pointers, to guarantee there is only one pointer of a particular
3174   // structure.
3175   llvm::FoldingSetNodeID ID;
3176   PointerType::Profile(ID, T);
3177 
3178   void *InsertPos = nullptr;
3179   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3180     return QualType(PT, 0);
3181 
3182   // If the pointee type isn't canonical, this won't be a canonical type either,
3183   // so fill in the canonical type field.
3184   QualType Canonical;
3185   if (!T.isCanonical()) {
3186     Canonical = getPointerType(getCanonicalType(T));
3187 
3188     // Get the new insert position for the node we care about.
3189     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3190     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3191   }
3192   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3193   Types.push_back(New);
3194   PointerTypes.InsertNode(New, InsertPos);
3195   return QualType(New, 0);
3196 }
3197 
3198 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3199   llvm::FoldingSetNodeID ID;
3200   AdjustedType::Profile(ID, Orig, New);
3201   void *InsertPos = nullptr;
3202   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3203   if (AT)
3204     return QualType(AT, 0);
3205 
3206   QualType Canonical = getCanonicalType(New);
3207 
3208   // Get the new insert position for the node we care about.
3209   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3210   assert(!AT && "Shouldn't be in the map!");
3211 
3212   AT = new (*this, TypeAlignment)
3213       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3214   Types.push_back(AT);
3215   AdjustedTypes.InsertNode(AT, InsertPos);
3216   return QualType(AT, 0);
3217 }
3218 
3219 QualType ASTContext::getDecayedType(QualType T) const {
3220   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3221 
3222   QualType Decayed;
3223 
3224   // C99 6.7.5.3p7:
3225   //   A declaration of a parameter as "array of type" shall be
3226   //   adjusted to "qualified pointer to type", where the type
3227   //   qualifiers (if any) are those specified within the [ and ] of
3228   //   the array type derivation.
3229   if (T->isArrayType())
3230     Decayed = getArrayDecayedType(T);
3231 
3232   // C99 6.7.5.3p8:
3233   //   A declaration of a parameter as "function returning type"
3234   //   shall be adjusted to "pointer to function returning type", as
3235   //   in 6.3.2.1.
3236   if (T->isFunctionType())
3237     Decayed = getPointerType(T);
3238 
3239   llvm::FoldingSetNodeID ID;
3240   AdjustedType::Profile(ID, T, Decayed);
3241   void *InsertPos = nullptr;
3242   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3243   if (AT)
3244     return QualType(AT, 0);
3245 
3246   QualType Canonical = getCanonicalType(Decayed);
3247 
3248   // Get the new insert position for the node we care about.
3249   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3250   assert(!AT && "Shouldn't be in the map!");
3251 
3252   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3253   Types.push_back(AT);
3254   AdjustedTypes.InsertNode(AT, InsertPos);
3255   return QualType(AT, 0);
3256 }
3257 
3258 /// getBlockPointerType - Return the uniqued reference to the type for
3259 /// a pointer to the specified block.
3260 QualType ASTContext::getBlockPointerType(QualType T) const {
3261   assert(T->isFunctionType() && "block of function types only");
3262   // Unique pointers, to guarantee there is only one block of a particular
3263   // structure.
3264   llvm::FoldingSetNodeID ID;
3265   BlockPointerType::Profile(ID, T);
3266 
3267   void *InsertPos = nullptr;
3268   if (BlockPointerType *PT =
3269         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3270     return QualType(PT, 0);
3271 
3272   // If the block pointee type isn't canonical, this won't be a canonical
3273   // type either so fill in the canonical type field.
3274   QualType Canonical;
3275   if (!T.isCanonical()) {
3276     Canonical = getBlockPointerType(getCanonicalType(T));
3277 
3278     // Get the new insert position for the node we care about.
3279     BlockPointerType *NewIP =
3280       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3281     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3282   }
3283   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3284   Types.push_back(New);
3285   BlockPointerTypes.InsertNode(New, InsertPos);
3286   return QualType(New, 0);
3287 }
3288 
3289 /// getLValueReferenceType - Return the uniqued reference to the type for an
3290 /// lvalue reference to the specified type.
3291 QualType
3292 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3293   assert(getCanonicalType(T) != OverloadTy &&
3294          "Unresolved overloaded function type");
3295 
3296   // Unique pointers, to guarantee there is only one pointer of a particular
3297   // structure.
3298   llvm::FoldingSetNodeID ID;
3299   ReferenceType::Profile(ID, T, SpelledAsLValue);
3300 
3301   void *InsertPos = nullptr;
3302   if (LValueReferenceType *RT =
3303         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3304     return QualType(RT, 0);
3305 
3306   const auto *InnerRef = T->getAs<ReferenceType>();
3307 
3308   // If the referencee type isn't canonical, this won't be a canonical type
3309   // either, so fill in the canonical type field.
3310   QualType Canonical;
3311   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3312     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3313     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3314 
3315     // Get the new insert position for the node we care about.
3316     LValueReferenceType *NewIP =
3317       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3318     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3319   }
3320 
3321   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3322                                                              SpelledAsLValue);
3323   Types.push_back(New);
3324   LValueReferenceTypes.InsertNode(New, InsertPos);
3325 
3326   return QualType(New, 0);
3327 }
3328 
3329 /// getRValueReferenceType - Return the uniqued reference to the type for an
3330 /// rvalue reference to the specified type.
3331 QualType ASTContext::getRValueReferenceType(QualType T) const {
3332   // Unique pointers, to guarantee there is only one pointer of a particular
3333   // structure.
3334   llvm::FoldingSetNodeID ID;
3335   ReferenceType::Profile(ID, T, false);
3336 
3337   void *InsertPos = nullptr;
3338   if (RValueReferenceType *RT =
3339         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3340     return QualType(RT, 0);
3341 
3342   const auto *InnerRef = T->getAs<ReferenceType>();
3343 
3344   // If the referencee type isn't canonical, this won't be a canonical type
3345   // either, so fill in the canonical type field.
3346   QualType Canonical;
3347   if (InnerRef || !T.isCanonical()) {
3348     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3349     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3350 
3351     // Get the new insert position for the node we care about.
3352     RValueReferenceType *NewIP =
3353       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3354     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3355   }
3356 
3357   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3358   Types.push_back(New);
3359   RValueReferenceTypes.InsertNode(New, InsertPos);
3360   return QualType(New, 0);
3361 }
3362 
3363 /// getMemberPointerType - Return the uniqued reference to the type for a
3364 /// member pointer to the specified type, in the specified class.
3365 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3366   // Unique pointers, to guarantee there is only one pointer of a particular
3367   // structure.
3368   llvm::FoldingSetNodeID ID;
3369   MemberPointerType::Profile(ID, T, Cls);
3370 
3371   void *InsertPos = nullptr;
3372   if (MemberPointerType *PT =
3373       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3374     return QualType(PT, 0);
3375 
3376   // If the pointee or class type isn't canonical, this won't be a canonical
3377   // type either, so fill in the canonical type field.
3378   QualType Canonical;
3379   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3380     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3381 
3382     // Get the new insert position for the node we care about.
3383     MemberPointerType *NewIP =
3384       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3385     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3386   }
3387   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3388   Types.push_back(New);
3389   MemberPointerTypes.InsertNode(New, InsertPos);
3390   return QualType(New, 0);
3391 }
3392 
3393 /// getConstantArrayType - Return the unique reference to the type for an
3394 /// array of the specified element type.
3395 QualType ASTContext::getConstantArrayType(QualType EltTy,
3396                                           const llvm::APInt &ArySizeIn,
3397                                           const Expr *SizeExpr,
3398                                           ArrayType::ArraySizeModifier ASM,
3399                                           unsigned IndexTypeQuals) const {
3400   assert((EltTy->isDependentType() ||
3401           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3402          "Constant array of VLAs is illegal!");
3403 
3404   // We only need the size as part of the type if it's instantiation-dependent.
3405   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3406     SizeExpr = nullptr;
3407 
3408   // Convert the array size into a canonical width matching the pointer size for
3409   // the target.
3410   llvm::APInt ArySize(ArySizeIn);
3411   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3412 
3413   llvm::FoldingSetNodeID ID;
3414   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3415                              IndexTypeQuals);
3416 
3417   void *InsertPos = nullptr;
3418   if (ConstantArrayType *ATP =
3419       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3420     return QualType(ATP, 0);
3421 
3422   // If the element type isn't canonical or has qualifiers, or the array bound
3423   // is instantiation-dependent, this won't be a canonical type either, so fill
3424   // in the canonical type field.
3425   QualType Canon;
3426   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3427     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3428     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3429                                  ASM, IndexTypeQuals);
3430     Canon = getQualifiedType(Canon, canonSplit.Quals);
3431 
3432     // Get the new insert position for the node we care about.
3433     ConstantArrayType *NewIP =
3434       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3435     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3436   }
3437 
3438   void *Mem = Allocate(
3439       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3440       TypeAlignment);
3441   auto *New = new (Mem)
3442     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3443   ConstantArrayTypes.InsertNode(New, InsertPos);
3444   Types.push_back(New);
3445   return QualType(New, 0);
3446 }
3447 
3448 /// getVariableArrayDecayedType - Turns the given type, which may be
3449 /// variably-modified, into the corresponding type with all the known
3450 /// sizes replaced with [*].
3451 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3452   // Vastly most common case.
3453   if (!type->isVariablyModifiedType()) return type;
3454 
3455   QualType result;
3456 
3457   SplitQualType split = type.getSplitDesugaredType();
3458   const Type *ty = split.Ty;
3459   switch (ty->getTypeClass()) {
3460 #define TYPE(Class, Base)
3461 #define ABSTRACT_TYPE(Class, Base)
3462 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3463 #include "clang/AST/TypeNodes.inc"
3464     llvm_unreachable("didn't desugar past all non-canonical types?");
3465 
3466   // These types should never be variably-modified.
3467   case Type::Builtin:
3468   case Type::Complex:
3469   case Type::Vector:
3470   case Type::DependentVector:
3471   case Type::ExtVector:
3472   case Type::DependentSizedExtVector:
3473   case Type::ConstantMatrix:
3474   case Type::DependentSizedMatrix:
3475   case Type::DependentAddressSpace:
3476   case Type::ObjCObject:
3477   case Type::ObjCInterface:
3478   case Type::ObjCObjectPointer:
3479   case Type::Record:
3480   case Type::Enum:
3481   case Type::UnresolvedUsing:
3482   case Type::TypeOfExpr:
3483   case Type::TypeOf:
3484   case Type::Decltype:
3485   case Type::UnaryTransform:
3486   case Type::DependentName:
3487   case Type::InjectedClassName:
3488   case Type::TemplateSpecialization:
3489   case Type::DependentTemplateSpecialization:
3490   case Type::TemplateTypeParm:
3491   case Type::SubstTemplateTypeParmPack:
3492   case Type::Auto:
3493   case Type::DeducedTemplateSpecialization:
3494   case Type::PackExpansion:
3495   case Type::ExtInt:
3496   case Type::DependentExtInt:
3497     llvm_unreachable("type should never be variably-modified");
3498 
3499   // These types can be variably-modified but should never need to
3500   // further decay.
3501   case Type::FunctionNoProto:
3502   case Type::FunctionProto:
3503   case Type::BlockPointer:
3504   case Type::MemberPointer:
3505   case Type::Pipe:
3506     return type;
3507 
3508   // These types can be variably-modified.  All these modifications
3509   // preserve structure except as noted by comments.
3510   // TODO: if we ever care about optimizing VLAs, there are no-op
3511   // optimizations available here.
3512   case Type::Pointer:
3513     result = getPointerType(getVariableArrayDecayedType(
3514                               cast<PointerType>(ty)->getPointeeType()));
3515     break;
3516 
3517   case Type::LValueReference: {
3518     const auto *lv = cast<LValueReferenceType>(ty);
3519     result = getLValueReferenceType(
3520                  getVariableArrayDecayedType(lv->getPointeeType()),
3521                                     lv->isSpelledAsLValue());
3522     break;
3523   }
3524 
3525   case Type::RValueReference: {
3526     const auto *lv = cast<RValueReferenceType>(ty);
3527     result = getRValueReferenceType(
3528                  getVariableArrayDecayedType(lv->getPointeeType()));
3529     break;
3530   }
3531 
3532   case Type::Atomic: {
3533     const auto *at = cast<AtomicType>(ty);
3534     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3535     break;
3536   }
3537 
3538   case Type::ConstantArray: {
3539     const auto *cat = cast<ConstantArrayType>(ty);
3540     result = getConstantArrayType(
3541                  getVariableArrayDecayedType(cat->getElementType()),
3542                                   cat->getSize(),
3543                                   cat->getSizeExpr(),
3544                                   cat->getSizeModifier(),
3545                                   cat->getIndexTypeCVRQualifiers());
3546     break;
3547   }
3548 
3549   case Type::DependentSizedArray: {
3550     const auto *dat = cast<DependentSizedArrayType>(ty);
3551     result = getDependentSizedArrayType(
3552                  getVariableArrayDecayedType(dat->getElementType()),
3553                                         dat->getSizeExpr(),
3554                                         dat->getSizeModifier(),
3555                                         dat->getIndexTypeCVRQualifiers(),
3556                                         dat->getBracketsRange());
3557     break;
3558   }
3559 
3560   // Turn incomplete types into [*] types.
3561   case Type::IncompleteArray: {
3562     const auto *iat = cast<IncompleteArrayType>(ty);
3563     result = getVariableArrayType(
3564                  getVariableArrayDecayedType(iat->getElementType()),
3565                                   /*size*/ nullptr,
3566                                   ArrayType::Normal,
3567                                   iat->getIndexTypeCVRQualifiers(),
3568                                   SourceRange());
3569     break;
3570   }
3571 
3572   // Turn VLA types into [*] types.
3573   case Type::VariableArray: {
3574     const auto *vat = cast<VariableArrayType>(ty);
3575     result = getVariableArrayType(
3576                  getVariableArrayDecayedType(vat->getElementType()),
3577                                   /*size*/ nullptr,
3578                                   ArrayType::Star,
3579                                   vat->getIndexTypeCVRQualifiers(),
3580                                   vat->getBracketsRange());
3581     break;
3582   }
3583   }
3584 
3585   // Apply the top-level qualifiers from the original.
3586   return getQualifiedType(result, split.Quals);
3587 }
3588 
3589 /// getVariableArrayType - Returns a non-unique reference to the type for a
3590 /// variable array of the specified element type.
3591 QualType ASTContext::getVariableArrayType(QualType EltTy,
3592                                           Expr *NumElts,
3593                                           ArrayType::ArraySizeModifier ASM,
3594                                           unsigned IndexTypeQuals,
3595                                           SourceRange Brackets) const {
3596   // Since we don't unique expressions, it isn't possible to unique VLA's
3597   // that have an expression provided for their size.
3598   QualType Canon;
3599 
3600   // Be sure to pull qualifiers off the element type.
3601   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3602     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3603     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3604                                  IndexTypeQuals, Brackets);
3605     Canon = getQualifiedType(Canon, canonSplit.Quals);
3606   }
3607 
3608   auto *New = new (*this, TypeAlignment)
3609     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3610 
3611   VariableArrayTypes.push_back(New);
3612   Types.push_back(New);
3613   return QualType(New, 0);
3614 }
3615 
3616 /// getDependentSizedArrayType - Returns a non-unique reference to
3617 /// the type for a dependently-sized array of the specified element
3618 /// type.
3619 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3620                                                 Expr *numElements,
3621                                                 ArrayType::ArraySizeModifier ASM,
3622                                                 unsigned elementTypeQuals,
3623                                                 SourceRange brackets) const {
3624   assert((!numElements || numElements->isTypeDependent() ||
3625           numElements->isValueDependent()) &&
3626          "Size must be type- or value-dependent!");
3627 
3628   // Dependently-sized array types that do not have a specified number
3629   // of elements will have their sizes deduced from a dependent
3630   // initializer.  We do no canonicalization here at all, which is okay
3631   // because they can't be used in most locations.
3632   if (!numElements) {
3633     auto *newType
3634       = new (*this, TypeAlignment)
3635           DependentSizedArrayType(*this, elementType, QualType(),
3636                                   numElements, ASM, elementTypeQuals,
3637                                   brackets);
3638     Types.push_back(newType);
3639     return QualType(newType, 0);
3640   }
3641 
3642   // Otherwise, we actually build a new type every time, but we
3643   // also build a canonical type.
3644 
3645   SplitQualType canonElementType = getCanonicalType(elementType).split();
3646 
3647   void *insertPos = nullptr;
3648   llvm::FoldingSetNodeID ID;
3649   DependentSizedArrayType::Profile(ID, *this,
3650                                    QualType(canonElementType.Ty, 0),
3651                                    ASM, elementTypeQuals, numElements);
3652 
3653   // Look for an existing type with these properties.
3654   DependentSizedArrayType *canonTy =
3655     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3656 
3657   // If we don't have one, build one.
3658   if (!canonTy) {
3659     canonTy = new (*this, TypeAlignment)
3660       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3661                               QualType(), numElements, ASM, elementTypeQuals,
3662                               brackets);
3663     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3664     Types.push_back(canonTy);
3665   }
3666 
3667   // Apply qualifiers from the element type to the array.
3668   QualType canon = getQualifiedType(QualType(canonTy,0),
3669                                     canonElementType.Quals);
3670 
3671   // If we didn't need extra canonicalization for the element type or the size
3672   // expression, then just use that as our result.
3673   if (QualType(canonElementType.Ty, 0) == elementType &&
3674       canonTy->getSizeExpr() == numElements)
3675     return canon;
3676 
3677   // Otherwise, we need to build a type which follows the spelling
3678   // of the element type.
3679   auto *sugaredType
3680     = new (*this, TypeAlignment)
3681         DependentSizedArrayType(*this, elementType, canon, numElements,
3682                                 ASM, elementTypeQuals, brackets);
3683   Types.push_back(sugaredType);
3684   return QualType(sugaredType, 0);
3685 }
3686 
3687 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3688                                             ArrayType::ArraySizeModifier ASM,
3689                                             unsigned elementTypeQuals) const {
3690   llvm::FoldingSetNodeID ID;
3691   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3692 
3693   void *insertPos = nullptr;
3694   if (IncompleteArrayType *iat =
3695        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3696     return QualType(iat, 0);
3697 
3698   // If the element type isn't canonical, this won't be a canonical type
3699   // either, so fill in the canonical type field.  We also have to pull
3700   // qualifiers off the element type.
3701   QualType canon;
3702 
3703   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3704     SplitQualType canonSplit = getCanonicalType(elementType).split();
3705     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3706                                    ASM, elementTypeQuals);
3707     canon = getQualifiedType(canon, canonSplit.Quals);
3708 
3709     // Get the new insert position for the node we care about.
3710     IncompleteArrayType *existing =
3711       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3712     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3713   }
3714 
3715   auto *newType = new (*this, TypeAlignment)
3716     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3717 
3718   IncompleteArrayTypes.InsertNode(newType, insertPos);
3719   Types.push_back(newType);
3720   return QualType(newType, 0);
3721 }
3722 
3723 ASTContext::BuiltinVectorTypeInfo
3724 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3725 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3726   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3727    NUMVECTORS};
3728 
3729 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3730   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3731 
3732   switch (Ty->getKind()) {
3733   default:
3734     llvm_unreachable("Unsupported builtin vector type");
3735   case BuiltinType::SveInt8:
3736     return SVE_INT_ELTTY(8, 16, true, 1);
3737   case BuiltinType::SveUint8:
3738     return SVE_INT_ELTTY(8, 16, false, 1);
3739   case BuiltinType::SveInt8x2:
3740     return SVE_INT_ELTTY(8, 16, true, 2);
3741   case BuiltinType::SveUint8x2:
3742     return SVE_INT_ELTTY(8, 16, false, 2);
3743   case BuiltinType::SveInt8x3:
3744     return SVE_INT_ELTTY(8, 16, true, 3);
3745   case BuiltinType::SveUint8x3:
3746     return SVE_INT_ELTTY(8, 16, false, 3);
3747   case BuiltinType::SveInt8x4:
3748     return SVE_INT_ELTTY(8, 16, true, 4);
3749   case BuiltinType::SveUint8x4:
3750     return SVE_INT_ELTTY(8, 16, false, 4);
3751   case BuiltinType::SveInt16:
3752     return SVE_INT_ELTTY(16, 8, true, 1);
3753   case BuiltinType::SveUint16:
3754     return SVE_INT_ELTTY(16, 8, false, 1);
3755   case BuiltinType::SveInt16x2:
3756     return SVE_INT_ELTTY(16, 8, true, 2);
3757   case BuiltinType::SveUint16x2:
3758     return SVE_INT_ELTTY(16, 8, false, 2);
3759   case BuiltinType::SveInt16x3:
3760     return SVE_INT_ELTTY(16, 8, true, 3);
3761   case BuiltinType::SveUint16x3:
3762     return SVE_INT_ELTTY(16, 8, false, 3);
3763   case BuiltinType::SveInt16x4:
3764     return SVE_INT_ELTTY(16, 8, true, 4);
3765   case BuiltinType::SveUint16x4:
3766     return SVE_INT_ELTTY(16, 8, false, 4);
3767   case BuiltinType::SveInt32:
3768     return SVE_INT_ELTTY(32, 4, true, 1);
3769   case BuiltinType::SveUint32:
3770     return SVE_INT_ELTTY(32, 4, false, 1);
3771   case BuiltinType::SveInt32x2:
3772     return SVE_INT_ELTTY(32, 4, true, 2);
3773   case BuiltinType::SveUint32x2:
3774     return SVE_INT_ELTTY(32, 4, false, 2);
3775   case BuiltinType::SveInt32x3:
3776     return SVE_INT_ELTTY(32, 4, true, 3);
3777   case BuiltinType::SveUint32x3:
3778     return SVE_INT_ELTTY(32, 4, false, 3);
3779   case BuiltinType::SveInt32x4:
3780     return SVE_INT_ELTTY(32, 4, true, 4);
3781   case BuiltinType::SveUint32x4:
3782     return SVE_INT_ELTTY(32, 4, false, 4);
3783   case BuiltinType::SveInt64:
3784     return SVE_INT_ELTTY(64, 2, true, 1);
3785   case BuiltinType::SveUint64:
3786     return SVE_INT_ELTTY(64, 2, false, 1);
3787   case BuiltinType::SveInt64x2:
3788     return SVE_INT_ELTTY(64, 2, true, 2);
3789   case BuiltinType::SveUint64x2:
3790     return SVE_INT_ELTTY(64, 2, false, 2);
3791   case BuiltinType::SveInt64x3:
3792     return SVE_INT_ELTTY(64, 2, true, 3);
3793   case BuiltinType::SveUint64x3:
3794     return SVE_INT_ELTTY(64, 2, false, 3);
3795   case BuiltinType::SveInt64x4:
3796     return SVE_INT_ELTTY(64, 2, true, 4);
3797   case BuiltinType::SveUint64x4:
3798     return SVE_INT_ELTTY(64, 2, false, 4);
3799   case BuiltinType::SveBool:
3800     return SVE_ELTTY(BoolTy, 16, 1);
3801   case BuiltinType::SveFloat16:
3802     return SVE_ELTTY(HalfTy, 8, 1);
3803   case BuiltinType::SveFloat16x2:
3804     return SVE_ELTTY(HalfTy, 8, 2);
3805   case BuiltinType::SveFloat16x3:
3806     return SVE_ELTTY(HalfTy, 8, 3);
3807   case BuiltinType::SveFloat16x4:
3808     return SVE_ELTTY(HalfTy, 8, 4);
3809   case BuiltinType::SveFloat32:
3810     return SVE_ELTTY(FloatTy, 4, 1);
3811   case BuiltinType::SveFloat32x2:
3812     return SVE_ELTTY(FloatTy, 4, 2);
3813   case BuiltinType::SveFloat32x3:
3814     return SVE_ELTTY(FloatTy, 4, 3);
3815   case BuiltinType::SveFloat32x4:
3816     return SVE_ELTTY(FloatTy, 4, 4);
3817   case BuiltinType::SveFloat64:
3818     return SVE_ELTTY(DoubleTy, 2, 1);
3819   case BuiltinType::SveFloat64x2:
3820     return SVE_ELTTY(DoubleTy, 2, 2);
3821   case BuiltinType::SveFloat64x3:
3822     return SVE_ELTTY(DoubleTy, 2, 3);
3823   case BuiltinType::SveFloat64x4:
3824     return SVE_ELTTY(DoubleTy, 2, 4);
3825   case BuiltinType::SveBFloat16:
3826     return SVE_ELTTY(BFloat16Ty, 8, 1);
3827   case BuiltinType::SveBFloat16x2:
3828     return SVE_ELTTY(BFloat16Ty, 8, 2);
3829   case BuiltinType::SveBFloat16x3:
3830     return SVE_ELTTY(BFloat16Ty, 8, 3);
3831   case BuiltinType::SveBFloat16x4:
3832     return SVE_ELTTY(BFloat16Ty, 8, 4);
3833 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3834                             IsSigned)                                          \
3835   case BuiltinType::Id:                                                        \
3836     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3837             llvm::ElementCount::getScalable(NumEls), NF};
3838 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3839   case BuiltinType::Id:                                                        \
3840     return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy),       \
3841             llvm::ElementCount::getScalable(NumEls), NF};
3842 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3843   case BuiltinType::Id:                                                        \
3844     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3845 #include "clang/Basic/RISCVVTypes.def"
3846   }
3847 }
3848 
3849 /// getScalableVectorType - Return the unique reference to a scalable vector
3850 /// type of the specified element type and size. VectorType must be a built-in
3851 /// type.
3852 QualType ASTContext::getScalableVectorType(QualType EltTy,
3853                                            unsigned NumElts) const {
3854   if (Target->hasAArch64SVETypes()) {
3855     uint64_t EltTySize = getTypeSize(EltTy);
3856 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3857                         IsSigned, IsFP, IsBF)                                  \
3858   if (!EltTy->isBooleanType() &&                                               \
3859       ((EltTy->hasIntegerRepresentation() &&                                   \
3860         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3861        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3862         IsFP && !IsBF) ||                                                      \
3863        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3864         IsBF && !IsFP)) &&                                                     \
3865       EltTySize == ElBits && NumElts == NumEls) {                              \
3866     return SingletonId;                                                        \
3867   }
3868 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3869   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3870     return SingletonId;
3871 #include "clang/Basic/AArch64SVEACLETypes.def"
3872   } else if (Target->hasRISCVVTypes()) {
3873     uint64_t EltTySize = getTypeSize(EltTy);
3874 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3875                         IsFP)                                                  \
3876     if (!EltTy->isBooleanType() &&                                             \
3877         ((EltTy->hasIntegerRepresentation() &&                                 \
3878           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3879          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3880         EltTySize == ElBits && NumElts == NumEls)                              \
3881       return SingletonId;
3882 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3883     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3884       return SingletonId;
3885 #include "clang/Basic/RISCVVTypes.def"
3886   }
3887   return QualType();
3888 }
3889 
3890 /// getVectorType - Return the unique reference to a vector type of
3891 /// the specified element type and size. VectorType must be a built-in type.
3892 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3893                                    VectorType::VectorKind VecKind) const {
3894   assert(vecType->isBuiltinType());
3895 
3896   // Check if we've already instantiated a vector of this type.
3897   llvm::FoldingSetNodeID ID;
3898   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3899 
3900   void *InsertPos = nullptr;
3901   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3902     return QualType(VTP, 0);
3903 
3904   // If the element type isn't canonical, this won't be a canonical type either,
3905   // so fill in the canonical type field.
3906   QualType Canonical;
3907   if (!vecType.isCanonical()) {
3908     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3909 
3910     // Get the new insert position for the node we care about.
3911     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3912     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3913   }
3914   auto *New = new (*this, TypeAlignment)
3915     VectorType(vecType, NumElts, Canonical, VecKind);
3916   VectorTypes.InsertNode(New, InsertPos);
3917   Types.push_back(New);
3918   return QualType(New, 0);
3919 }
3920 
3921 QualType
3922 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3923                                    SourceLocation AttrLoc,
3924                                    VectorType::VectorKind VecKind) const {
3925   llvm::FoldingSetNodeID ID;
3926   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3927                                VecKind);
3928   void *InsertPos = nullptr;
3929   DependentVectorType *Canon =
3930       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3931   DependentVectorType *New;
3932 
3933   if (Canon) {
3934     New = new (*this, TypeAlignment) DependentVectorType(
3935         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3936   } else {
3937     QualType CanonVecTy = getCanonicalType(VecType);
3938     if (CanonVecTy == VecType) {
3939       New = new (*this, TypeAlignment) DependentVectorType(
3940           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3941 
3942       DependentVectorType *CanonCheck =
3943           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3944       assert(!CanonCheck &&
3945              "Dependent-sized vector_size canonical type broken");
3946       (void)CanonCheck;
3947       DependentVectorTypes.InsertNode(New, InsertPos);
3948     } else {
3949       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3950                                                 SourceLocation(), VecKind);
3951       New = new (*this, TypeAlignment) DependentVectorType(
3952           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3953     }
3954   }
3955 
3956   Types.push_back(New);
3957   return QualType(New, 0);
3958 }
3959 
3960 /// getExtVectorType - Return the unique reference to an extended vector type of
3961 /// the specified element type and size. VectorType must be a built-in type.
3962 QualType
3963 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3964   assert(vecType->isBuiltinType() || vecType->isDependentType());
3965 
3966   // Check if we've already instantiated a vector of this type.
3967   llvm::FoldingSetNodeID ID;
3968   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3969                       VectorType::GenericVector);
3970   void *InsertPos = nullptr;
3971   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3972     return QualType(VTP, 0);
3973 
3974   // If the element type isn't canonical, this won't be a canonical type either,
3975   // so fill in the canonical type field.
3976   QualType Canonical;
3977   if (!vecType.isCanonical()) {
3978     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3979 
3980     // Get the new insert position for the node we care about.
3981     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3982     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3983   }
3984   auto *New = new (*this, TypeAlignment)
3985     ExtVectorType(vecType, NumElts, Canonical);
3986   VectorTypes.InsertNode(New, InsertPos);
3987   Types.push_back(New);
3988   return QualType(New, 0);
3989 }
3990 
3991 QualType
3992 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3993                                            Expr *SizeExpr,
3994                                            SourceLocation AttrLoc) const {
3995   llvm::FoldingSetNodeID ID;
3996   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3997                                        SizeExpr);
3998 
3999   void *InsertPos = nullptr;
4000   DependentSizedExtVectorType *Canon
4001     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4002   DependentSizedExtVectorType *New;
4003   if (Canon) {
4004     // We already have a canonical version of this array type; use it as
4005     // the canonical type for a newly-built type.
4006     New = new (*this, TypeAlignment)
4007       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4008                                   SizeExpr, AttrLoc);
4009   } else {
4010     QualType CanonVecTy = getCanonicalType(vecType);
4011     if (CanonVecTy == vecType) {
4012       New = new (*this, TypeAlignment)
4013         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4014                                     AttrLoc);
4015 
4016       DependentSizedExtVectorType *CanonCheck
4017         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4018       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4019       (void)CanonCheck;
4020       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4021     } else {
4022       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4023                                                            SourceLocation());
4024       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4025           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4026     }
4027   }
4028 
4029   Types.push_back(New);
4030   return QualType(New, 0);
4031 }
4032 
4033 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4034                                            unsigned NumColumns) const {
4035   llvm::FoldingSetNodeID ID;
4036   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4037                               Type::ConstantMatrix);
4038 
4039   assert(MatrixType::isValidElementType(ElementTy) &&
4040          "need a valid element type");
4041   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4042          ConstantMatrixType::isDimensionValid(NumColumns) &&
4043          "need valid matrix dimensions");
4044   void *InsertPos = nullptr;
4045   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4046     return QualType(MTP, 0);
4047 
4048   QualType Canonical;
4049   if (!ElementTy.isCanonical()) {
4050     Canonical =
4051         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4052 
4053     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4054     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4055     (void)NewIP;
4056   }
4057 
4058   auto *New = new (*this, TypeAlignment)
4059       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4060   MatrixTypes.InsertNode(New, InsertPos);
4061   Types.push_back(New);
4062   return QualType(New, 0);
4063 }
4064 
4065 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4066                                                  Expr *RowExpr,
4067                                                  Expr *ColumnExpr,
4068                                                  SourceLocation AttrLoc) const {
4069   QualType CanonElementTy = getCanonicalType(ElementTy);
4070   llvm::FoldingSetNodeID ID;
4071   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4072                                     ColumnExpr);
4073 
4074   void *InsertPos = nullptr;
4075   DependentSizedMatrixType *Canon =
4076       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4077 
4078   if (!Canon) {
4079     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4080         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4081 #ifndef NDEBUG
4082     DependentSizedMatrixType *CanonCheck =
4083         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4084     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4085 #endif
4086     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4087     Types.push_back(Canon);
4088   }
4089 
4090   // Already have a canonical version of the matrix type
4091   //
4092   // If it exactly matches the requested type, use it directly.
4093   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4094       Canon->getRowExpr() == ColumnExpr)
4095     return QualType(Canon, 0);
4096 
4097   // Use Canon as the canonical type for newly-built type.
4098   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4099       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4100                                ColumnExpr, AttrLoc);
4101   Types.push_back(New);
4102   return QualType(New, 0);
4103 }
4104 
4105 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4106                                                   Expr *AddrSpaceExpr,
4107                                                   SourceLocation AttrLoc) const {
4108   assert(AddrSpaceExpr->isInstantiationDependent());
4109 
4110   QualType canonPointeeType = getCanonicalType(PointeeType);
4111 
4112   void *insertPos = nullptr;
4113   llvm::FoldingSetNodeID ID;
4114   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4115                                      AddrSpaceExpr);
4116 
4117   DependentAddressSpaceType *canonTy =
4118     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4119 
4120   if (!canonTy) {
4121     canonTy = new (*this, TypeAlignment)
4122       DependentAddressSpaceType(*this, canonPointeeType,
4123                                 QualType(), AddrSpaceExpr, AttrLoc);
4124     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4125     Types.push_back(canonTy);
4126   }
4127 
4128   if (canonPointeeType == PointeeType &&
4129       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4130     return QualType(canonTy, 0);
4131 
4132   auto *sugaredType
4133     = new (*this, TypeAlignment)
4134         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4135                                   AddrSpaceExpr, AttrLoc);
4136   Types.push_back(sugaredType);
4137   return QualType(sugaredType, 0);
4138 }
4139 
4140 /// Determine whether \p T is canonical as the result type of a function.
4141 static bool isCanonicalResultType(QualType T) {
4142   return T.isCanonical() &&
4143          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4144           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4145 }
4146 
4147 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4148 QualType
4149 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4150                                    const FunctionType::ExtInfo &Info) const {
4151   // Unique functions, to guarantee there is only one function of a particular
4152   // structure.
4153   llvm::FoldingSetNodeID ID;
4154   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4155 
4156   void *InsertPos = nullptr;
4157   if (FunctionNoProtoType *FT =
4158         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4159     return QualType(FT, 0);
4160 
4161   QualType Canonical;
4162   if (!isCanonicalResultType(ResultTy)) {
4163     Canonical =
4164       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4165 
4166     // Get the new insert position for the node we care about.
4167     FunctionNoProtoType *NewIP =
4168       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4169     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4170   }
4171 
4172   auto *New = new (*this, TypeAlignment)
4173     FunctionNoProtoType(ResultTy, Canonical, Info);
4174   Types.push_back(New);
4175   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4176   return QualType(New, 0);
4177 }
4178 
4179 CanQualType
4180 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4181   CanQualType CanResultType = getCanonicalType(ResultType);
4182 
4183   // Canonical result types do not have ARC lifetime qualifiers.
4184   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4185     Qualifiers Qs = CanResultType.getQualifiers();
4186     Qs.removeObjCLifetime();
4187     return CanQualType::CreateUnsafe(
4188              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4189   }
4190 
4191   return CanResultType;
4192 }
4193 
4194 static bool isCanonicalExceptionSpecification(
4195     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4196   if (ESI.Type == EST_None)
4197     return true;
4198   if (!NoexceptInType)
4199     return false;
4200 
4201   // C++17 onwards: exception specification is part of the type, as a simple
4202   // boolean "can this function type throw".
4203   if (ESI.Type == EST_BasicNoexcept)
4204     return true;
4205 
4206   // A noexcept(expr) specification is (possibly) canonical if expr is
4207   // value-dependent.
4208   if (ESI.Type == EST_DependentNoexcept)
4209     return true;
4210 
4211   // A dynamic exception specification is canonical if it only contains pack
4212   // expansions (so we can't tell whether it's non-throwing) and all its
4213   // contained types are canonical.
4214   if (ESI.Type == EST_Dynamic) {
4215     bool AnyPackExpansions = false;
4216     for (QualType ET : ESI.Exceptions) {
4217       if (!ET.isCanonical())
4218         return false;
4219       if (ET->getAs<PackExpansionType>())
4220         AnyPackExpansions = true;
4221     }
4222     return AnyPackExpansions;
4223   }
4224 
4225   return false;
4226 }
4227 
4228 QualType ASTContext::getFunctionTypeInternal(
4229     QualType ResultTy, ArrayRef<QualType> ArgArray,
4230     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4231   size_t NumArgs = ArgArray.size();
4232 
4233   // Unique functions, to guarantee there is only one function of a particular
4234   // structure.
4235   llvm::FoldingSetNodeID ID;
4236   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4237                              *this, true);
4238 
4239   QualType Canonical;
4240   bool Unique = false;
4241 
4242   void *InsertPos = nullptr;
4243   if (FunctionProtoType *FPT =
4244         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4245     QualType Existing = QualType(FPT, 0);
4246 
4247     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4248     // it so long as our exception specification doesn't contain a dependent
4249     // noexcept expression, or we're just looking for a canonical type.
4250     // Otherwise, we're going to need to create a type
4251     // sugar node to hold the concrete expression.
4252     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4253         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4254       return Existing;
4255 
4256     // We need a new type sugar node for this one, to hold the new noexcept
4257     // expression. We do no canonicalization here, but that's OK since we don't
4258     // expect to see the same noexcept expression much more than once.
4259     Canonical = getCanonicalType(Existing);
4260     Unique = true;
4261   }
4262 
4263   bool NoexceptInType = getLangOpts().CPlusPlus17;
4264   bool IsCanonicalExceptionSpec =
4265       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4266 
4267   // Determine whether the type being created is already canonical or not.
4268   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4269                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4270   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4271     if (!ArgArray[i].isCanonicalAsParam())
4272       isCanonical = false;
4273 
4274   if (OnlyWantCanonical)
4275     assert(isCanonical &&
4276            "given non-canonical parameters constructing canonical type");
4277 
4278   // If this type isn't canonical, get the canonical version of it if we don't
4279   // already have it. The exception spec is only partially part of the
4280   // canonical type, and only in C++17 onwards.
4281   if (!isCanonical && Canonical.isNull()) {
4282     SmallVector<QualType, 16> CanonicalArgs;
4283     CanonicalArgs.reserve(NumArgs);
4284     for (unsigned i = 0; i != NumArgs; ++i)
4285       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4286 
4287     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4288     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4289     CanonicalEPI.HasTrailingReturn = false;
4290 
4291     if (IsCanonicalExceptionSpec) {
4292       // Exception spec is already OK.
4293     } else if (NoexceptInType) {
4294       switch (EPI.ExceptionSpec.Type) {
4295       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4296         // We don't know yet. It shouldn't matter what we pick here; no-one
4297         // should ever look at this.
4298         LLVM_FALLTHROUGH;
4299       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4300         CanonicalEPI.ExceptionSpec.Type = EST_None;
4301         break;
4302 
4303         // A dynamic exception specification is almost always "not noexcept",
4304         // with the exception that a pack expansion might expand to no types.
4305       case EST_Dynamic: {
4306         bool AnyPacks = false;
4307         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4308           if (ET->getAs<PackExpansionType>())
4309             AnyPacks = true;
4310           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4311         }
4312         if (!AnyPacks)
4313           CanonicalEPI.ExceptionSpec.Type = EST_None;
4314         else {
4315           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4316           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4317         }
4318         break;
4319       }
4320 
4321       case EST_DynamicNone:
4322       case EST_BasicNoexcept:
4323       case EST_NoexceptTrue:
4324       case EST_NoThrow:
4325         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4326         break;
4327 
4328       case EST_DependentNoexcept:
4329         llvm_unreachable("dependent noexcept is already canonical");
4330       }
4331     } else {
4332       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4333     }
4334 
4335     // Adjust the canonical function result type.
4336     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4337     Canonical =
4338         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4339 
4340     // Get the new insert position for the node we care about.
4341     FunctionProtoType *NewIP =
4342       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4343     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4344   }
4345 
4346   // Compute the needed size to hold this FunctionProtoType and the
4347   // various trailing objects.
4348   auto ESH = FunctionProtoType::getExceptionSpecSize(
4349       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4350   size_t Size = FunctionProtoType::totalSizeToAlloc<
4351       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4352       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4353       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4354       NumArgs, EPI.Variadic,
4355       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4356       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4357       EPI.ExtParameterInfos ? NumArgs : 0,
4358       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4359 
4360   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4361   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4362   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4363   Types.push_back(FTP);
4364   if (!Unique)
4365     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4366   return QualType(FTP, 0);
4367 }
4368 
4369 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4370   llvm::FoldingSetNodeID ID;
4371   PipeType::Profile(ID, T, ReadOnly);
4372 
4373   void *InsertPos = nullptr;
4374   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4375     return QualType(PT, 0);
4376 
4377   // If the pipe element type isn't canonical, this won't be a canonical type
4378   // either, so fill in the canonical type field.
4379   QualType Canonical;
4380   if (!T.isCanonical()) {
4381     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4382 
4383     // Get the new insert position for the node we care about.
4384     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4385     assert(!NewIP && "Shouldn't be in the map!");
4386     (void)NewIP;
4387   }
4388   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4389   Types.push_back(New);
4390   PipeTypes.InsertNode(New, InsertPos);
4391   return QualType(New, 0);
4392 }
4393 
4394 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4395   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4396   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4397                          : Ty;
4398 }
4399 
4400 QualType ASTContext::getReadPipeType(QualType T) const {
4401   return getPipeType(T, true);
4402 }
4403 
4404 QualType ASTContext::getWritePipeType(QualType T) const {
4405   return getPipeType(T, false);
4406 }
4407 
4408 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4409   llvm::FoldingSetNodeID ID;
4410   ExtIntType::Profile(ID, IsUnsigned, NumBits);
4411 
4412   void *InsertPos = nullptr;
4413   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4414     return QualType(EIT, 0);
4415 
4416   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4417   ExtIntTypes.InsertNode(New, InsertPos);
4418   Types.push_back(New);
4419   return QualType(New, 0);
4420 }
4421 
4422 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4423                                             Expr *NumBitsExpr) const {
4424   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4425   llvm::FoldingSetNodeID ID;
4426   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4427 
4428   void *InsertPos = nullptr;
4429   if (DependentExtIntType *Existing =
4430           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4431     return QualType(Existing, 0);
4432 
4433   auto *New = new (*this, TypeAlignment)
4434       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4435   DependentExtIntTypes.InsertNode(New, InsertPos);
4436 
4437   Types.push_back(New);
4438   return QualType(New, 0);
4439 }
4440 
4441 #ifndef NDEBUG
4442 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4443   if (!isa<CXXRecordDecl>(D)) return false;
4444   const auto *RD = cast<CXXRecordDecl>(D);
4445   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4446     return true;
4447   if (RD->getDescribedClassTemplate() &&
4448       !isa<ClassTemplateSpecializationDecl>(RD))
4449     return true;
4450   return false;
4451 }
4452 #endif
4453 
4454 /// getInjectedClassNameType - Return the unique reference to the
4455 /// injected class name type for the specified templated declaration.
4456 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4457                                               QualType TST) const {
4458   assert(NeedsInjectedClassNameType(Decl));
4459   if (Decl->TypeForDecl) {
4460     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4461   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4462     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4463     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4464     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4465   } else {
4466     Type *newType =
4467       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4468     Decl->TypeForDecl = newType;
4469     Types.push_back(newType);
4470   }
4471   return QualType(Decl->TypeForDecl, 0);
4472 }
4473 
4474 /// getTypeDeclType - Return the unique reference to the type for the
4475 /// specified type declaration.
4476 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4477   assert(Decl && "Passed null for Decl param");
4478   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4479 
4480   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4481     return getTypedefType(Typedef);
4482 
4483   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4484          "Template type parameter types are always available.");
4485 
4486   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4487     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4488     assert(!NeedsInjectedClassNameType(Record));
4489     return getRecordType(Record);
4490   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4491     assert(Enum->isFirstDecl() && "enum has previous declaration");
4492     return getEnumType(Enum);
4493   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4494     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4495     Decl->TypeForDecl = newType;
4496     Types.push_back(newType);
4497   } else
4498     llvm_unreachable("TypeDecl without a type?");
4499 
4500   return QualType(Decl->TypeForDecl, 0);
4501 }
4502 
4503 /// getTypedefType - Return the unique reference to the type for the
4504 /// specified typedef name decl.
4505 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4506                                     QualType Underlying) const {
4507   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4508 
4509   if (Underlying.isNull())
4510     Underlying = Decl->getUnderlyingType();
4511   QualType Canonical = getCanonicalType(Underlying);
4512   auto *newType = new (*this, TypeAlignment)
4513       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4514   Decl->TypeForDecl = newType;
4515   Types.push_back(newType);
4516   return QualType(newType, 0);
4517 }
4518 
4519 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4520   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4521 
4522   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4523     if (PrevDecl->TypeForDecl)
4524       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4525 
4526   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4527   Decl->TypeForDecl = newType;
4528   Types.push_back(newType);
4529   return QualType(newType, 0);
4530 }
4531 
4532 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4533   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4534 
4535   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4536     if (PrevDecl->TypeForDecl)
4537       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4538 
4539   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4540   Decl->TypeForDecl = newType;
4541   Types.push_back(newType);
4542   return QualType(newType, 0);
4543 }
4544 
4545 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4546                                        QualType modifiedType,
4547                                        QualType equivalentType) {
4548   llvm::FoldingSetNodeID id;
4549   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4550 
4551   void *insertPos = nullptr;
4552   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4553   if (type) return QualType(type, 0);
4554 
4555   QualType canon = getCanonicalType(equivalentType);
4556   type = new (*this, TypeAlignment)
4557       AttributedType(canon, attrKind, modifiedType, equivalentType);
4558 
4559   Types.push_back(type);
4560   AttributedTypes.InsertNode(type, insertPos);
4561 
4562   return QualType(type, 0);
4563 }
4564 
4565 /// Retrieve a substitution-result type.
4566 QualType
4567 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4568                                          QualType Replacement) const {
4569   assert(Replacement.isCanonical()
4570          && "replacement types must always be canonical");
4571 
4572   llvm::FoldingSetNodeID ID;
4573   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4574   void *InsertPos = nullptr;
4575   SubstTemplateTypeParmType *SubstParm
4576     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4577 
4578   if (!SubstParm) {
4579     SubstParm = new (*this, TypeAlignment)
4580       SubstTemplateTypeParmType(Parm, Replacement);
4581     Types.push_back(SubstParm);
4582     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4583   }
4584 
4585   return QualType(SubstParm, 0);
4586 }
4587 
4588 /// Retrieve a
4589 QualType ASTContext::getSubstTemplateTypeParmPackType(
4590                                           const TemplateTypeParmType *Parm,
4591                                               const TemplateArgument &ArgPack) {
4592 #ifndef NDEBUG
4593   for (const auto &P : ArgPack.pack_elements()) {
4594     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4595     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4596   }
4597 #endif
4598 
4599   llvm::FoldingSetNodeID ID;
4600   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4601   void *InsertPos = nullptr;
4602   if (SubstTemplateTypeParmPackType *SubstParm
4603         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4604     return QualType(SubstParm, 0);
4605 
4606   QualType Canon;
4607   if (!Parm->isCanonicalUnqualified()) {
4608     Canon = getCanonicalType(QualType(Parm, 0));
4609     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4610                                              ArgPack);
4611     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4612   }
4613 
4614   auto *SubstParm
4615     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4616                                                                ArgPack);
4617   Types.push_back(SubstParm);
4618   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4619   return QualType(SubstParm, 0);
4620 }
4621 
4622 /// Retrieve the template type parameter type for a template
4623 /// parameter or parameter pack with the given depth, index, and (optionally)
4624 /// name.
4625 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4626                                              bool ParameterPack,
4627                                              TemplateTypeParmDecl *TTPDecl) const {
4628   llvm::FoldingSetNodeID ID;
4629   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4630   void *InsertPos = nullptr;
4631   TemplateTypeParmType *TypeParm
4632     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4633 
4634   if (TypeParm)
4635     return QualType(TypeParm, 0);
4636 
4637   if (TTPDecl) {
4638     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4639     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4640 
4641     TemplateTypeParmType *TypeCheck
4642       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4643     assert(!TypeCheck && "Template type parameter canonical type broken");
4644     (void)TypeCheck;
4645   } else
4646     TypeParm = new (*this, TypeAlignment)
4647       TemplateTypeParmType(Depth, Index, ParameterPack);
4648 
4649   Types.push_back(TypeParm);
4650   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4651 
4652   return QualType(TypeParm, 0);
4653 }
4654 
4655 TypeSourceInfo *
4656 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4657                                               SourceLocation NameLoc,
4658                                         const TemplateArgumentListInfo &Args,
4659                                               QualType Underlying) const {
4660   assert(!Name.getAsDependentTemplateName() &&
4661          "No dependent template names here!");
4662   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4663 
4664   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4665   TemplateSpecializationTypeLoc TL =
4666       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4667   TL.setTemplateKeywordLoc(SourceLocation());
4668   TL.setTemplateNameLoc(NameLoc);
4669   TL.setLAngleLoc(Args.getLAngleLoc());
4670   TL.setRAngleLoc(Args.getRAngleLoc());
4671   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4672     TL.setArgLocInfo(i, Args[i].getLocInfo());
4673   return DI;
4674 }
4675 
4676 QualType
4677 ASTContext::getTemplateSpecializationType(TemplateName Template,
4678                                           const TemplateArgumentListInfo &Args,
4679                                           QualType Underlying) const {
4680   assert(!Template.getAsDependentTemplateName() &&
4681          "No dependent template names here!");
4682 
4683   SmallVector<TemplateArgument, 4> ArgVec;
4684   ArgVec.reserve(Args.size());
4685   for (const TemplateArgumentLoc &Arg : Args.arguments())
4686     ArgVec.push_back(Arg.getArgument());
4687 
4688   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4689 }
4690 
4691 #ifndef NDEBUG
4692 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4693   for (const TemplateArgument &Arg : Args)
4694     if (Arg.isPackExpansion())
4695       return true;
4696 
4697   return true;
4698 }
4699 #endif
4700 
4701 QualType
4702 ASTContext::getTemplateSpecializationType(TemplateName Template,
4703                                           ArrayRef<TemplateArgument> Args,
4704                                           QualType Underlying) const {
4705   assert(!Template.getAsDependentTemplateName() &&
4706          "No dependent template names here!");
4707   // Look through qualified template names.
4708   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4709     Template = TemplateName(QTN->getTemplateDecl());
4710 
4711   bool IsTypeAlias =
4712     Template.getAsTemplateDecl() &&
4713     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4714   QualType CanonType;
4715   if (!Underlying.isNull())
4716     CanonType = getCanonicalType(Underlying);
4717   else {
4718     // We can get here with an alias template when the specialization contains
4719     // a pack expansion that does not match up with a parameter pack.
4720     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4721            "Caller must compute aliased type");
4722     IsTypeAlias = false;
4723     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4724   }
4725 
4726   // Allocate the (non-canonical) template specialization type, but don't
4727   // try to unique it: these types typically have location information that
4728   // we don't unique and don't want to lose.
4729   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4730                        sizeof(TemplateArgument) * Args.size() +
4731                        (IsTypeAlias? sizeof(QualType) : 0),
4732                        TypeAlignment);
4733   auto *Spec
4734     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4735                                          IsTypeAlias ? Underlying : QualType());
4736 
4737   Types.push_back(Spec);
4738   return QualType(Spec, 0);
4739 }
4740 
4741 QualType ASTContext::getCanonicalTemplateSpecializationType(
4742     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4743   assert(!Template.getAsDependentTemplateName() &&
4744          "No dependent template names here!");
4745 
4746   // Look through qualified template names.
4747   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4748     Template = TemplateName(QTN->getTemplateDecl());
4749 
4750   // Build the canonical template specialization type.
4751   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4752   SmallVector<TemplateArgument, 4> CanonArgs;
4753   unsigned NumArgs = Args.size();
4754   CanonArgs.reserve(NumArgs);
4755   for (const TemplateArgument &Arg : Args)
4756     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4757 
4758   // Determine whether this canonical template specialization type already
4759   // exists.
4760   llvm::FoldingSetNodeID ID;
4761   TemplateSpecializationType::Profile(ID, CanonTemplate,
4762                                       CanonArgs, *this);
4763 
4764   void *InsertPos = nullptr;
4765   TemplateSpecializationType *Spec
4766     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4767 
4768   if (!Spec) {
4769     // Allocate a new canonical template specialization type.
4770     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4771                           sizeof(TemplateArgument) * NumArgs),
4772                          TypeAlignment);
4773     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4774                                                 CanonArgs,
4775                                                 QualType(), QualType());
4776     Types.push_back(Spec);
4777     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4778   }
4779 
4780   assert(Spec->isDependentType() &&
4781          "Non-dependent template-id type must have a canonical type");
4782   return QualType(Spec, 0);
4783 }
4784 
4785 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4786                                        NestedNameSpecifier *NNS,
4787                                        QualType NamedType,
4788                                        TagDecl *OwnedTagDecl) const {
4789   llvm::FoldingSetNodeID ID;
4790   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4791 
4792   void *InsertPos = nullptr;
4793   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4794   if (T)
4795     return QualType(T, 0);
4796 
4797   QualType Canon = NamedType;
4798   if (!Canon.isCanonical()) {
4799     Canon = getCanonicalType(NamedType);
4800     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4801     assert(!CheckT && "Elaborated canonical type broken");
4802     (void)CheckT;
4803   }
4804 
4805   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4806                        TypeAlignment);
4807   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4808 
4809   Types.push_back(T);
4810   ElaboratedTypes.InsertNode(T, InsertPos);
4811   return QualType(T, 0);
4812 }
4813 
4814 QualType
4815 ASTContext::getParenType(QualType InnerType) const {
4816   llvm::FoldingSetNodeID ID;
4817   ParenType::Profile(ID, InnerType);
4818 
4819   void *InsertPos = nullptr;
4820   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4821   if (T)
4822     return QualType(T, 0);
4823 
4824   QualType Canon = InnerType;
4825   if (!Canon.isCanonical()) {
4826     Canon = getCanonicalType(InnerType);
4827     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4828     assert(!CheckT && "Paren canonical type broken");
4829     (void)CheckT;
4830   }
4831 
4832   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4833   Types.push_back(T);
4834   ParenTypes.InsertNode(T, InsertPos);
4835   return QualType(T, 0);
4836 }
4837 
4838 QualType
4839 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4840                                   const IdentifierInfo *MacroII) const {
4841   QualType Canon = UnderlyingTy;
4842   if (!Canon.isCanonical())
4843     Canon = getCanonicalType(UnderlyingTy);
4844 
4845   auto *newType = new (*this, TypeAlignment)
4846       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4847   Types.push_back(newType);
4848   return QualType(newType, 0);
4849 }
4850 
4851 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4852                                           NestedNameSpecifier *NNS,
4853                                           const IdentifierInfo *Name,
4854                                           QualType Canon) const {
4855   if (Canon.isNull()) {
4856     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4857     if (CanonNNS != NNS)
4858       Canon = getDependentNameType(Keyword, CanonNNS, Name);
4859   }
4860 
4861   llvm::FoldingSetNodeID ID;
4862   DependentNameType::Profile(ID, Keyword, NNS, Name);
4863 
4864   void *InsertPos = nullptr;
4865   DependentNameType *T
4866     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4867   if (T)
4868     return QualType(T, 0);
4869 
4870   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4871   Types.push_back(T);
4872   DependentNameTypes.InsertNode(T, InsertPos);
4873   return QualType(T, 0);
4874 }
4875 
4876 QualType
4877 ASTContext::getDependentTemplateSpecializationType(
4878                                  ElaboratedTypeKeyword Keyword,
4879                                  NestedNameSpecifier *NNS,
4880                                  const IdentifierInfo *Name,
4881                                  const TemplateArgumentListInfo &Args) const {
4882   // TODO: avoid this copy
4883   SmallVector<TemplateArgument, 16> ArgCopy;
4884   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4885     ArgCopy.push_back(Args[I].getArgument());
4886   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4887 }
4888 
4889 QualType
4890 ASTContext::getDependentTemplateSpecializationType(
4891                                  ElaboratedTypeKeyword Keyword,
4892                                  NestedNameSpecifier *NNS,
4893                                  const IdentifierInfo *Name,
4894                                  ArrayRef<TemplateArgument> Args) const {
4895   assert((!NNS || NNS->isDependent()) &&
4896          "nested-name-specifier must be dependent");
4897 
4898   llvm::FoldingSetNodeID ID;
4899   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4900                                                Name, Args);
4901 
4902   void *InsertPos = nullptr;
4903   DependentTemplateSpecializationType *T
4904     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4905   if (T)
4906     return QualType(T, 0);
4907 
4908   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4909 
4910   ElaboratedTypeKeyword CanonKeyword = Keyword;
4911   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4912 
4913   bool AnyNonCanonArgs = false;
4914   unsigned NumArgs = Args.size();
4915   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4916   for (unsigned I = 0; I != NumArgs; ++I) {
4917     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4918     if (!CanonArgs[I].structurallyEquals(Args[I]))
4919       AnyNonCanonArgs = true;
4920   }
4921 
4922   QualType Canon;
4923   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4924     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4925                                                    Name,
4926                                                    CanonArgs);
4927 
4928     // Find the insert position again.
4929     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4930   }
4931 
4932   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4933                         sizeof(TemplateArgument) * NumArgs),
4934                        TypeAlignment);
4935   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4936                                                     Name, Args, Canon);
4937   Types.push_back(T);
4938   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4939   return QualType(T, 0);
4940 }
4941 
4942 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4943   TemplateArgument Arg;
4944   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4945     QualType ArgType = getTypeDeclType(TTP);
4946     if (TTP->isParameterPack())
4947       ArgType = getPackExpansionType(ArgType, None);
4948 
4949     Arg = TemplateArgument(ArgType);
4950   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4951     QualType T =
4952         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
4953     // For class NTTPs, ensure we include the 'const' so the type matches that
4954     // of a real template argument.
4955     // FIXME: It would be more faithful to model this as something like an
4956     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
4957     if (T->isRecordType())
4958       T.addConst();
4959     Expr *E = new (*this) DeclRefExpr(
4960         *this, NTTP, /*enclosing*/ false, T,
4961         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4962 
4963     if (NTTP->isParameterPack())
4964       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4965                                         None);
4966     Arg = TemplateArgument(E);
4967   } else {
4968     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4969     if (TTP->isParameterPack())
4970       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4971     else
4972       Arg = TemplateArgument(TemplateName(TTP));
4973   }
4974 
4975   if (Param->isTemplateParameterPack())
4976     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4977 
4978   return Arg;
4979 }
4980 
4981 void
4982 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4983                                     SmallVectorImpl<TemplateArgument> &Args) {
4984   Args.reserve(Args.size() + Params->size());
4985 
4986   for (NamedDecl *Param : *Params)
4987     Args.push_back(getInjectedTemplateArg(Param));
4988 }
4989 
4990 QualType ASTContext::getPackExpansionType(QualType Pattern,
4991                                           Optional<unsigned> NumExpansions,
4992                                           bool ExpectPackInType) {
4993   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
4994          "Pack expansions must expand one or more parameter packs");
4995 
4996   llvm::FoldingSetNodeID ID;
4997   PackExpansionType::Profile(ID, Pattern, NumExpansions);
4998 
4999   void *InsertPos = nullptr;
5000   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5001   if (T)
5002     return QualType(T, 0);
5003 
5004   QualType Canon;
5005   if (!Pattern.isCanonical()) {
5006     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5007                                  /*ExpectPackInType=*/false);
5008 
5009     // Find the insert position again, in case we inserted an element into
5010     // PackExpansionTypes and invalidated our insert position.
5011     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5012   }
5013 
5014   T = new (*this, TypeAlignment)
5015       PackExpansionType(Pattern, Canon, NumExpansions);
5016   Types.push_back(T);
5017   PackExpansionTypes.InsertNode(T, InsertPos);
5018   return QualType(T, 0);
5019 }
5020 
5021 /// CmpProtocolNames - Comparison predicate for sorting protocols
5022 /// alphabetically.
5023 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5024                             ObjCProtocolDecl *const *RHS) {
5025   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5026 }
5027 
5028 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5029   if (Protocols.empty()) return true;
5030 
5031   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5032     return false;
5033 
5034   for (unsigned i = 1; i != Protocols.size(); ++i)
5035     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5036         Protocols[i]->getCanonicalDecl() != Protocols[i])
5037       return false;
5038   return true;
5039 }
5040 
5041 static void
5042 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5043   // Sort protocols, keyed by name.
5044   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5045 
5046   // Canonicalize.
5047   for (ObjCProtocolDecl *&P : Protocols)
5048     P = P->getCanonicalDecl();
5049 
5050   // Remove duplicates.
5051   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5052   Protocols.erase(ProtocolsEnd, Protocols.end());
5053 }
5054 
5055 QualType ASTContext::getObjCObjectType(QualType BaseType,
5056                                        ObjCProtocolDecl * const *Protocols,
5057                                        unsigned NumProtocols) const {
5058   return getObjCObjectType(BaseType, {},
5059                            llvm::makeArrayRef(Protocols, NumProtocols),
5060                            /*isKindOf=*/false);
5061 }
5062 
5063 QualType ASTContext::getObjCObjectType(
5064            QualType baseType,
5065            ArrayRef<QualType> typeArgs,
5066            ArrayRef<ObjCProtocolDecl *> protocols,
5067            bool isKindOf) const {
5068   // If the base type is an interface and there aren't any protocols or
5069   // type arguments to add, then the interface type will do just fine.
5070   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5071       isa<ObjCInterfaceType>(baseType))
5072     return baseType;
5073 
5074   // Look in the folding set for an existing type.
5075   llvm::FoldingSetNodeID ID;
5076   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5077   void *InsertPos = nullptr;
5078   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5079     return QualType(QT, 0);
5080 
5081   // Determine the type arguments to be used for canonicalization,
5082   // which may be explicitly specified here or written on the base
5083   // type.
5084   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5085   if (effectiveTypeArgs.empty()) {
5086     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5087       effectiveTypeArgs = baseObject->getTypeArgs();
5088   }
5089 
5090   // Build the canonical type, which has the canonical base type and a
5091   // sorted-and-uniqued list of protocols and the type arguments
5092   // canonicalized.
5093   QualType canonical;
5094   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
5095                                           effectiveTypeArgs.end(),
5096                                           [&](QualType type) {
5097                                             return type.isCanonical();
5098                                           });
5099   bool protocolsSorted = areSortedAndUniqued(protocols);
5100   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5101     // Determine the canonical type arguments.
5102     ArrayRef<QualType> canonTypeArgs;
5103     SmallVector<QualType, 4> canonTypeArgsVec;
5104     if (!typeArgsAreCanonical) {
5105       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5106       for (auto typeArg : effectiveTypeArgs)
5107         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5108       canonTypeArgs = canonTypeArgsVec;
5109     } else {
5110       canonTypeArgs = effectiveTypeArgs;
5111     }
5112 
5113     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5114     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5115     if (!protocolsSorted) {
5116       canonProtocolsVec.append(protocols.begin(), protocols.end());
5117       SortAndUniqueProtocols(canonProtocolsVec);
5118       canonProtocols = canonProtocolsVec;
5119     } else {
5120       canonProtocols = protocols;
5121     }
5122 
5123     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5124                                   canonProtocols, isKindOf);
5125 
5126     // Regenerate InsertPos.
5127     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5128   }
5129 
5130   unsigned size = sizeof(ObjCObjectTypeImpl);
5131   size += typeArgs.size() * sizeof(QualType);
5132   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5133   void *mem = Allocate(size, TypeAlignment);
5134   auto *T =
5135     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5136                                  isKindOf);
5137 
5138   Types.push_back(T);
5139   ObjCObjectTypes.InsertNode(T, InsertPos);
5140   return QualType(T, 0);
5141 }
5142 
5143 /// Apply Objective-C protocol qualifiers to the given type.
5144 /// If this is for the canonical type of a type parameter, we can apply
5145 /// protocol qualifiers on the ObjCObjectPointerType.
5146 QualType
5147 ASTContext::applyObjCProtocolQualifiers(QualType type,
5148                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5149                   bool allowOnPointerType) const {
5150   hasError = false;
5151 
5152   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5153     return getObjCTypeParamType(objT->getDecl(), protocols);
5154   }
5155 
5156   // Apply protocol qualifiers to ObjCObjectPointerType.
5157   if (allowOnPointerType) {
5158     if (const auto *objPtr =
5159             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5160       const ObjCObjectType *objT = objPtr->getObjectType();
5161       // Merge protocol lists and construct ObjCObjectType.
5162       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5163       protocolsVec.append(objT->qual_begin(),
5164                           objT->qual_end());
5165       protocolsVec.append(protocols.begin(), protocols.end());
5166       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5167       type = getObjCObjectType(
5168              objT->getBaseType(),
5169              objT->getTypeArgsAsWritten(),
5170              protocols,
5171              objT->isKindOfTypeAsWritten());
5172       return getObjCObjectPointerType(type);
5173     }
5174   }
5175 
5176   // Apply protocol qualifiers to ObjCObjectType.
5177   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5178     // FIXME: Check for protocols to which the class type is already
5179     // known to conform.
5180 
5181     return getObjCObjectType(objT->getBaseType(),
5182                              objT->getTypeArgsAsWritten(),
5183                              protocols,
5184                              objT->isKindOfTypeAsWritten());
5185   }
5186 
5187   // If the canonical type is ObjCObjectType, ...
5188   if (type->isObjCObjectType()) {
5189     // Silently overwrite any existing protocol qualifiers.
5190     // TODO: determine whether that's the right thing to do.
5191 
5192     // FIXME: Check for protocols to which the class type is already
5193     // known to conform.
5194     return getObjCObjectType(type, {}, protocols, false);
5195   }
5196 
5197   // id<protocol-list>
5198   if (type->isObjCIdType()) {
5199     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5200     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5201                                  objPtr->isKindOfType());
5202     return getObjCObjectPointerType(type);
5203   }
5204 
5205   // Class<protocol-list>
5206   if (type->isObjCClassType()) {
5207     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5208     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5209                                  objPtr->isKindOfType());
5210     return getObjCObjectPointerType(type);
5211   }
5212 
5213   hasError = true;
5214   return type;
5215 }
5216 
5217 QualType
5218 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5219                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5220   // Look in the folding set for an existing type.
5221   llvm::FoldingSetNodeID ID;
5222   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5223   void *InsertPos = nullptr;
5224   if (ObjCTypeParamType *TypeParam =
5225       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5226     return QualType(TypeParam, 0);
5227 
5228   // We canonicalize to the underlying type.
5229   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5230   if (!protocols.empty()) {
5231     // Apply the protocol qualifers.
5232     bool hasError;
5233     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5234         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5235     assert(!hasError && "Error when apply protocol qualifier to bound type");
5236   }
5237 
5238   unsigned size = sizeof(ObjCTypeParamType);
5239   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5240   void *mem = Allocate(size, TypeAlignment);
5241   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5242 
5243   Types.push_back(newType);
5244   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5245   return QualType(newType, 0);
5246 }
5247 
5248 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5249                                               ObjCTypeParamDecl *New) const {
5250   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5251   // Update TypeForDecl after updating TypeSourceInfo.
5252   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5253   SmallVector<ObjCProtocolDecl *, 8> protocols;
5254   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5255   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5256   New->setTypeForDecl(UpdatedTy.getTypePtr());
5257 }
5258 
5259 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5260 /// protocol list adopt all protocols in QT's qualified-id protocol
5261 /// list.
5262 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5263                                                 ObjCInterfaceDecl *IC) {
5264   if (!QT->isObjCQualifiedIdType())
5265     return false;
5266 
5267   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5268     // If both the right and left sides have qualifiers.
5269     for (auto *Proto : OPT->quals()) {
5270       if (!IC->ClassImplementsProtocol(Proto, false))
5271         return false;
5272     }
5273     return true;
5274   }
5275   return false;
5276 }
5277 
5278 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5279 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5280 /// of protocols.
5281 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5282                                                 ObjCInterfaceDecl *IDecl) {
5283   if (!QT->isObjCQualifiedIdType())
5284     return false;
5285   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5286   if (!OPT)
5287     return false;
5288   if (!IDecl->hasDefinition())
5289     return false;
5290   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5291   CollectInheritedProtocols(IDecl, InheritedProtocols);
5292   if (InheritedProtocols.empty())
5293     return false;
5294   // Check that if every protocol in list of id<plist> conforms to a protocol
5295   // of IDecl's, then bridge casting is ok.
5296   bool Conforms = false;
5297   for (auto *Proto : OPT->quals()) {
5298     Conforms = false;
5299     for (auto *PI : InheritedProtocols) {
5300       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5301         Conforms = true;
5302         break;
5303       }
5304     }
5305     if (!Conforms)
5306       break;
5307   }
5308   if (Conforms)
5309     return true;
5310 
5311   for (auto *PI : InheritedProtocols) {
5312     // If both the right and left sides have qualifiers.
5313     bool Adopts = false;
5314     for (auto *Proto : OPT->quals()) {
5315       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5316       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5317         break;
5318     }
5319     if (!Adopts)
5320       return false;
5321   }
5322   return true;
5323 }
5324 
5325 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5326 /// the given object type.
5327 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5328   llvm::FoldingSetNodeID ID;
5329   ObjCObjectPointerType::Profile(ID, ObjectT);
5330 
5331   void *InsertPos = nullptr;
5332   if (ObjCObjectPointerType *QT =
5333               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5334     return QualType(QT, 0);
5335 
5336   // Find the canonical object type.
5337   QualType Canonical;
5338   if (!ObjectT.isCanonical()) {
5339     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5340 
5341     // Regenerate InsertPos.
5342     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5343   }
5344 
5345   // No match.
5346   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5347   auto *QType =
5348     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5349 
5350   Types.push_back(QType);
5351   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5352   return QualType(QType, 0);
5353 }
5354 
5355 /// getObjCInterfaceType - Return the unique reference to the type for the
5356 /// specified ObjC interface decl. The list of protocols is optional.
5357 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5358                                           ObjCInterfaceDecl *PrevDecl) const {
5359   if (Decl->TypeForDecl)
5360     return QualType(Decl->TypeForDecl, 0);
5361 
5362   if (PrevDecl) {
5363     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5364     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5365     return QualType(PrevDecl->TypeForDecl, 0);
5366   }
5367 
5368   // Prefer the definition, if there is one.
5369   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5370     Decl = Def;
5371 
5372   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5373   auto *T = new (Mem) ObjCInterfaceType(Decl);
5374   Decl->TypeForDecl = T;
5375   Types.push_back(T);
5376   return QualType(T, 0);
5377 }
5378 
5379 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5380 /// TypeOfExprType AST's (since expression's are never shared). For example,
5381 /// multiple declarations that refer to "typeof(x)" all contain different
5382 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5383 /// on canonical type's (which are always unique).
5384 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5385   TypeOfExprType *toe;
5386   if (tofExpr->isTypeDependent()) {
5387     llvm::FoldingSetNodeID ID;
5388     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5389 
5390     void *InsertPos = nullptr;
5391     DependentTypeOfExprType *Canon
5392       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5393     if (Canon) {
5394       // We already have a "canonical" version of an identical, dependent
5395       // typeof(expr) type. Use that as our canonical type.
5396       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5397                                           QualType((TypeOfExprType*)Canon, 0));
5398     } else {
5399       // Build a new, canonical typeof(expr) type.
5400       Canon
5401         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5402       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5403       toe = Canon;
5404     }
5405   } else {
5406     QualType Canonical = getCanonicalType(tofExpr->getType());
5407     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5408   }
5409   Types.push_back(toe);
5410   return QualType(toe, 0);
5411 }
5412 
5413 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5414 /// TypeOfType nodes. The only motivation to unique these nodes would be
5415 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5416 /// an issue. This doesn't affect the type checker, since it operates
5417 /// on canonical types (which are always unique).
5418 QualType ASTContext::getTypeOfType(QualType tofType) const {
5419   QualType Canonical = getCanonicalType(tofType);
5420   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5421   Types.push_back(tot);
5422   return QualType(tot, 0);
5423 }
5424 
5425 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5426 /// nodes. This would never be helpful, since each such type has its own
5427 /// expression, and would not give a significant memory saving, since there
5428 /// is an Expr tree under each such type.
5429 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5430   DecltypeType *dt;
5431 
5432   // C++11 [temp.type]p2:
5433   //   If an expression e involves a template parameter, decltype(e) denotes a
5434   //   unique dependent type. Two such decltype-specifiers refer to the same
5435   //   type only if their expressions are equivalent (14.5.6.1).
5436   if (e->isInstantiationDependent()) {
5437     llvm::FoldingSetNodeID ID;
5438     DependentDecltypeType::Profile(ID, *this, e);
5439 
5440     void *InsertPos = nullptr;
5441     DependentDecltypeType *Canon
5442       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5443     if (!Canon) {
5444       // Build a new, canonical decltype(expr) type.
5445       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5446       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5447     }
5448     dt = new (*this, TypeAlignment)
5449         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5450   } else {
5451     dt = new (*this, TypeAlignment)
5452         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5453   }
5454   Types.push_back(dt);
5455   return QualType(dt, 0);
5456 }
5457 
5458 /// getUnaryTransformationType - We don't unique these, since the memory
5459 /// savings are minimal and these are rare.
5460 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5461                                            QualType UnderlyingType,
5462                                            UnaryTransformType::UTTKind Kind)
5463     const {
5464   UnaryTransformType *ut = nullptr;
5465 
5466   if (BaseType->isDependentType()) {
5467     // Look in the folding set for an existing type.
5468     llvm::FoldingSetNodeID ID;
5469     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5470 
5471     void *InsertPos = nullptr;
5472     DependentUnaryTransformType *Canon
5473       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5474 
5475     if (!Canon) {
5476       // Build a new, canonical __underlying_type(type) type.
5477       Canon = new (*this, TypeAlignment)
5478              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5479                                          Kind);
5480       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5481     }
5482     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5483                                                         QualType(), Kind,
5484                                                         QualType(Canon, 0));
5485   } else {
5486     QualType CanonType = getCanonicalType(UnderlyingType);
5487     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5488                                                         UnderlyingType, Kind,
5489                                                         CanonType);
5490   }
5491   Types.push_back(ut);
5492   return QualType(ut, 0);
5493 }
5494 
5495 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5496 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5497 /// canonical deduced-but-dependent 'auto' type.
5498 QualType
5499 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5500                         bool IsDependent, bool IsPack,
5501                         ConceptDecl *TypeConstraintConcept,
5502                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5503   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5504   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5505       !TypeConstraintConcept && !IsDependent)
5506     return getAutoDeductType();
5507 
5508   // Look in the folding set for an existing type.
5509   void *InsertPos = nullptr;
5510   llvm::FoldingSetNodeID ID;
5511   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5512                     TypeConstraintConcept, TypeConstraintArgs);
5513   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5514     return QualType(AT, 0);
5515 
5516   void *Mem = Allocate(sizeof(AutoType) +
5517                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5518                        TypeAlignment);
5519   auto *AT = new (Mem) AutoType(
5520       DeducedType, Keyword,
5521       (IsDependent ? TypeDependence::DependentInstantiation
5522                    : TypeDependence::None) |
5523           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5524       TypeConstraintConcept, TypeConstraintArgs);
5525   Types.push_back(AT);
5526   if (InsertPos)
5527     AutoTypes.InsertNode(AT, InsertPos);
5528   return QualType(AT, 0);
5529 }
5530 
5531 /// Return the uniqued reference to the deduced template specialization type
5532 /// which has been deduced to the given type, or to the canonical undeduced
5533 /// such type, or the canonical deduced-but-dependent such type.
5534 QualType ASTContext::getDeducedTemplateSpecializationType(
5535     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5536   // Look in the folding set for an existing type.
5537   void *InsertPos = nullptr;
5538   llvm::FoldingSetNodeID ID;
5539   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5540                                              IsDependent);
5541   if (DeducedTemplateSpecializationType *DTST =
5542           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5543     return QualType(DTST, 0);
5544 
5545   auto *DTST = new (*this, TypeAlignment)
5546       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5547   Types.push_back(DTST);
5548   if (InsertPos)
5549     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5550   return QualType(DTST, 0);
5551 }
5552 
5553 /// getAtomicType - Return the uniqued reference to the atomic type for
5554 /// the given value type.
5555 QualType ASTContext::getAtomicType(QualType T) const {
5556   // Unique pointers, to guarantee there is only one pointer of a particular
5557   // structure.
5558   llvm::FoldingSetNodeID ID;
5559   AtomicType::Profile(ID, T);
5560 
5561   void *InsertPos = nullptr;
5562   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5563     return QualType(AT, 0);
5564 
5565   // If the atomic value type isn't canonical, this won't be a canonical type
5566   // either, so fill in the canonical type field.
5567   QualType Canonical;
5568   if (!T.isCanonical()) {
5569     Canonical = getAtomicType(getCanonicalType(T));
5570 
5571     // Get the new insert position for the node we care about.
5572     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5573     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5574   }
5575   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5576   Types.push_back(New);
5577   AtomicTypes.InsertNode(New, InsertPos);
5578   return QualType(New, 0);
5579 }
5580 
5581 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5582 QualType ASTContext::getAutoDeductType() const {
5583   if (AutoDeductTy.isNull())
5584     AutoDeductTy = QualType(new (*this, TypeAlignment)
5585                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5586                                          TypeDependence::None,
5587                                          /*concept*/ nullptr, /*args*/ {}),
5588                             0);
5589   return AutoDeductTy;
5590 }
5591 
5592 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5593 QualType ASTContext::getAutoRRefDeductType() const {
5594   if (AutoRRefDeductTy.isNull())
5595     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5596   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5597   return AutoRRefDeductTy;
5598 }
5599 
5600 /// getTagDeclType - Return the unique reference to the type for the
5601 /// specified TagDecl (struct/union/class/enum) decl.
5602 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5603   assert(Decl);
5604   // FIXME: What is the design on getTagDeclType when it requires casting
5605   // away const?  mutable?
5606   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5607 }
5608 
5609 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5610 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5611 /// needs to agree with the definition in <stddef.h>.
5612 CanQualType ASTContext::getSizeType() const {
5613   return getFromTargetType(Target->getSizeType());
5614 }
5615 
5616 /// Return the unique signed counterpart of the integer type
5617 /// corresponding to size_t.
5618 CanQualType ASTContext::getSignedSizeType() const {
5619   return getFromTargetType(Target->getSignedSizeType());
5620 }
5621 
5622 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5623 CanQualType ASTContext::getIntMaxType() const {
5624   return getFromTargetType(Target->getIntMaxType());
5625 }
5626 
5627 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5628 CanQualType ASTContext::getUIntMaxType() const {
5629   return getFromTargetType(Target->getUIntMaxType());
5630 }
5631 
5632 /// getSignedWCharType - Return the type of "signed wchar_t".
5633 /// Used when in C++, as a GCC extension.
5634 QualType ASTContext::getSignedWCharType() const {
5635   // FIXME: derive from "Target" ?
5636   return WCharTy;
5637 }
5638 
5639 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5640 /// Used when in C++, as a GCC extension.
5641 QualType ASTContext::getUnsignedWCharType() const {
5642   // FIXME: derive from "Target" ?
5643   return UnsignedIntTy;
5644 }
5645 
5646 QualType ASTContext::getIntPtrType() const {
5647   return getFromTargetType(Target->getIntPtrType());
5648 }
5649 
5650 QualType ASTContext::getUIntPtrType() const {
5651   return getCorrespondingUnsignedType(getIntPtrType());
5652 }
5653 
5654 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5655 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5656 QualType ASTContext::getPointerDiffType() const {
5657   return getFromTargetType(Target->getPtrDiffType(0));
5658 }
5659 
5660 /// Return the unique unsigned counterpart of "ptrdiff_t"
5661 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5662 /// in the definition of %tu format specifier.
5663 QualType ASTContext::getUnsignedPointerDiffType() const {
5664   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5665 }
5666 
5667 /// Return the unique type for "pid_t" defined in
5668 /// <sys/types.h>. We need this to compute the correct type for vfork().
5669 QualType ASTContext::getProcessIDType() const {
5670   return getFromTargetType(Target->getProcessIDType());
5671 }
5672 
5673 //===----------------------------------------------------------------------===//
5674 //                              Type Operators
5675 //===----------------------------------------------------------------------===//
5676 
5677 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5678   // Push qualifiers into arrays, and then discard any remaining
5679   // qualifiers.
5680   T = getCanonicalType(T);
5681   T = getVariableArrayDecayedType(T);
5682   const Type *Ty = T.getTypePtr();
5683   QualType Result;
5684   if (isa<ArrayType>(Ty)) {
5685     Result = getArrayDecayedType(QualType(Ty,0));
5686   } else if (isa<FunctionType>(Ty)) {
5687     Result = getPointerType(QualType(Ty, 0));
5688   } else {
5689     Result = QualType(Ty, 0);
5690   }
5691 
5692   return CanQualType::CreateUnsafe(Result);
5693 }
5694 
5695 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5696                                              Qualifiers &quals) {
5697   SplitQualType splitType = type.getSplitUnqualifiedType();
5698 
5699   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5700   // the unqualified desugared type and then drops it on the floor.
5701   // We then have to strip that sugar back off with
5702   // getUnqualifiedDesugaredType(), which is silly.
5703   const auto *AT =
5704       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5705 
5706   // If we don't have an array, just use the results in splitType.
5707   if (!AT) {
5708     quals = splitType.Quals;
5709     return QualType(splitType.Ty, 0);
5710   }
5711 
5712   // Otherwise, recurse on the array's element type.
5713   QualType elementType = AT->getElementType();
5714   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5715 
5716   // If that didn't change the element type, AT has no qualifiers, so we
5717   // can just use the results in splitType.
5718   if (elementType == unqualElementType) {
5719     assert(quals.empty()); // from the recursive call
5720     quals = splitType.Quals;
5721     return QualType(splitType.Ty, 0);
5722   }
5723 
5724   // Otherwise, add in the qualifiers from the outermost type, then
5725   // build the type back up.
5726   quals.addConsistentQualifiers(splitType.Quals);
5727 
5728   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5729     return getConstantArrayType(unqualElementType, CAT->getSize(),
5730                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5731   }
5732 
5733   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5734     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5735   }
5736 
5737   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5738     return getVariableArrayType(unqualElementType,
5739                                 VAT->getSizeExpr(),
5740                                 VAT->getSizeModifier(),
5741                                 VAT->getIndexTypeCVRQualifiers(),
5742                                 VAT->getBracketsRange());
5743   }
5744 
5745   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5746   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5747                                     DSAT->getSizeModifier(), 0,
5748                                     SourceRange());
5749 }
5750 
5751 /// Attempt to unwrap two types that may both be array types with the same bound
5752 /// (or both be array types of unknown bound) for the purpose of comparing the
5753 /// cv-decomposition of two types per C++ [conv.qual].
5754 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5755   bool UnwrappedAny = false;
5756   while (true) {
5757     auto *AT1 = getAsArrayType(T1);
5758     if (!AT1) return UnwrappedAny;
5759 
5760     auto *AT2 = getAsArrayType(T2);
5761     if (!AT2) return UnwrappedAny;
5762 
5763     // If we don't have two array types with the same constant bound nor two
5764     // incomplete array types, we've unwrapped everything we can.
5765     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5766       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5767       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5768         return UnwrappedAny;
5769     } else if (!isa<IncompleteArrayType>(AT1) ||
5770                !isa<IncompleteArrayType>(AT2)) {
5771       return UnwrappedAny;
5772     }
5773 
5774     T1 = AT1->getElementType();
5775     T2 = AT2->getElementType();
5776     UnwrappedAny = true;
5777   }
5778 }
5779 
5780 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5781 ///
5782 /// If T1 and T2 are both pointer types of the same kind, or both array types
5783 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5784 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5785 ///
5786 /// This function will typically be called in a loop that successively
5787 /// "unwraps" pointer and pointer-to-member types to compare them at each
5788 /// level.
5789 ///
5790 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5791 /// pair of types that can't be unwrapped further.
5792 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5793   UnwrapSimilarArrayTypes(T1, T2);
5794 
5795   const auto *T1PtrType = T1->getAs<PointerType>();
5796   const auto *T2PtrType = T2->getAs<PointerType>();
5797   if (T1PtrType && T2PtrType) {
5798     T1 = T1PtrType->getPointeeType();
5799     T2 = T2PtrType->getPointeeType();
5800     return true;
5801   }
5802 
5803   const auto *T1MPType = T1->getAs<MemberPointerType>();
5804   const auto *T2MPType = T2->getAs<MemberPointerType>();
5805   if (T1MPType && T2MPType &&
5806       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5807                              QualType(T2MPType->getClass(), 0))) {
5808     T1 = T1MPType->getPointeeType();
5809     T2 = T2MPType->getPointeeType();
5810     return true;
5811   }
5812 
5813   if (getLangOpts().ObjC) {
5814     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5815     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5816     if (T1OPType && T2OPType) {
5817       T1 = T1OPType->getPointeeType();
5818       T2 = T2OPType->getPointeeType();
5819       return true;
5820     }
5821   }
5822 
5823   // FIXME: Block pointers, too?
5824 
5825   return false;
5826 }
5827 
5828 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5829   while (true) {
5830     Qualifiers Quals;
5831     T1 = getUnqualifiedArrayType(T1, Quals);
5832     T2 = getUnqualifiedArrayType(T2, Quals);
5833     if (hasSameType(T1, T2))
5834       return true;
5835     if (!UnwrapSimilarTypes(T1, T2))
5836       return false;
5837   }
5838 }
5839 
5840 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5841   while (true) {
5842     Qualifiers Quals1, Quals2;
5843     T1 = getUnqualifiedArrayType(T1, Quals1);
5844     T2 = getUnqualifiedArrayType(T2, Quals2);
5845 
5846     Quals1.removeCVRQualifiers();
5847     Quals2.removeCVRQualifiers();
5848     if (Quals1 != Quals2)
5849       return false;
5850 
5851     if (hasSameType(T1, T2))
5852       return true;
5853 
5854     if (!UnwrapSimilarTypes(T1, T2))
5855       return false;
5856   }
5857 }
5858 
5859 DeclarationNameInfo
5860 ASTContext::getNameForTemplate(TemplateName Name,
5861                                SourceLocation NameLoc) const {
5862   switch (Name.getKind()) {
5863   case TemplateName::QualifiedTemplate:
5864   case TemplateName::Template:
5865     // DNInfo work in progress: CHECKME: what about DNLoc?
5866     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5867                                NameLoc);
5868 
5869   case TemplateName::OverloadedTemplate: {
5870     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5871     // DNInfo work in progress: CHECKME: what about DNLoc?
5872     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5873   }
5874 
5875   case TemplateName::AssumedTemplate: {
5876     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5877     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5878   }
5879 
5880   case TemplateName::DependentTemplate: {
5881     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5882     DeclarationName DName;
5883     if (DTN->isIdentifier()) {
5884       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5885       return DeclarationNameInfo(DName, NameLoc);
5886     } else {
5887       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5888       // DNInfo work in progress: FIXME: source locations?
5889       DeclarationNameLoc DNLoc =
5890           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
5891       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5892     }
5893   }
5894 
5895   case TemplateName::SubstTemplateTemplateParm: {
5896     SubstTemplateTemplateParmStorage *subst
5897       = Name.getAsSubstTemplateTemplateParm();
5898     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5899                                NameLoc);
5900   }
5901 
5902   case TemplateName::SubstTemplateTemplateParmPack: {
5903     SubstTemplateTemplateParmPackStorage *subst
5904       = Name.getAsSubstTemplateTemplateParmPack();
5905     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5906                                NameLoc);
5907   }
5908   }
5909 
5910   llvm_unreachable("bad template name kind!");
5911 }
5912 
5913 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5914   switch (Name.getKind()) {
5915   case TemplateName::QualifiedTemplate:
5916   case TemplateName::Template: {
5917     TemplateDecl *Template = Name.getAsTemplateDecl();
5918     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5919       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5920 
5921     // The canonical template name is the canonical template declaration.
5922     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5923   }
5924 
5925   case TemplateName::OverloadedTemplate:
5926   case TemplateName::AssumedTemplate:
5927     llvm_unreachable("cannot canonicalize unresolved template");
5928 
5929   case TemplateName::DependentTemplate: {
5930     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5931     assert(DTN && "Non-dependent template names must refer to template decls.");
5932     return DTN->CanonicalTemplateName;
5933   }
5934 
5935   case TemplateName::SubstTemplateTemplateParm: {
5936     SubstTemplateTemplateParmStorage *subst
5937       = Name.getAsSubstTemplateTemplateParm();
5938     return getCanonicalTemplateName(subst->getReplacement());
5939   }
5940 
5941   case TemplateName::SubstTemplateTemplateParmPack: {
5942     SubstTemplateTemplateParmPackStorage *subst
5943                                   = Name.getAsSubstTemplateTemplateParmPack();
5944     TemplateTemplateParmDecl *canonParameter
5945       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5946     TemplateArgument canonArgPack
5947       = getCanonicalTemplateArgument(subst->getArgumentPack());
5948     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5949   }
5950   }
5951 
5952   llvm_unreachable("bad template name!");
5953 }
5954 
5955 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5956   X = getCanonicalTemplateName(X);
5957   Y = getCanonicalTemplateName(Y);
5958   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5959 }
5960 
5961 TemplateArgument
5962 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5963   switch (Arg.getKind()) {
5964     case TemplateArgument::Null:
5965       return Arg;
5966 
5967     case TemplateArgument::Expression:
5968       return Arg;
5969 
5970     case TemplateArgument::Declaration: {
5971       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5972       return TemplateArgument(D, Arg.getParamTypeForDecl());
5973     }
5974 
5975     case TemplateArgument::NullPtr:
5976       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5977                               /*isNullPtr*/true);
5978 
5979     case TemplateArgument::Template:
5980       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5981 
5982     case TemplateArgument::TemplateExpansion:
5983       return TemplateArgument(getCanonicalTemplateName(
5984                                          Arg.getAsTemplateOrTemplatePattern()),
5985                               Arg.getNumTemplateExpansions());
5986 
5987     case TemplateArgument::Integral:
5988       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5989 
5990     case TemplateArgument::Type:
5991       return TemplateArgument(getCanonicalType(Arg.getAsType()));
5992 
5993     case TemplateArgument::Pack: {
5994       if (Arg.pack_size() == 0)
5995         return Arg;
5996 
5997       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5998       unsigned Idx = 0;
5999       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6000                                         AEnd = Arg.pack_end();
6001            A != AEnd; (void)++A, ++Idx)
6002         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6003 
6004       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6005     }
6006   }
6007 
6008   // Silence GCC warning
6009   llvm_unreachable("Unhandled template argument kind");
6010 }
6011 
6012 NestedNameSpecifier *
6013 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6014   if (!NNS)
6015     return nullptr;
6016 
6017   switch (NNS->getKind()) {
6018   case NestedNameSpecifier::Identifier:
6019     // Canonicalize the prefix but keep the identifier the same.
6020     return NestedNameSpecifier::Create(*this,
6021                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6022                                        NNS->getAsIdentifier());
6023 
6024   case NestedNameSpecifier::Namespace:
6025     // A namespace is canonical; build a nested-name-specifier with
6026     // this namespace and no prefix.
6027     return NestedNameSpecifier::Create(*this, nullptr,
6028                                  NNS->getAsNamespace()->getOriginalNamespace());
6029 
6030   case NestedNameSpecifier::NamespaceAlias:
6031     // A namespace is canonical; build a nested-name-specifier with
6032     // this namespace and no prefix.
6033     return NestedNameSpecifier::Create(*this, nullptr,
6034                                     NNS->getAsNamespaceAlias()->getNamespace()
6035                                                       ->getOriginalNamespace());
6036 
6037   case NestedNameSpecifier::TypeSpec:
6038   case NestedNameSpecifier::TypeSpecWithTemplate: {
6039     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
6040 
6041     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6042     // break it apart into its prefix and identifier, then reconsititute those
6043     // as the canonical nested-name-specifier. This is required to canonicalize
6044     // a dependent nested-name-specifier involving typedefs of dependent-name
6045     // types, e.g.,
6046     //   typedef typename T::type T1;
6047     //   typedef typename T1::type T2;
6048     if (const auto *DNT = T->getAs<DependentNameType>())
6049       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6050                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6051 
6052     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
6053     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
6054     // first place?
6055     return NestedNameSpecifier::Create(*this, nullptr, false,
6056                                        const_cast<Type *>(T.getTypePtr()));
6057   }
6058 
6059   case NestedNameSpecifier::Global:
6060   case NestedNameSpecifier::Super:
6061     // The global specifier and __super specifer are canonical and unique.
6062     return NNS;
6063   }
6064 
6065   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6066 }
6067 
6068 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6069   // Handle the non-qualified case efficiently.
6070   if (!T.hasLocalQualifiers()) {
6071     // Handle the common positive case fast.
6072     if (const auto *AT = dyn_cast<ArrayType>(T))
6073       return AT;
6074   }
6075 
6076   // Handle the common negative case fast.
6077   if (!isa<ArrayType>(T.getCanonicalType()))
6078     return nullptr;
6079 
6080   // Apply any qualifiers from the array type to the element type.  This
6081   // implements C99 6.7.3p8: "If the specification of an array type includes
6082   // any type qualifiers, the element type is so qualified, not the array type."
6083 
6084   // If we get here, we either have type qualifiers on the type, or we have
6085   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6086   // we must propagate them down into the element type.
6087 
6088   SplitQualType split = T.getSplitDesugaredType();
6089   Qualifiers qs = split.Quals;
6090 
6091   // If we have a simple case, just return now.
6092   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6093   if (!ATy || qs.empty())
6094     return ATy;
6095 
6096   // Otherwise, we have an array and we have qualifiers on it.  Push the
6097   // qualifiers into the array element type and return a new array type.
6098   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6099 
6100   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6101     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6102                                                 CAT->getSizeExpr(),
6103                                                 CAT->getSizeModifier(),
6104                                            CAT->getIndexTypeCVRQualifiers()));
6105   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6106     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6107                                                   IAT->getSizeModifier(),
6108                                            IAT->getIndexTypeCVRQualifiers()));
6109 
6110   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6111     return cast<ArrayType>(
6112                      getDependentSizedArrayType(NewEltTy,
6113                                                 DSAT->getSizeExpr(),
6114                                                 DSAT->getSizeModifier(),
6115                                               DSAT->getIndexTypeCVRQualifiers(),
6116                                                 DSAT->getBracketsRange()));
6117 
6118   const auto *VAT = cast<VariableArrayType>(ATy);
6119   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6120                                               VAT->getSizeExpr(),
6121                                               VAT->getSizeModifier(),
6122                                               VAT->getIndexTypeCVRQualifiers(),
6123                                               VAT->getBracketsRange()));
6124 }
6125 
6126 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6127   if (T->isArrayType() || T->isFunctionType())
6128     return getDecayedType(T);
6129   return T;
6130 }
6131 
6132 QualType ASTContext::getSignatureParameterType(QualType T) const {
6133   T = getVariableArrayDecayedType(T);
6134   T = getAdjustedParameterType(T);
6135   return T.getUnqualifiedType();
6136 }
6137 
6138 QualType ASTContext::getExceptionObjectType(QualType T) const {
6139   // C++ [except.throw]p3:
6140   //   A throw-expression initializes a temporary object, called the exception
6141   //   object, the type of which is determined by removing any top-level
6142   //   cv-qualifiers from the static type of the operand of throw and adjusting
6143   //   the type from "array of T" or "function returning T" to "pointer to T"
6144   //   or "pointer to function returning T", [...]
6145   T = getVariableArrayDecayedType(T);
6146   if (T->isArrayType() || T->isFunctionType())
6147     T = getDecayedType(T);
6148   return T.getUnqualifiedType();
6149 }
6150 
6151 /// getArrayDecayedType - Return the properly qualified result of decaying the
6152 /// specified array type to a pointer.  This operation is non-trivial when
6153 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6154 /// this returns a pointer to a properly qualified element of the array.
6155 ///
6156 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6157 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6158   // Get the element type with 'getAsArrayType' so that we don't lose any
6159   // typedefs in the element type of the array.  This also handles propagation
6160   // of type qualifiers from the array type into the element type if present
6161   // (C99 6.7.3p8).
6162   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6163   assert(PrettyArrayType && "Not an array type!");
6164 
6165   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6166 
6167   // int x[restrict 4] ->  int *restrict
6168   QualType Result = getQualifiedType(PtrTy,
6169                                      PrettyArrayType->getIndexTypeQualifiers());
6170 
6171   // int x[_Nullable] -> int * _Nullable
6172   if (auto Nullability = Ty->getNullability(*this)) {
6173     Result = const_cast<ASTContext *>(this)->getAttributedType(
6174         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6175   }
6176   return Result;
6177 }
6178 
6179 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6180   return getBaseElementType(array->getElementType());
6181 }
6182 
6183 QualType ASTContext::getBaseElementType(QualType type) const {
6184   Qualifiers qs;
6185   while (true) {
6186     SplitQualType split = type.getSplitDesugaredType();
6187     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6188     if (!array) break;
6189 
6190     type = array->getElementType();
6191     qs.addConsistentQualifiers(split.Quals);
6192   }
6193 
6194   return getQualifiedType(type, qs);
6195 }
6196 
6197 /// getConstantArrayElementCount - Returns number of constant array elements.
6198 uint64_t
6199 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6200   uint64_t ElementCount = 1;
6201   do {
6202     ElementCount *= CA->getSize().getZExtValue();
6203     CA = dyn_cast_or_null<ConstantArrayType>(
6204       CA->getElementType()->getAsArrayTypeUnsafe());
6205   } while (CA);
6206   return ElementCount;
6207 }
6208 
6209 /// getFloatingRank - Return a relative rank for floating point types.
6210 /// This routine will assert if passed a built-in type that isn't a float.
6211 static FloatingRank getFloatingRank(QualType T) {
6212   if (const auto *CT = T->getAs<ComplexType>())
6213     return getFloatingRank(CT->getElementType());
6214 
6215   switch (T->castAs<BuiltinType>()->getKind()) {
6216   default: llvm_unreachable("getFloatingRank(): not a floating type");
6217   case BuiltinType::Float16:    return Float16Rank;
6218   case BuiltinType::Half:       return HalfRank;
6219   case BuiltinType::Float:      return FloatRank;
6220   case BuiltinType::Double:     return DoubleRank;
6221   case BuiltinType::LongDouble: return LongDoubleRank;
6222   case BuiltinType::Float128:   return Float128Rank;
6223   case BuiltinType::BFloat16:   return BFloat16Rank;
6224   }
6225 }
6226 
6227 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6228 /// point or a complex type (based on typeDomain/typeSize).
6229 /// 'typeDomain' is a real floating point or complex type.
6230 /// 'typeSize' is a real floating point or complex type.
6231 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6232                                                        QualType Domain) const {
6233   FloatingRank EltRank = getFloatingRank(Size);
6234   if (Domain->isComplexType()) {
6235     switch (EltRank) {
6236     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6237     case Float16Rank:
6238     case HalfRank: llvm_unreachable("Complex half is not supported");
6239     case FloatRank:      return FloatComplexTy;
6240     case DoubleRank:     return DoubleComplexTy;
6241     case LongDoubleRank: return LongDoubleComplexTy;
6242     case Float128Rank:   return Float128ComplexTy;
6243     }
6244   }
6245 
6246   assert(Domain->isRealFloatingType() && "Unknown domain!");
6247   switch (EltRank) {
6248   case Float16Rank:    return HalfTy;
6249   case BFloat16Rank:   return BFloat16Ty;
6250   case HalfRank:       return HalfTy;
6251   case FloatRank:      return FloatTy;
6252   case DoubleRank:     return DoubleTy;
6253   case LongDoubleRank: return LongDoubleTy;
6254   case Float128Rank:   return Float128Ty;
6255   }
6256   llvm_unreachable("getFloatingRank(): illegal value for rank");
6257 }
6258 
6259 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6260 /// point types, ignoring the domain of the type (i.e. 'double' ==
6261 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6262 /// LHS < RHS, return -1.
6263 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6264   FloatingRank LHSR = getFloatingRank(LHS);
6265   FloatingRank RHSR = getFloatingRank(RHS);
6266 
6267   if (LHSR == RHSR)
6268     return 0;
6269   if (LHSR > RHSR)
6270     return 1;
6271   return -1;
6272 }
6273 
6274 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6275   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6276     return 0;
6277   return getFloatingTypeOrder(LHS, RHS);
6278 }
6279 
6280 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6281 /// routine will assert if passed a built-in type that isn't an integer or enum,
6282 /// or if it is not canonicalized.
6283 unsigned ASTContext::getIntegerRank(const Type *T) const {
6284   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6285 
6286   // Results in this 'losing' to any type of the same size, but winning if
6287   // larger.
6288   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6289     return 0 + (EIT->getNumBits() << 3);
6290 
6291   switch (cast<BuiltinType>(T)->getKind()) {
6292   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6293   case BuiltinType::Bool:
6294     return 1 + (getIntWidth(BoolTy) << 3);
6295   case BuiltinType::Char_S:
6296   case BuiltinType::Char_U:
6297   case BuiltinType::SChar:
6298   case BuiltinType::UChar:
6299     return 2 + (getIntWidth(CharTy) << 3);
6300   case BuiltinType::Short:
6301   case BuiltinType::UShort:
6302     return 3 + (getIntWidth(ShortTy) << 3);
6303   case BuiltinType::Int:
6304   case BuiltinType::UInt:
6305     return 4 + (getIntWidth(IntTy) << 3);
6306   case BuiltinType::Long:
6307   case BuiltinType::ULong:
6308     return 5 + (getIntWidth(LongTy) << 3);
6309   case BuiltinType::LongLong:
6310   case BuiltinType::ULongLong:
6311     return 6 + (getIntWidth(LongLongTy) << 3);
6312   case BuiltinType::Int128:
6313   case BuiltinType::UInt128:
6314     return 7 + (getIntWidth(Int128Ty) << 3);
6315   }
6316 }
6317 
6318 /// Whether this is a promotable bitfield reference according
6319 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6320 ///
6321 /// \returns the type this bit-field will promote to, or NULL if no
6322 /// promotion occurs.
6323 QualType ASTContext::isPromotableBitField(Expr *E) const {
6324   if (E->isTypeDependent() || E->isValueDependent())
6325     return {};
6326 
6327   // C++ [conv.prom]p5:
6328   //    If the bit-field has an enumerated type, it is treated as any other
6329   //    value of that type for promotion purposes.
6330   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6331     return {};
6332 
6333   // FIXME: We should not do this unless E->refersToBitField() is true. This
6334   // matters in C where getSourceBitField() will find bit-fields for various
6335   // cases where the source expression is not a bit-field designator.
6336 
6337   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6338   if (!Field)
6339     return {};
6340 
6341   QualType FT = Field->getType();
6342 
6343   uint64_t BitWidth = Field->getBitWidthValue(*this);
6344   uint64_t IntSize = getTypeSize(IntTy);
6345   // C++ [conv.prom]p5:
6346   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6347   //   int if int can represent all the values of the bit-field; otherwise, it
6348   //   can be converted to unsigned int if unsigned int can represent all the
6349   //   values of the bit-field. If the bit-field is larger yet, no integral
6350   //   promotion applies to it.
6351   // C11 6.3.1.1/2:
6352   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6353   //   If an int can represent all values of the original type (as restricted by
6354   //   the width, for a bit-field), the value is converted to an int; otherwise,
6355   //   it is converted to an unsigned int.
6356   //
6357   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6358   //        We perform that promotion here to match GCC and C++.
6359   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6360   //        greater than that of 'int'. We perform that promotion to match GCC.
6361   if (BitWidth < IntSize)
6362     return IntTy;
6363 
6364   if (BitWidth == IntSize)
6365     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6366 
6367   // Bit-fields wider than int are not subject to promotions, and therefore act
6368   // like the base type. GCC has some weird bugs in this area that we
6369   // deliberately do not follow (GCC follows a pre-standard resolution to
6370   // C's DR315 which treats bit-width as being part of the type, and this leaks
6371   // into their semantics in some cases).
6372   return {};
6373 }
6374 
6375 /// getPromotedIntegerType - Returns the type that Promotable will
6376 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6377 /// integer type.
6378 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6379   assert(!Promotable.isNull());
6380   assert(Promotable->isPromotableIntegerType());
6381   if (const auto *ET = Promotable->getAs<EnumType>())
6382     return ET->getDecl()->getPromotionType();
6383 
6384   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6385     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6386     // (3.9.1) can be converted to a prvalue of the first of the following
6387     // types that can represent all the values of its underlying type:
6388     // int, unsigned int, long int, unsigned long int, long long int, or
6389     // unsigned long long int [...]
6390     // FIXME: Is there some better way to compute this?
6391     if (BT->getKind() == BuiltinType::WChar_S ||
6392         BT->getKind() == BuiltinType::WChar_U ||
6393         BT->getKind() == BuiltinType::Char8 ||
6394         BT->getKind() == BuiltinType::Char16 ||
6395         BT->getKind() == BuiltinType::Char32) {
6396       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6397       uint64_t FromSize = getTypeSize(BT);
6398       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6399                                   LongLongTy, UnsignedLongLongTy };
6400       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6401         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6402         if (FromSize < ToSize ||
6403             (FromSize == ToSize &&
6404              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6405           return PromoteTypes[Idx];
6406       }
6407       llvm_unreachable("char type should fit into long long");
6408     }
6409   }
6410 
6411   // At this point, we should have a signed or unsigned integer type.
6412   if (Promotable->isSignedIntegerType())
6413     return IntTy;
6414   uint64_t PromotableSize = getIntWidth(Promotable);
6415   uint64_t IntSize = getIntWidth(IntTy);
6416   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6417   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6418 }
6419 
6420 /// Recurses in pointer/array types until it finds an objc retainable
6421 /// type and returns its ownership.
6422 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6423   while (!T.isNull()) {
6424     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6425       return T.getObjCLifetime();
6426     if (T->isArrayType())
6427       T = getBaseElementType(T);
6428     else if (const auto *PT = T->getAs<PointerType>())
6429       T = PT->getPointeeType();
6430     else if (const auto *RT = T->getAs<ReferenceType>())
6431       T = RT->getPointeeType();
6432     else
6433       break;
6434   }
6435 
6436   return Qualifiers::OCL_None;
6437 }
6438 
6439 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6440   // Incomplete enum types are not treated as integer types.
6441   // FIXME: In C++, enum types are never integer types.
6442   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6443     return ET->getDecl()->getIntegerType().getTypePtr();
6444   return nullptr;
6445 }
6446 
6447 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6448 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6449 /// LHS < RHS, return -1.
6450 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6451   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6452   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6453 
6454   // Unwrap enums to their underlying type.
6455   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6456     LHSC = getIntegerTypeForEnum(ET);
6457   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6458     RHSC = getIntegerTypeForEnum(ET);
6459 
6460   if (LHSC == RHSC) return 0;
6461 
6462   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6463   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6464 
6465   unsigned LHSRank = getIntegerRank(LHSC);
6466   unsigned RHSRank = getIntegerRank(RHSC);
6467 
6468   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6469     if (LHSRank == RHSRank) return 0;
6470     return LHSRank > RHSRank ? 1 : -1;
6471   }
6472 
6473   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6474   if (LHSUnsigned) {
6475     // If the unsigned [LHS] type is larger, return it.
6476     if (LHSRank >= RHSRank)
6477       return 1;
6478 
6479     // If the signed type can represent all values of the unsigned type, it
6480     // wins.  Because we are dealing with 2's complement and types that are
6481     // powers of two larger than each other, this is always safe.
6482     return -1;
6483   }
6484 
6485   // If the unsigned [RHS] type is larger, return it.
6486   if (RHSRank >= LHSRank)
6487     return -1;
6488 
6489   // If the signed type can represent all values of the unsigned type, it
6490   // wins.  Because we are dealing with 2's complement and types that are
6491   // powers of two larger than each other, this is always safe.
6492   return 1;
6493 }
6494 
6495 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6496   if (CFConstantStringTypeDecl)
6497     return CFConstantStringTypeDecl;
6498 
6499   assert(!CFConstantStringTagDecl &&
6500          "tag and typedef should be initialized together");
6501   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6502   CFConstantStringTagDecl->startDefinition();
6503 
6504   struct {
6505     QualType Type;
6506     const char *Name;
6507   } Fields[5];
6508   unsigned Count = 0;
6509 
6510   /// Objective-C ABI
6511   ///
6512   ///    typedef struct __NSConstantString_tag {
6513   ///      const int *isa;
6514   ///      int flags;
6515   ///      const char *str;
6516   ///      long length;
6517   ///    } __NSConstantString;
6518   ///
6519   /// Swift ABI (4.1, 4.2)
6520   ///
6521   ///    typedef struct __NSConstantString_tag {
6522   ///      uintptr_t _cfisa;
6523   ///      uintptr_t _swift_rc;
6524   ///      _Atomic(uint64_t) _cfinfoa;
6525   ///      const char *_ptr;
6526   ///      uint32_t _length;
6527   ///    } __NSConstantString;
6528   ///
6529   /// Swift ABI (5.0)
6530   ///
6531   ///    typedef struct __NSConstantString_tag {
6532   ///      uintptr_t _cfisa;
6533   ///      uintptr_t _swift_rc;
6534   ///      _Atomic(uint64_t) _cfinfoa;
6535   ///      const char *_ptr;
6536   ///      uintptr_t _length;
6537   ///    } __NSConstantString;
6538 
6539   const auto CFRuntime = getLangOpts().CFRuntime;
6540   if (static_cast<unsigned>(CFRuntime) <
6541       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6542     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6543     Fields[Count++] = { IntTy, "flags" };
6544     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6545     Fields[Count++] = { LongTy, "length" };
6546   } else {
6547     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6548     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6549     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6550     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6551     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6552         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6553       Fields[Count++] = { IntTy, "_ptr" };
6554     else
6555       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6556   }
6557 
6558   // Create fields
6559   for (unsigned i = 0; i < Count; ++i) {
6560     FieldDecl *Field =
6561         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6562                           SourceLocation(), &Idents.get(Fields[i].Name),
6563                           Fields[i].Type, /*TInfo=*/nullptr,
6564                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6565     Field->setAccess(AS_public);
6566     CFConstantStringTagDecl->addDecl(Field);
6567   }
6568 
6569   CFConstantStringTagDecl->completeDefinition();
6570   // This type is designed to be compatible with NSConstantString, but cannot
6571   // use the same name, since NSConstantString is an interface.
6572   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6573   CFConstantStringTypeDecl =
6574       buildImplicitTypedef(tagType, "__NSConstantString");
6575 
6576   return CFConstantStringTypeDecl;
6577 }
6578 
6579 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6580   if (!CFConstantStringTagDecl)
6581     getCFConstantStringDecl(); // Build the tag and the typedef.
6582   return CFConstantStringTagDecl;
6583 }
6584 
6585 // getCFConstantStringType - Return the type used for constant CFStrings.
6586 QualType ASTContext::getCFConstantStringType() const {
6587   return getTypedefType(getCFConstantStringDecl());
6588 }
6589 
6590 QualType ASTContext::getObjCSuperType() const {
6591   if (ObjCSuperType.isNull()) {
6592     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6593     TUDecl->addDecl(ObjCSuperTypeDecl);
6594     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6595   }
6596   return ObjCSuperType;
6597 }
6598 
6599 void ASTContext::setCFConstantStringType(QualType T) {
6600   const auto *TD = T->castAs<TypedefType>();
6601   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6602   const auto *TagType =
6603       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6604   CFConstantStringTagDecl = TagType->getDecl();
6605 }
6606 
6607 QualType ASTContext::getBlockDescriptorType() const {
6608   if (BlockDescriptorType)
6609     return getTagDeclType(BlockDescriptorType);
6610 
6611   RecordDecl *RD;
6612   // FIXME: Needs the FlagAppleBlock bit.
6613   RD = buildImplicitRecord("__block_descriptor");
6614   RD->startDefinition();
6615 
6616   QualType FieldTypes[] = {
6617     UnsignedLongTy,
6618     UnsignedLongTy,
6619   };
6620 
6621   static const char *const FieldNames[] = {
6622     "reserved",
6623     "Size"
6624   };
6625 
6626   for (size_t i = 0; i < 2; ++i) {
6627     FieldDecl *Field = FieldDecl::Create(
6628         *this, RD, SourceLocation(), SourceLocation(),
6629         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6630         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6631     Field->setAccess(AS_public);
6632     RD->addDecl(Field);
6633   }
6634 
6635   RD->completeDefinition();
6636 
6637   BlockDescriptorType = RD;
6638 
6639   return getTagDeclType(BlockDescriptorType);
6640 }
6641 
6642 QualType ASTContext::getBlockDescriptorExtendedType() const {
6643   if (BlockDescriptorExtendedType)
6644     return getTagDeclType(BlockDescriptorExtendedType);
6645 
6646   RecordDecl *RD;
6647   // FIXME: Needs the FlagAppleBlock bit.
6648   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6649   RD->startDefinition();
6650 
6651   QualType FieldTypes[] = {
6652     UnsignedLongTy,
6653     UnsignedLongTy,
6654     getPointerType(VoidPtrTy),
6655     getPointerType(VoidPtrTy)
6656   };
6657 
6658   static const char *const FieldNames[] = {
6659     "reserved",
6660     "Size",
6661     "CopyFuncPtr",
6662     "DestroyFuncPtr"
6663   };
6664 
6665   for (size_t i = 0; i < 4; ++i) {
6666     FieldDecl *Field = FieldDecl::Create(
6667         *this, RD, SourceLocation(), SourceLocation(),
6668         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6669         /*BitWidth=*/nullptr,
6670         /*Mutable=*/false, ICIS_NoInit);
6671     Field->setAccess(AS_public);
6672     RD->addDecl(Field);
6673   }
6674 
6675   RD->completeDefinition();
6676 
6677   BlockDescriptorExtendedType = RD;
6678   return getTagDeclType(BlockDescriptorExtendedType);
6679 }
6680 
6681 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6682   const auto *BT = dyn_cast<BuiltinType>(T);
6683 
6684   if (!BT) {
6685     if (isa<PipeType>(T))
6686       return OCLTK_Pipe;
6687 
6688     return OCLTK_Default;
6689   }
6690 
6691   switch (BT->getKind()) {
6692 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6693   case BuiltinType::Id:                                                        \
6694     return OCLTK_Image;
6695 #include "clang/Basic/OpenCLImageTypes.def"
6696 
6697   case BuiltinType::OCLClkEvent:
6698     return OCLTK_ClkEvent;
6699 
6700   case BuiltinType::OCLEvent:
6701     return OCLTK_Event;
6702 
6703   case BuiltinType::OCLQueue:
6704     return OCLTK_Queue;
6705 
6706   case BuiltinType::OCLReserveID:
6707     return OCLTK_ReserveID;
6708 
6709   case BuiltinType::OCLSampler:
6710     return OCLTK_Sampler;
6711 
6712   default:
6713     return OCLTK_Default;
6714   }
6715 }
6716 
6717 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6718   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6719 }
6720 
6721 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6722 /// requires copy/dispose. Note that this must match the logic
6723 /// in buildByrefHelpers.
6724 bool ASTContext::BlockRequiresCopying(QualType Ty,
6725                                       const VarDecl *D) {
6726   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6727     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6728     if (!copyExpr && record->hasTrivialDestructor()) return false;
6729 
6730     return true;
6731   }
6732 
6733   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6734   // move or destroy.
6735   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6736     return true;
6737 
6738   if (!Ty->isObjCRetainableType()) return false;
6739 
6740   Qualifiers qs = Ty.getQualifiers();
6741 
6742   // If we have lifetime, that dominates.
6743   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6744     switch (lifetime) {
6745       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6746 
6747       // These are just bits as far as the runtime is concerned.
6748       case Qualifiers::OCL_ExplicitNone:
6749       case Qualifiers::OCL_Autoreleasing:
6750         return false;
6751 
6752       // These cases should have been taken care of when checking the type's
6753       // non-triviality.
6754       case Qualifiers::OCL_Weak:
6755       case Qualifiers::OCL_Strong:
6756         llvm_unreachable("impossible");
6757     }
6758     llvm_unreachable("fell out of lifetime switch!");
6759   }
6760   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6761           Ty->isObjCObjectPointerType());
6762 }
6763 
6764 bool ASTContext::getByrefLifetime(QualType Ty,
6765                               Qualifiers::ObjCLifetime &LifeTime,
6766                               bool &HasByrefExtendedLayout) const {
6767   if (!getLangOpts().ObjC ||
6768       getLangOpts().getGC() != LangOptions::NonGC)
6769     return false;
6770 
6771   HasByrefExtendedLayout = false;
6772   if (Ty->isRecordType()) {
6773     HasByrefExtendedLayout = true;
6774     LifeTime = Qualifiers::OCL_None;
6775   } else if ((LifeTime = Ty.getObjCLifetime())) {
6776     // Honor the ARC qualifiers.
6777   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6778     // The MRR rule.
6779     LifeTime = Qualifiers::OCL_ExplicitNone;
6780   } else {
6781     LifeTime = Qualifiers::OCL_None;
6782   }
6783   return true;
6784 }
6785 
6786 CanQualType ASTContext::getNSUIntegerType() const {
6787   assert(Target && "Expected target to be initialized");
6788   const llvm::Triple &T = Target->getTriple();
6789   // Windows is LLP64 rather than LP64
6790   if (T.isOSWindows() && T.isArch64Bit())
6791     return UnsignedLongLongTy;
6792   return UnsignedLongTy;
6793 }
6794 
6795 CanQualType ASTContext::getNSIntegerType() const {
6796   assert(Target && "Expected target to be initialized");
6797   const llvm::Triple &T = Target->getTriple();
6798   // Windows is LLP64 rather than LP64
6799   if (T.isOSWindows() && T.isArch64Bit())
6800     return LongLongTy;
6801   return LongTy;
6802 }
6803 
6804 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6805   if (!ObjCInstanceTypeDecl)
6806     ObjCInstanceTypeDecl =
6807         buildImplicitTypedef(getObjCIdType(), "instancetype");
6808   return ObjCInstanceTypeDecl;
6809 }
6810 
6811 // This returns true if a type has been typedefed to BOOL:
6812 // typedef <type> BOOL;
6813 static bool isTypeTypedefedAsBOOL(QualType T) {
6814   if (const auto *TT = dyn_cast<TypedefType>(T))
6815     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6816       return II->isStr("BOOL");
6817 
6818   return false;
6819 }
6820 
6821 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6822 /// purpose.
6823 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6824   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6825     return CharUnits::Zero();
6826 
6827   CharUnits sz = getTypeSizeInChars(type);
6828 
6829   // Make all integer and enum types at least as large as an int
6830   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6831     sz = std::max(sz, getTypeSizeInChars(IntTy));
6832   // Treat arrays as pointers, since that's how they're passed in.
6833   else if (type->isArrayType())
6834     sz = getTypeSizeInChars(VoidPtrTy);
6835   return sz;
6836 }
6837 
6838 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6839   return getTargetInfo().getCXXABI().isMicrosoft() &&
6840          VD->isStaticDataMember() &&
6841          VD->getType()->isIntegralOrEnumerationType() &&
6842          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6843 }
6844 
6845 ASTContext::InlineVariableDefinitionKind
6846 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6847   if (!VD->isInline())
6848     return InlineVariableDefinitionKind::None;
6849 
6850   // In almost all cases, it's a weak definition.
6851   auto *First = VD->getFirstDecl();
6852   if (First->isInlineSpecified() || !First->isStaticDataMember())
6853     return InlineVariableDefinitionKind::Weak;
6854 
6855   // If there's a file-context declaration in this translation unit, it's a
6856   // non-discardable definition.
6857   for (auto *D : VD->redecls())
6858     if (D->getLexicalDeclContext()->isFileContext() &&
6859         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6860       return InlineVariableDefinitionKind::Strong;
6861 
6862   // If we've not seen one yet, we don't know.
6863   return InlineVariableDefinitionKind::WeakUnknown;
6864 }
6865 
6866 static std::string charUnitsToString(const CharUnits &CU) {
6867   return llvm::itostr(CU.getQuantity());
6868 }
6869 
6870 /// getObjCEncodingForBlock - Return the encoded type for this block
6871 /// declaration.
6872 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6873   std::string S;
6874 
6875   const BlockDecl *Decl = Expr->getBlockDecl();
6876   QualType BlockTy =
6877       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6878   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6879   // Encode result type.
6880   if (getLangOpts().EncodeExtendedBlockSig)
6881     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6882                                       true /*Extended*/);
6883   else
6884     getObjCEncodingForType(BlockReturnTy, S);
6885   // Compute size of all parameters.
6886   // Start with computing size of a pointer in number of bytes.
6887   // FIXME: There might(should) be a better way of doing this computation!
6888   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6889   CharUnits ParmOffset = PtrSize;
6890   for (auto PI : Decl->parameters()) {
6891     QualType PType = PI->getType();
6892     CharUnits sz = getObjCEncodingTypeSize(PType);
6893     if (sz.isZero())
6894       continue;
6895     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6896     ParmOffset += sz;
6897   }
6898   // Size of the argument frame
6899   S += charUnitsToString(ParmOffset);
6900   // Block pointer and offset.
6901   S += "@?0";
6902 
6903   // Argument types.
6904   ParmOffset = PtrSize;
6905   for (auto PVDecl : Decl->parameters()) {
6906     QualType PType = PVDecl->getOriginalType();
6907     if (const auto *AT =
6908             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6909       // Use array's original type only if it has known number of
6910       // elements.
6911       if (!isa<ConstantArrayType>(AT))
6912         PType = PVDecl->getType();
6913     } else if (PType->isFunctionType())
6914       PType = PVDecl->getType();
6915     if (getLangOpts().EncodeExtendedBlockSig)
6916       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6917                                       S, true /*Extended*/);
6918     else
6919       getObjCEncodingForType(PType, S);
6920     S += charUnitsToString(ParmOffset);
6921     ParmOffset += getObjCEncodingTypeSize(PType);
6922   }
6923 
6924   return S;
6925 }
6926 
6927 std::string
6928 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6929   std::string S;
6930   // Encode result type.
6931   getObjCEncodingForType(Decl->getReturnType(), S);
6932   CharUnits ParmOffset;
6933   // Compute size of all parameters.
6934   for (auto PI : Decl->parameters()) {
6935     QualType PType = PI->getType();
6936     CharUnits sz = getObjCEncodingTypeSize(PType);
6937     if (sz.isZero())
6938       continue;
6939 
6940     assert(sz.isPositive() &&
6941            "getObjCEncodingForFunctionDecl - Incomplete param type");
6942     ParmOffset += sz;
6943   }
6944   S += charUnitsToString(ParmOffset);
6945   ParmOffset = CharUnits::Zero();
6946 
6947   // Argument types.
6948   for (auto PVDecl : Decl->parameters()) {
6949     QualType PType = PVDecl->getOriginalType();
6950     if (const auto *AT =
6951             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6952       // Use array's original type only if it has known number of
6953       // elements.
6954       if (!isa<ConstantArrayType>(AT))
6955         PType = PVDecl->getType();
6956     } else if (PType->isFunctionType())
6957       PType = PVDecl->getType();
6958     getObjCEncodingForType(PType, S);
6959     S += charUnitsToString(ParmOffset);
6960     ParmOffset += getObjCEncodingTypeSize(PType);
6961   }
6962 
6963   return S;
6964 }
6965 
6966 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6967 /// method parameter or return type. If Extended, include class names and
6968 /// block object types.
6969 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6970                                                    QualType T, std::string& S,
6971                                                    bool Extended) const {
6972   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6973   getObjCEncodingForTypeQualifier(QT, S);
6974   // Encode parameter type.
6975   ObjCEncOptions Options = ObjCEncOptions()
6976                                .setExpandPointedToStructures()
6977                                .setExpandStructures()
6978                                .setIsOutermostType();
6979   if (Extended)
6980     Options.setEncodeBlockParameters().setEncodeClassNames();
6981   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6982 }
6983 
6984 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6985 /// declaration.
6986 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6987                                                      bool Extended) const {
6988   // FIXME: This is not very efficient.
6989   // Encode return type.
6990   std::string S;
6991   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6992                                     Decl->getReturnType(), S, Extended);
6993   // Compute size of all parameters.
6994   // Start with computing size of a pointer in number of bytes.
6995   // FIXME: There might(should) be a better way of doing this computation!
6996   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6997   // The first two arguments (self and _cmd) are pointers; account for
6998   // their size.
6999   CharUnits ParmOffset = 2 * PtrSize;
7000   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7001        E = Decl->sel_param_end(); PI != E; ++PI) {
7002     QualType PType = (*PI)->getType();
7003     CharUnits sz = getObjCEncodingTypeSize(PType);
7004     if (sz.isZero())
7005       continue;
7006 
7007     assert(sz.isPositive() &&
7008            "getObjCEncodingForMethodDecl - Incomplete param type");
7009     ParmOffset += sz;
7010   }
7011   S += charUnitsToString(ParmOffset);
7012   S += "@0:";
7013   S += charUnitsToString(PtrSize);
7014 
7015   // Argument types.
7016   ParmOffset = 2 * PtrSize;
7017   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7018        E = Decl->sel_param_end(); PI != E; ++PI) {
7019     const ParmVarDecl *PVDecl = *PI;
7020     QualType PType = PVDecl->getOriginalType();
7021     if (const auto *AT =
7022             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7023       // Use array's original type only if it has known number of
7024       // elements.
7025       if (!isa<ConstantArrayType>(AT))
7026         PType = PVDecl->getType();
7027     } else if (PType->isFunctionType())
7028       PType = PVDecl->getType();
7029     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7030                                       PType, S, Extended);
7031     S += charUnitsToString(ParmOffset);
7032     ParmOffset += getObjCEncodingTypeSize(PType);
7033   }
7034 
7035   return S;
7036 }
7037 
7038 ObjCPropertyImplDecl *
7039 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7040                                       const ObjCPropertyDecl *PD,
7041                                       const Decl *Container) const {
7042   if (!Container)
7043     return nullptr;
7044   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7045     for (auto *PID : CID->property_impls())
7046       if (PID->getPropertyDecl() == PD)
7047         return PID;
7048   } else {
7049     const auto *OID = cast<ObjCImplementationDecl>(Container);
7050     for (auto *PID : OID->property_impls())
7051       if (PID->getPropertyDecl() == PD)
7052         return PID;
7053   }
7054   return nullptr;
7055 }
7056 
7057 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7058 /// property declaration. If non-NULL, Container must be either an
7059 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7060 /// NULL when getting encodings for protocol properties.
7061 /// Property attributes are stored as a comma-delimited C string. The simple
7062 /// attributes readonly and bycopy are encoded as single characters. The
7063 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7064 /// encoded as single characters, followed by an identifier. Property types
7065 /// are also encoded as a parametrized attribute. The characters used to encode
7066 /// these attributes are defined by the following enumeration:
7067 /// @code
7068 /// enum PropertyAttributes {
7069 /// kPropertyReadOnly = 'R',   // property is read-only.
7070 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7071 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7072 /// kPropertyDynamic = 'D',    // property is dynamic
7073 /// kPropertyGetter = 'G',     // followed by getter selector name
7074 /// kPropertySetter = 'S',     // followed by setter selector name
7075 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7076 /// kPropertyType = 'T'              // followed by old-style type encoding.
7077 /// kPropertyWeak = 'W'              // 'weak' property
7078 /// kPropertyStrong = 'P'            // property GC'able
7079 /// kPropertyNonAtomic = 'N'         // property non-atomic
7080 /// };
7081 /// @endcode
7082 std::string
7083 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7084                                            const Decl *Container) const {
7085   // Collect information from the property implementation decl(s).
7086   bool Dynamic = false;
7087   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7088 
7089   if (ObjCPropertyImplDecl *PropertyImpDecl =
7090       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7091     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7092       Dynamic = true;
7093     else
7094       SynthesizePID = PropertyImpDecl;
7095   }
7096 
7097   // FIXME: This is not very efficient.
7098   std::string S = "T";
7099 
7100   // Encode result type.
7101   // GCC has some special rules regarding encoding of properties which
7102   // closely resembles encoding of ivars.
7103   getObjCEncodingForPropertyType(PD->getType(), S);
7104 
7105   if (PD->isReadOnly()) {
7106     S += ",R";
7107     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7108       S += ",C";
7109     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7110       S += ",&";
7111     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7112       S += ",W";
7113   } else {
7114     switch (PD->getSetterKind()) {
7115     case ObjCPropertyDecl::Assign: break;
7116     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7117     case ObjCPropertyDecl::Retain: S += ",&"; break;
7118     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7119     }
7120   }
7121 
7122   // It really isn't clear at all what this means, since properties
7123   // are "dynamic by default".
7124   if (Dynamic)
7125     S += ",D";
7126 
7127   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7128     S += ",N";
7129 
7130   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7131     S += ",G";
7132     S += PD->getGetterName().getAsString();
7133   }
7134 
7135   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7136     S += ",S";
7137     S += PD->getSetterName().getAsString();
7138   }
7139 
7140   if (SynthesizePID) {
7141     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7142     S += ",V";
7143     S += OID->getNameAsString();
7144   }
7145 
7146   // FIXME: OBJCGC: weak & strong
7147   return S;
7148 }
7149 
7150 /// getLegacyIntegralTypeEncoding -
7151 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7152 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7153 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7154 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7155   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7156     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7157       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7158         PointeeTy = UnsignedIntTy;
7159       else
7160         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7161           PointeeTy = IntTy;
7162     }
7163   }
7164 }
7165 
7166 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7167                                         const FieldDecl *Field,
7168                                         QualType *NotEncodedT) const {
7169   // We follow the behavior of gcc, expanding structures which are
7170   // directly pointed to, and expanding embedded structures. Note that
7171   // these rules are sufficient to prevent recursive encoding of the
7172   // same type.
7173   getObjCEncodingForTypeImpl(T, S,
7174                              ObjCEncOptions()
7175                                  .setExpandPointedToStructures()
7176                                  .setExpandStructures()
7177                                  .setIsOutermostType(),
7178                              Field, NotEncodedT);
7179 }
7180 
7181 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7182                                                 std::string& S) const {
7183   // Encode result type.
7184   // GCC has some special rules regarding encoding of properties which
7185   // closely resembles encoding of ivars.
7186   getObjCEncodingForTypeImpl(T, S,
7187                              ObjCEncOptions()
7188                                  .setExpandPointedToStructures()
7189                                  .setExpandStructures()
7190                                  .setIsOutermostType()
7191                                  .setEncodingProperty(),
7192                              /*Field=*/nullptr);
7193 }
7194 
7195 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7196                                             const BuiltinType *BT) {
7197     BuiltinType::Kind kind = BT->getKind();
7198     switch (kind) {
7199     case BuiltinType::Void:       return 'v';
7200     case BuiltinType::Bool:       return 'B';
7201     case BuiltinType::Char8:
7202     case BuiltinType::Char_U:
7203     case BuiltinType::UChar:      return 'C';
7204     case BuiltinType::Char16:
7205     case BuiltinType::UShort:     return 'S';
7206     case BuiltinType::Char32:
7207     case BuiltinType::UInt:       return 'I';
7208     case BuiltinType::ULong:
7209         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7210     case BuiltinType::UInt128:    return 'T';
7211     case BuiltinType::ULongLong:  return 'Q';
7212     case BuiltinType::Char_S:
7213     case BuiltinType::SChar:      return 'c';
7214     case BuiltinType::Short:      return 's';
7215     case BuiltinType::WChar_S:
7216     case BuiltinType::WChar_U:
7217     case BuiltinType::Int:        return 'i';
7218     case BuiltinType::Long:
7219       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7220     case BuiltinType::LongLong:   return 'q';
7221     case BuiltinType::Int128:     return 't';
7222     case BuiltinType::Float:      return 'f';
7223     case BuiltinType::Double:     return 'd';
7224     case BuiltinType::LongDouble: return 'D';
7225     case BuiltinType::NullPtr:    return '*'; // like char*
7226 
7227     case BuiltinType::BFloat16:
7228     case BuiltinType::Float16:
7229     case BuiltinType::Float128:
7230     case BuiltinType::Half:
7231     case BuiltinType::ShortAccum:
7232     case BuiltinType::Accum:
7233     case BuiltinType::LongAccum:
7234     case BuiltinType::UShortAccum:
7235     case BuiltinType::UAccum:
7236     case BuiltinType::ULongAccum:
7237     case BuiltinType::ShortFract:
7238     case BuiltinType::Fract:
7239     case BuiltinType::LongFract:
7240     case BuiltinType::UShortFract:
7241     case BuiltinType::UFract:
7242     case BuiltinType::ULongFract:
7243     case BuiltinType::SatShortAccum:
7244     case BuiltinType::SatAccum:
7245     case BuiltinType::SatLongAccum:
7246     case BuiltinType::SatUShortAccum:
7247     case BuiltinType::SatUAccum:
7248     case BuiltinType::SatULongAccum:
7249     case BuiltinType::SatShortFract:
7250     case BuiltinType::SatFract:
7251     case BuiltinType::SatLongFract:
7252     case BuiltinType::SatUShortFract:
7253     case BuiltinType::SatUFract:
7254     case BuiltinType::SatULongFract:
7255       // FIXME: potentially need @encodes for these!
7256       return ' ';
7257 
7258 #define SVE_TYPE(Name, Id, SingletonId) \
7259     case BuiltinType::Id:
7260 #include "clang/Basic/AArch64SVEACLETypes.def"
7261 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7262 #include "clang/Basic/RISCVVTypes.def"
7263       {
7264         DiagnosticsEngine &Diags = C->getDiagnostics();
7265         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7266                                                 "cannot yet @encode type %0");
7267         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7268         return ' ';
7269       }
7270 
7271     case BuiltinType::ObjCId:
7272     case BuiltinType::ObjCClass:
7273     case BuiltinType::ObjCSel:
7274       llvm_unreachable("@encoding ObjC primitive type");
7275 
7276     // OpenCL and placeholder types don't need @encodings.
7277 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7278     case BuiltinType::Id:
7279 #include "clang/Basic/OpenCLImageTypes.def"
7280 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7281     case BuiltinType::Id:
7282 #include "clang/Basic/OpenCLExtensionTypes.def"
7283     case BuiltinType::OCLEvent:
7284     case BuiltinType::OCLClkEvent:
7285     case BuiltinType::OCLQueue:
7286     case BuiltinType::OCLReserveID:
7287     case BuiltinType::OCLSampler:
7288     case BuiltinType::Dependent:
7289 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7290     case BuiltinType::Id:
7291 #include "clang/Basic/PPCTypes.def"
7292 #define BUILTIN_TYPE(KIND, ID)
7293 #define PLACEHOLDER_TYPE(KIND, ID) \
7294     case BuiltinType::KIND:
7295 #include "clang/AST/BuiltinTypes.def"
7296       llvm_unreachable("invalid builtin type for @encode");
7297     }
7298     llvm_unreachable("invalid BuiltinType::Kind value");
7299 }
7300 
7301 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7302   EnumDecl *Enum = ET->getDecl();
7303 
7304   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7305   if (!Enum->isFixed())
7306     return 'i';
7307 
7308   // The encoding of a fixed enum type matches its fixed underlying type.
7309   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7310   return getObjCEncodingForPrimitiveType(C, BT);
7311 }
7312 
7313 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7314                            QualType T, const FieldDecl *FD) {
7315   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7316   S += 'b';
7317   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7318   // The GNU runtime requires more information; bitfields are encoded as b,
7319   // then the offset (in bits) of the first element, then the type of the
7320   // bitfield, then the size in bits.  For example, in this structure:
7321   //
7322   // struct
7323   // {
7324   //    int integer;
7325   //    int flags:2;
7326   // };
7327   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7328   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7329   // information is not especially sensible, but we're stuck with it for
7330   // compatibility with GCC, although providing it breaks anything that
7331   // actually uses runtime introspection and wants to work on both runtimes...
7332   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7333     uint64_t Offset;
7334 
7335     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7336       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7337                                          IVD);
7338     } else {
7339       const RecordDecl *RD = FD->getParent();
7340       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7341       Offset = RL.getFieldOffset(FD->getFieldIndex());
7342     }
7343 
7344     S += llvm::utostr(Offset);
7345 
7346     if (const auto *ET = T->getAs<EnumType>())
7347       S += ObjCEncodingForEnumType(Ctx, ET);
7348     else {
7349       const auto *BT = T->castAs<BuiltinType>();
7350       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7351     }
7352   }
7353   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7354 }
7355 
7356 // Helper function for determining whether the encoded type string would include
7357 // a template specialization type.
7358 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7359                                                      bool VisitBasesAndFields) {
7360   T = T->getBaseElementTypeUnsafe();
7361 
7362   if (auto *PT = T->getAs<PointerType>())
7363     return hasTemplateSpecializationInEncodedString(
7364         PT->getPointeeType().getTypePtr(), false);
7365 
7366   auto *CXXRD = T->getAsCXXRecordDecl();
7367 
7368   if (!CXXRD)
7369     return false;
7370 
7371   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7372     return true;
7373 
7374   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7375     return false;
7376 
7377   for (auto B : CXXRD->bases())
7378     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7379                                                  true))
7380       return true;
7381 
7382   for (auto *FD : CXXRD->fields())
7383     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7384                                                  true))
7385       return true;
7386 
7387   return false;
7388 }
7389 
7390 // FIXME: Use SmallString for accumulating string.
7391 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7392                                             const ObjCEncOptions Options,
7393                                             const FieldDecl *FD,
7394                                             QualType *NotEncodedT) const {
7395   CanQualType CT = getCanonicalType(T);
7396   switch (CT->getTypeClass()) {
7397   case Type::Builtin:
7398   case Type::Enum:
7399     if (FD && FD->isBitField())
7400       return EncodeBitField(this, S, T, FD);
7401     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7402       S += getObjCEncodingForPrimitiveType(this, BT);
7403     else
7404       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7405     return;
7406 
7407   case Type::Complex:
7408     S += 'j';
7409     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7410                                ObjCEncOptions(),
7411                                /*Field=*/nullptr);
7412     return;
7413 
7414   case Type::Atomic:
7415     S += 'A';
7416     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7417                                ObjCEncOptions(),
7418                                /*Field=*/nullptr);
7419     return;
7420 
7421   // encoding for pointer or reference types.
7422   case Type::Pointer:
7423   case Type::LValueReference:
7424   case Type::RValueReference: {
7425     QualType PointeeTy;
7426     if (isa<PointerType>(CT)) {
7427       const auto *PT = T->castAs<PointerType>();
7428       if (PT->isObjCSelType()) {
7429         S += ':';
7430         return;
7431       }
7432       PointeeTy = PT->getPointeeType();
7433     } else {
7434       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7435     }
7436 
7437     bool isReadOnly = false;
7438     // For historical/compatibility reasons, the read-only qualifier of the
7439     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7440     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7441     // Also, do not emit the 'r' for anything but the outermost type!
7442     if (isa<TypedefType>(T.getTypePtr())) {
7443       if (Options.IsOutermostType() && T.isConstQualified()) {
7444         isReadOnly = true;
7445         S += 'r';
7446       }
7447     } else if (Options.IsOutermostType()) {
7448       QualType P = PointeeTy;
7449       while (auto PT = P->getAs<PointerType>())
7450         P = PT->getPointeeType();
7451       if (P.isConstQualified()) {
7452         isReadOnly = true;
7453         S += 'r';
7454       }
7455     }
7456     if (isReadOnly) {
7457       // Another legacy compatibility encoding. Some ObjC qualifier and type
7458       // combinations need to be rearranged.
7459       // Rewrite "in const" from "nr" to "rn"
7460       if (StringRef(S).endswith("nr"))
7461         S.replace(S.end()-2, S.end(), "rn");
7462     }
7463 
7464     if (PointeeTy->isCharType()) {
7465       // char pointer types should be encoded as '*' unless it is a
7466       // type that has been typedef'd to 'BOOL'.
7467       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7468         S += '*';
7469         return;
7470       }
7471     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7472       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7473       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7474         S += '#';
7475         return;
7476       }
7477       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7478       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7479         S += '@';
7480         return;
7481       }
7482       // If the encoded string for the class includes template names, just emit
7483       // "^v" for pointers to the class.
7484       if (getLangOpts().CPlusPlus &&
7485           (!getLangOpts().EncodeCXXClassTemplateSpec &&
7486            hasTemplateSpecializationInEncodedString(
7487                RTy, Options.ExpandPointedToStructures()))) {
7488         S += "^v";
7489         return;
7490       }
7491       // fall through...
7492     }
7493     S += '^';
7494     getLegacyIntegralTypeEncoding(PointeeTy);
7495 
7496     ObjCEncOptions NewOptions;
7497     if (Options.ExpandPointedToStructures())
7498       NewOptions.setExpandStructures();
7499     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7500                                /*Field=*/nullptr, NotEncodedT);
7501     return;
7502   }
7503 
7504   case Type::ConstantArray:
7505   case Type::IncompleteArray:
7506   case Type::VariableArray: {
7507     const auto *AT = cast<ArrayType>(CT);
7508 
7509     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7510       // Incomplete arrays are encoded as a pointer to the array element.
7511       S += '^';
7512 
7513       getObjCEncodingForTypeImpl(
7514           AT->getElementType(), S,
7515           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7516     } else {
7517       S += '[';
7518 
7519       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7520         S += llvm::utostr(CAT->getSize().getZExtValue());
7521       else {
7522         //Variable length arrays are encoded as a regular array with 0 elements.
7523         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7524                "Unknown array type!");
7525         S += '0';
7526       }
7527 
7528       getObjCEncodingForTypeImpl(
7529           AT->getElementType(), S,
7530           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7531           NotEncodedT);
7532       S += ']';
7533     }
7534     return;
7535   }
7536 
7537   case Type::FunctionNoProto:
7538   case Type::FunctionProto:
7539     S += '?';
7540     return;
7541 
7542   case Type::Record: {
7543     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7544     S += RDecl->isUnion() ? '(' : '{';
7545     // Anonymous structures print as '?'
7546     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7547       S += II->getName();
7548       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7549         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7550         llvm::raw_string_ostream OS(S);
7551         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7552                                   getPrintingPolicy());
7553       }
7554     } else {
7555       S += '?';
7556     }
7557     if (Options.ExpandStructures()) {
7558       S += '=';
7559       if (!RDecl->isUnion()) {
7560         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7561       } else {
7562         for (const auto *Field : RDecl->fields()) {
7563           if (FD) {
7564             S += '"';
7565             S += Field->getNameAsString();
7566             S += '"';
7567           }
7568 
7569           // Special case bit-fields.
7570           if (Field->isBitField()) {
7571             getObjCEncodingForTypeImpl(Field->getType(), S,
7572                                        ObjCEncOptions().setExpandStructures(),
7573                                        Field);
7574           } else {
7575             QualType qt = Field->getType();
7576             getLegacyIntegralTypeEncoding(qt);
7577             getObjCEncodingForTypeImpl(
7578                 qt, S,
7579                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7580                 NotEncodedT);
7581           }
7582         }
7583       }
7584     }
7585     S += RDecl->isUnion() ? ')' : '}';
7586     return;
7587   }
7588 
7589   case Type::BlockPointer: {
7590     const auto *BT = T->castAs<BlockPointerType>();
7591     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7592     if (Options.EncodeBlockParameters()) {
7593       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7594 
7595       S += '<';
7596       // Block return type
7597       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7598                                  Options.forComponentType(), FD, NotEncodedT);
7599       // Block self
7600       S += "@?";
7601       // Block parameters
7602       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7603         for (const auto &I : FPT->param_types())
7604           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7605                                      NotEncodedT);
7606       }
7607       S += '>';
7608     }
7609     return;
7610   }
7611 
7612   case Type::ObjCObject: {
7613     // hack to match legacy encoding of *id and *Class
7614     QualType Ty = getObjCObjectPointerType(CT);
7615     if (Ty->isObjCIdType()) {
7616       S += "{objc_object=}";
7617       return;
7618     }
7619     else if (Ty->isObjCClassType()) {
7620       S += "{objc_class=}";
7621       return;
7622     }
7623     // TODO: Double check to make sure this intentionally falls through.
7624     LLVM_FALLTHROUGH;
7625   }
7626 
7627   case Type::ObjCInterface: {
7628     // Ignore protocol qualifiers when mangling at this level.
7629     // @encode(class_name)
7630     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7631     S += '{';
7632     S += OI->getObjCRuntimeNameAsString();
7633     if (Options.ExpandStructures()) {
7634       S += '=';
7635       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7636       DeepCollectObjCIvars(OI, true, Ivars);
7637       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7638         const FieldDecl *Field = Ivars[i];
7639         if (Field->isBitField())
7640           getObjCEncodingForTypeImpl(Field->getType(), S,
7641                                      ObjCEncOptions().setExpandStructures(),
7642                                      Field);
7643         else
7644           getObjCEncodingForTypeImpl(Field->getType(), S,
7645                                      ObjCEncOptions().setExpandStructures(), FD,
7646                                      NotEncodedT);
7647       }
7648     }
7649     S += '}';
7650     return;
7651   }
7652 
7653   case Type::ObjCObjectPointer: {
7654     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7655     if (OPT->isObjCIdType()) {
7656       S += '@';
7657       return;
7658     }
7659 
7660     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7661       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7662       // Since this is a binary compatibility issue, need to consult with
7663       // runtime folks. Fortunately, this is a *very* obscure construct.
7664       S += '#';
7665       return;
7666     }
7667 
7668     if (OPT->isObjCQualifiedIdType()) {
7669       getObjCEncodingForTypeImpl(
7670           getObjCIdType(), S,
7671           Options.keepingOnly(ObjCEncOptions()
7672                                   .setExpandPointedToStructures()
7673                                   .setExpandStructures()),
7674           FD);
7675       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7676         // Note that we do extended encoding of protocol qualifer list
7677         // Only when doing ivar or property encoding.
7678         S += '"';
7679         for (const auto *I : OPT->quals()) {
7680           S += '<';
7681           S += I->getObjCRuntimeNameAsString();
7682           S += '>';
7683         }
7684         S += '"';
7685       }
7686       return;
7687     }
7688 
7689     S += '@';
7690     if (OPT->getInterfaceDecl() &&
7691         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7692       S += '"';
7693       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7694       for (const auto *I : OPT->quals()) {
7695         S += '<';
7696         S += I->getObjCRuntimeNameAsString();
7697         S += '>';
7698       }
7699       S += '"';
7700     }
7701     return;
7702   }
7703 
7704   // gcc just blithely ignores member pointers.
7705   // FIXME: we should do better than that.  'M' is available.
7706   case Type::MemberPointer:
7707   // This matches gcc's encoding, even though technically it is insufficient.
7708   //FIXME. We should do a better job than gcc.
7709   case Type::Vector:
7710   case Type::ExtVector:
7711   // Until we have a coherent encoding of these three types, issue warning.
7712     if (NotEncodedT)
7713       *NotEncodedT = T;
7714     return;
7715 
7716   case Type::ConstantMatrix:
7717     if (NotEncodedT)
7718       *NotEncodedT = T;
7719     return;
7720 
7721   // We could see an undeduced auto type here during error recovery.
7722   // Just ignore it.
7723   case Type::Auto:
7724   case Type::DeducedTemplateSpecialization:
7725     return;
7726 
7727   case Type::Pipe:
7728   case Type::ExtInt:
7729 #define ABSTRACT_TYPE(KIND, BASE)
7730 #define TYPE(KIND, BASE)
7731 #define DEPENDENT_TYPE(KIND, BASE) \
7732   case Type::KIND:
7733 #define NON_CANONICAL_TYPE(KIND, BASE) \
7734   case Type::KIND:
7735 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7736   case Type::KIND:
7737 #include "clang/AST/TypeNodes.inc"
7738     llvm_unreachable("@encode for dependent type!");
7739   }
7740   llvm_unreachable("bad type kind!");
7741 }
7742 
7743 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7744                                                  std::string &S,
7745                                                  const FieldDecl *FD,
7746                                                  bool includeVBases,
7747                                                  QualType *NotEncodedT) const {
7748   assert(RDecl && "Expected non-null RecordDecl");
7749   assert(!RDecl->isUnion() && "Should not be called for unions");
7750   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7751     return;
7752 
7753   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7754   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7755   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7756 
7757   if (CXXRec) {
7758     for (const auto &BI : CXXRec->bases()) {
7759       if (!BI.isVirtual()) {
7760         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7761         if (base->isEmpty())
7762           continue;
7763         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7764         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7765                                   std::make_pair(offs, base));
7766       }
7767     }
7768   }
7769 
7770   unsigned i = 0;
7771   for (FieldDecl *Field : RDecl->fields()) {
7772     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
7773       continue;
7774     uint64_t offs = layout.getFieldOffset(i);
7775     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7776                               std::make_pair(offs, Field));
7777     ++i;
7778   }
7779 
7780   if (CXXRec && includeVBases) {
7781     for (const auto &BI : CXXRec->vbases()) {
7782       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7783       if (base->isEmpty())
7784         continue;
7785       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7786       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7787           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7788         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7789                                   std::make_pair(offs, base));
7790     }
7791   }
7792 
7793   CharUnits size;
7794   if (CXXRec) {
7795     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7796   } else {
7797     size = layout.getSize();
7798   }
7799 
7800 #ifndef NDEBUG
7801   uint64_t CurOffs = 0;
7802 #endif
7803   std::multimap<uint64_t, NamedDecl *>::iterator
7804     CurLayObj = FieldOrBaseOffsets.begin();
7805 
7806   if (CXXRec && CXXRec->isDynamicClass() &&
7807       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7808     if (FD) {
7809       S += "\"_vptr$";
7810       std::string recname = CXXRec->getNameAsString();
7811       if (recname.empty()) recname = "?";
7812       S += recname;
7813       S += '"';
7814     }
7815     S += "^^?";
7816 #ifndef NDEBUG
7817     CurOffs += getTypeSize(VoidPtrTy);
7818 #endif
7819   }
7820 
7821   if (!RDecl->hasFlexibleArrayMember()) {
7822     // Mark the end of the structure.
7823     uint64_t offs = toBits(size);
7824     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7825                               std::make_pair(offs, nullptr));
7826   }
7827 
7828   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7829 #ifndef NDEBUG
7830     assert(CurOffs <= CurLayObj->first);
7831     if (CurOffs < CurLayObj->first) {
7832       uint64_t padding = CurLayObj->first - CurOffs;
7833       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7834       // packing/alignment of members is different that normal, in which case
7835       // the encoding will be out-of-sync with the real layout.
7836       // If the runtime switches to just consider the size of types without
7837       // taking into account alignment, we could make padding explicit in the
7838       // encoding (e.g. using arrays of chars). The encoding strings would be
7839       // longer then though.
7840       CurOffs += padding;
7841     }
7842 #endif
7843 
7844     NamedDecl *dcl = CurLayObj->second;
7845     if (!dcl)
7846       break; // reached end of structure.
7847 
7848     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7849       // We expand the bases without their virtual bases since those are going
7850       // in the initial structure. Note that this differs from gcc which
7851       // expands virtual bases each time one is encountered in the hierarchy,
7852       // making the encoding type bigger than it really is.
7853       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7854                                       NotEncodedT);
7855       assert(!base->isEmpty());
7856 #ifndef NDEBUG
7857       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7858 #endif
7859     } else {
7860       const auto *field = cast<FieldDecl>(dcl);
7861       if (FD) {
7862         S += '"';
7863         S += field->getNameAsString();
7864         S += '"';
7865       }
7866 
7867       if (field->isBitField()) {
7868         EncodeBitField(this, S, field->getType(), field);
7869 #ifndef NDEBUG
7870         CurOffs += field->getBitWidthValue(*this);
7871 #endif
7872       } else {
7873         QualType qt = field->getType();
7874         getLegacyIntegralTypeEncoding(qt);
7875         getObjCEncodingForTypeImpl(
7876             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7877             FD, NotEncodedT);
7878 #ifndef NDEBUG
7879         CurOffs += getTypeSize(field->getType());
7880 #endif
7881       }
7882     }
7883   }
7884 }
7885 
7886 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7887                                                  std::string& S) const {
7888   if (QT & Decl::OBJC_TQ_In)
7889     S += 'n';
7890   if (QT & Decl::OBJC_TQ_Inout)
7891     S += 'N';
7892   if (QT & Decl::OBJC_TQ_Out)
7893     S += 'o';
7894   if (QT & Decl::OBJC_TQ_Bycopy)
7895     S += 'O';
7896   if (QT & Decl::OBJC_TQ_Byref)
7897     S += 'R';
7898   if (QT & Decl::OBJC_TQ_Oneway)
7899     S += 'V';
7900 }
7901 
7902 TypedefDecl *ASTContext::getObjCIdDecl() const {
7903   if (!ObjCIdDecl) {
7904     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7905     T = getObjCObjectPointerType(T);
7906     ObjCIdDecl = buildImplicitTypedef(T, "id");
7907   }
7908   return ObjCIdDecl;
7909 }
7910 
7911 TypedefDecl *ASTContext::getObjCSelDecl() const {
7912   if (!ObjCSelDecl) {
7913     QualType T = getPointerType(ObjCBuiltinSelTy);
7914     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7915   }
7916   return ObjCSelDecl;
7917 }
7918 
7919 TypedefDecl *ASTContext::getObjCClassDecl() const {
7920   if (!ObjCClassDecl) {
7921     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7922     T = getObjCObjectPointerType(T);
7923     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7924   }
7925   return ObjCClassDecl;
7926 }
7927 
7928 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7929   if (!ObjCProtocolClassDecl) {
7930     ObjCProtocolClassDecl
7931       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7932                                   SourceLocation(),
7933                                   &Idents.get("Protocol"),
7934                                   /*typeParamList=*/nullptr,
7935                                   /*PrevDecl=*/nullptr,
7936                                   SourceLocation(), true);
7937   }
7938 
7939   return ObjCProtocolClassDecl;
7940 }
7941 
7942 //===----------------------------------------------------------------------===//
7943 // __builtin_va_list Construction Functions
7944 //===----------------------------------------------------------------------===//
7945 
7946 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7947                                                  StringRef Name) {
7948   // typedef char* __builtin[_ms]_va_list;
7949   QualType T = Context->getPointerType(Context->CharTy);
7950   return Context->buildImplicitTypedef(T, Name);
7951 }
7952 
7953 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7954   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7955 }
7956 
7957 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7958   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7959 }
7960 
7961 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7962   // typedef void* __builtin_va_list;
7963   QualType T = Context->getPointerType(Context->VoidTy);
7964   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7965 }
7966 
7967 static TypedefDecl *
7968 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7969   // struct __va_list
7970   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7971   if (Context->getLangOpts().CPlusPlus) {
7972     // namespace std { struct __va_list {
7973     NamespaceDecl *NS;
7974     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7975                                Context->getTranslationUnitDecl(),
7976                                /*Inline*/ false, SourceLocation(),
7977                                SourceLocation(), &Context->Idents.get("std"),
7978                                /*PrevDecl*/ nullptr);
7979     NS->setImplicit();
7980     VaListTagDecl->setDeclContext(NS);
7981   }
7982 
7983   VaListTagDecl->startDefinition();
7984 
7985   const size_t NumFields = 5;
7986   QualType FieldTypes[NumFields];
7987   const char *FieldNames[NumFields];
7988 
7989   // void *__stack;
7990   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7991   FieldNames[0] = "__stack";
7992 
7993   // void *__gr_top;
7994   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7995   FieldNames[1] = "__gr_top";
7996 
7997   // void *__vr_top;
7998   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7999   FieldNames[2] = "__vr_top";
8000 
8001   // int __gr_offs;
8002   FieldTypes[3] = Context->IntTy;
8003   FieldNames[3] = "__gr_offs";
8004 
8005   // int __vr_offs;
8006   FieldTypes[4] = Context->IntTy;
8007   FieldNames[4] = "__vr_offs";
8008 
8009   // Create fields
8010   for (unsigned i = 0; i < NumFields; ++i) {
8011     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8012                                          VaListTagDecl,
8013                                          SourceLocation(),
8014                                          SourceLocation(),
8015                                          &Context->Idents.get(FieldNames[i]),
8016                                          FieldTypes[i], /*TInfo=*/nullptr,
8017                                          /*BitWidth=*/nullptr,
8018                                          /*Mutable=*/false,
8019                                          ICIS_NoInit);
8020     Field->setAccess(AS_public);
8021     VaListTagDecl->addDecl(Field);
8022   }
8023   VaListTagDecl->completeDefinition();
8024   Context->VaListTagDecl = VaListTagDecl;
8025   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8026 
8027   // } __builtin_va_list;
8028   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8029 }
8030 
8031 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8032   // typedef struct __va_list_tag {
8033   RecordDecl *VaListTagDecl;
8034 
8035   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8036   VaListTagDecl->startDefinition();
8037 
8038   const size_t NumFields = 5;
8039   QualType FieldTypes[NumFields];
8040   const char *FieldNames[NumFields];
8041 
8042   //   unsigned char gpr;
8043   FieldTypes[0] = Context->UnsignedCharTy;
8044   FieldNames[0] = "gpr";
8045 
8046   //   unsigned char fpr;
8047   FieldTypes[1] = Context->UnsignedCharTy;
8048   FieldNames[1] = "fpr";
8049 
8050   //   unsigned short reserved;
8051   FieldTypes[2] = Context->UnsignedShortTy;
8052   FieldNames[2] = "reserved";
8053 
8054   //   void* overflow_arg_area;
8055   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8056   FieldNames[3] = "overflow_arg_area";
8057 
8058   //   void* reg_save_area;
8059   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8060   FieldNames[4] = "reg_save_area";
8061 
8062   // Create fields
8063   for (unsigned i = 0; i < NumFields; ++i) {
8064     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8065                                          SourceLocation(),
8066                                          SourceLocation(),
8067                                          &Context->Idents.get(FieldNames[i]),
8068                                          FieldTypes[i], /*TInfo=*/nullptr,
8069                                          /*BitWidth=*/nullptr,
8070                                          /*Mutable=*/false,
8071                                          ICIS_NoInit);
8072     Field->setAccess(AS_public);
8073     VaListTagDecl->addDecl(Field);
8074   }
8075   VaListTagDecl->completeDefinition();
8076   Context->VaListTagDecl = VaListTagDecl;
8077   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8078 
8079   // } __va_list_tag;
8080   TypedefDecl *VaListTagTypedefDecl =
8081       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8082 
8083   QualType VaListTagTypedefType =
8084     Context->getTypedefType(VaListTagTypedefDecl);
8085 
8086   // typedef __va_list_tag __builtin_va_list[1];
8087   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8088   QualType VaListTagArrayType
8089     = Context->getConstantArrayType(VaListTagTypedefType,
8090                                     Size, nullptr, ArrayType::Normal, 0);
8091   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8092 }
8093 
8094 static TypedefDecl *
8095 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8096   // struct __va_list_tag {
8097   RecordDecl *VaListTagDecl;
8098   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8099   VaListTagDecl->startDefinition();
8100 
8101   const size_t NumFields = 4;
8102   QualType FieldTypes[NumFields];
8103   const char *FieldNames[NumFields];
8104 
8105   //   unsigned gp_offset;
8106   FieldTypes[0] = Context->UnsignedIntTy;
8107   FieldNames[0] = "gp_offset";
8108 
8109   //   unsigned fp_offset;
8110   FieldTypes[1] = Context->UnsignedIntTy;
8111   FieldNames[1] = "fp_offset";
8112 
8113   //   void* overflow_arg_area;
8114   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8115   FieldNames[2] = "overflow_arg_area";
8116 
8117   //   void* reg_save_area;
8118   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8119   FieldNames[3] = "reg_save_area";
8120 
8121   // Create fields
8122   for (unsigned i = 0; i < NumFields; ++i) {
8123     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8124                                          VaListTagDecl,
8125                                          SourceLocation(),
8126                                          SourceLocation(),
8127                                          &Context->Idents.get(FieldNames[i]),
8128                                          FieldTypes[i], /*TInfo=*/nullptr,
8129                                          /*BitWidth=*/nullptr,
8130                                          /*Mutable=*/false,
8131                                          ICIS_NoInit);
8132     Field->setAccess(AS_public);
8133     VaListTagDecl->addDecl(Field);
8134   }
8135   VaListTagDecl->completeDefinition();
8136   Context->VaListTagDecl = VaListTagDecl;
8137   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8138 
8139   // };
8140 
8141   // typedef struct __va_list_tag __builtin_va_list[1];
8142   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8143   QualType VaListTagArrayType = Context->getConstantArrayType(
8144       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8145   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8146 }
8147 
8148 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8149   // typedef int __builtin_va_list[4];
8150   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8151   QualType IntArrayType = Context->getConstantArrayType(
8152       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8153   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8154 }
8155 
8156 static TypedefDecl *
8157 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8158   // struct __va_list
8159   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8160   if (Context->getLangOpts().CPlusPlus) {
8161     // namespace std { struct __va_list {
8162     NamespaceDecl *NS;
8163     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8164                                Context->getTranslationUnitDecl(),
8165                                /*Inline*/false, SourceLocation(),
8166                                SourceLocation(), &Context->Idents.get("std"),
8167                                /*PrevDecl*/ nullptr);
8168     NS->setImplicit();
8169     VaListDecl->setDeclContext(NS);
8170   }
8171 
8172   VaListDecl->startDefinition();
8173 
8174   // void * __ap;
8175   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8176                                        VaListDecl,
8177                                        SourceLocation(),
8178                                        SourceLocation(),
8179                                        &Context->Idents.get("__ap"),
8180                                        Context->getPointerType(Context->VoidTy),
8181                                        /*TInfo=*/nullptr,
8182                                        /*BitWidth=*/nullptr,
8183                                        /*Mutable=*/false,
8184                                        ICIS_NoInit);
8185   Field->setAccess(AS_public);
8186   VaListDecl->addDecl(Field);
8187 
8188   // };
8189   VaListDecl->completeDefinition();
8190   Context->VaListTagDecl = VaListDecl;
8191 
8192   // typedef struct __va_list __builtin_va_list;
8193   QualType T = Context->getRecordType(VaListDecl);
8194   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8195 }
8196 
8197 static TypedefDecl *
8198 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8199   // struct __va_list_tag {
8200   RecordDecl *VaListTagDecl;
8201   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8202   VaListTagDecl->startDefinition();
8203 
8204   const size_t NumFields = 4;
8205   QualType FieldTypes[NumFields];
8206   const char *FieldNames[NumFields];
8207 
8208   //   long __gpr;
8209   FieldTypes[0] = Context->LongTy;
8210   FieldNames[0] = "__gpr";
8211 
8212   //   long __fpr;
8213   FieldTypes[1] = Context->LongTy;
8214   FieldNames[1] = "__fpr";
8215 
8216   //   void *__overflow_arg_area;
8217   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8218   FieldNames[2] = "__overflow_arg_area";
8219 
8220   //   void *__reg_save_area;
8221   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8222   FieldNames[3] = "__reg_save_area";
8223 
8224   // Create fields
8225   for (unsigned i = 0; i < NumFields; ++i) {
8226     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8227                                          VaListTagDecl,
8228                                          SourceLocation(),
8229                                          SourceLocation(),
8230                                          &Context->Idents.get(FieldNames[i]),
8231                                          FieldTypes[i], /*TInfo=*/nullptr,
8232                                          /*BitWidth=*/nullptr,
8233                                          /*Mutable=*/false,
8234                                          ICIS_NoInit);
8235     Field->setAccess(AS_public);
8236     VaListTagDecl->addDecl(Field);
8237   }
8238   VaListTagDecl->completeDefinition();
8239   Context->VaListTagDecl = VaListTagDecl;
8240   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8241 
8242   // };
8243 
8244   // typedef __va_list_tag __builtin_va_list[1];
8245   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8246   QualType VaListTagArrayType = Context->getConstantArrayType(
8247       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8248 
8249   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8250 }
8251 
8252 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8253   // typedef struct __va_list_tag {
8254   RecordDecl *VaListTagDecl;
8255   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8256   VaListTagDecl->startDefinition();
8257 
8258   const size_t NumFields = 3;
8259   QualType FieldTypes[NumFields];
8260   const char *FieldNames[NumFields];
8261 
8262   //   void *CurrentSavedRegisterArea;
8263   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8264   FieldNames[0] = "__current_saved_reg_area_pointer";
8265 
8266   //   void *SavedRegAreaEnd;
8267   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8268   FieldNames[1] = "__saved_reg_area_end_pointer";
8269 
8270   //   void *OverflowArea;
8271   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8272   FieldNames[2] = "__overflow_area_pointer";
8273 
8274   // Create fields
8275   for (unsigned i = 0; i < NumFields; ++i) {
8276     FieldDecl *Field = FieldDecl::Create(
8277         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8278         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8279         /*TInfo=*/0,
8280         /*BitWidth=*/0,
8281         /*Mutable=*/false, ICIS_NoInit);
8282     Field->setAccess(AS_public);
8283     VaListTagDecl->addDecl(Field);
8284   }
8285   VaListTagDecl->completeDefinition();
8286   Context->VaListTagDecl = VaListTagDecl;
8287   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8288 
8289   // } __va_list_tag;
8290   TypedefDecl *VaListTagTypedefDecl =
8291       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8292 
8293   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8294 
8295   // typedef __va_list_tag __builtin_va_list[1];
8296   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8297   QualType VaListTagArrayType = Context->getConstantArrayType(
8298       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8299 
8300   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8301 }
8302 
8303 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8304                                      TargetInfo::BuiltinVaListKind Kind) {
8305   switch (Kind) {
8306   case TargetInfo::CharPtrBuiltinVaList:
8307     return CreateCharPtrBuiltinVaListDecl(Context);
8308   case TargetInfo::VoidPtrBuiltinVaList:
8309     return CreateVoidPtrBuiltinVaListDecl(Context);
8310   case TargetInfo::AArch64ABIBuiltinVaList:
8311     return CreateAArch64ABIBuiltinVaListDecl(Context);
8312   case TargetInfo::PowerABIBuiltinVaList:
8313     return CreatePowerABIBuiltinVaListDecl(Context);
8314   case TargetInfo::X86_64ABIBuiltinVaList:
8315     return CreateX86_64ABIBuiltinVaListDecl(Context);
8316   case TargetInfo::PNaClABIBuiltinVaList:
8317     return CreatePNaClABIBuiltinVaListDecl(Context);
8318   case TargetInfo::AAPCSABIBuiltinVaList:
8319     return CreateAAPCSABIBuiltinVaListDecl(Context);
8320   case TargetInfo::SystemZBuiltinVaList:
8321     return CreateSystemZBuiltinVaListDecl(Context);
8322   case TargetInfo::HexagonBuiltinVaList:
8323     return CreateHexagonBuiltinVaListDecl(Context);
8324   }
8325 
8326   llvm_unreachable("Unhandled __builtin_va_list type kind");
8327 }
8328 
8329 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8330   if (!BuiltinVaListDecl) {
8331     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8332     assert(BuiltinVaListDecl->isImplicit());
8333   }
8334 
8335   return BuiltinVaListDecl;
8336 }
8337 
8338 Decl *ASTContext::getVaListTagDecl() const {
8339   // Force the creation of VaListTagDecl by building the __builtin_va_list
8340   // declaration.
8341   if (!VaListTagDecl)
8342     (void)getBuiltinVaListDecl();
8343 
8344   return VaListTagDecl;
8345 }
8346 
8347 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8348   if (!BuiltinMSVaListDecl)
8349     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8350 
8351   return BuiltinMSVaListDecl;
8352 }
8353 
8354 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8355   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8356 }
8357 
8358 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8359   assert(ObjCConstantStringType.isNull() &&
8360          "'NSConstantString' type already set!");
8361 
8362   ObjCConstantStringType = getObjCInterfaceType(Decl);
8363 }
8364 
8365 /// Retrieve the template name that corresponds to a non-empty
8366 /// lookup.
8367 TemplateName
8368 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8369                                       UnresolvedSetIterator End) const {
8370   unsigned size = End - Begin;
8371   assert(size > 1 && "set is not overloaded!");
8372 
8373   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8374                           size * sizeof(FunctionTemplateDecl*));
8375   auto *OT = new (memory) OverloadedTemplateStorage(size);
8376 
8377   NamedDecl **Storage = OT->getStorage();
8378   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8379     NamedDecl *D = *I;
8380     assert(isa<FunctionTemplateDecl>(D) ||
8381            isa<UnresolvedUsingValueDecl>(D) ||
8382            (isa<UsingShadowDecl>(D) &&
8383             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8384     *Storage++ = D;
8385   }
8386 
8387   return TemplateName(OT);
8388 }
8389 
8390 /// Retrieve a template name representing an unqualified-id that has been
8391 /// assumed to name a template for ADL purposes.
8392 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8393   auto *OT = new (*this) AssumedTemplateStorage(Name);
8394   return TemplateName(OT);
8395 }
8396 
8397 /// Retrieve the template name that represents a qualified
8398 /// template name such as \c std::vector.
8399 TemplateName
8400 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8401                                      bool TemplateKeyword,
8402                                      TemplateDecl *Template) const {
8403   assert(NNS && "Missing nested-name-specifier in qualified template name");
8404 
8405   // FIXME: Canonicalization?
8406   llvm::FoldingSetNodeID ID;
8407   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8408 
8409   void *InsertPos = nullptr;
8410   QualifiedTemplateName *QTN =
8411     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8412   if (!QTN) {
8413     QTN = new (*this, alignof(QualifiedTemplateName))
8414         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8415     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8416   }
8417 
8418   return TemplateName(QTN);
8419 }
8420 
8421 /// Retrieve the template name that represents a dependent
8422 /// template name such as \c MetaFun::template apply.
8423 TemplateName
8424 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8425                                      const IdentifierInfo *Name) const {
8426   assert((!NNS || NNS->isDependent()) &&
8427          "Nested name specifier must be dependent");
8428 
8429   llvm::FoldingSetNodeID ID;
8430   DependentTemplateName::Profile(ID, NNS, Name);
8431 
8432   void *InsertPos = nullptr;
8433   DependentTemplateName *QTN =
8434     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8435 
8436   if (QTN)
8437     return TemplateName(QTN);
8438 
8439   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8440   if (CanonNNS == NNS) {
8441     QTN = new (*this, alignof(DependentTemplateName))
8442         DependentTemplateName(NNS, Name);
8443   } else {
8444     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8445     QTN = new (*this, alignof(DependentTemplateName))
8446         DependentTemplateName(NNS, Name, Canon);
8447     DependentTemplateName *CheckQTN =
8448       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8449     assert(!CheckQTN && "Dependent type name canonicalization broken");
8450     (void)CheckQTN;
8451   }
8452 
8453   DependentTemplateNames.InsertNode(QTN, InsertPos);
8454   return TemplateName(QTN);
8455 }
8456 
8457 /// Retrieve the template name that represents a dependent
8458 /// template name such as \c MetaFun::template operator+.
8459 TemplateName
8460 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8461                                      OverloadedOperatorKind Operator) const {
8462   assert((!NNS || NNS->isDependent()) &&
8463          "Nested name specifier must be dependent");
8464 
8465   llvm::FoldingSetNodeID ID;
8466   DependentTemplateName::Profile(ID, NNS, Operator);
8467 
8468   void *InsertPos = nullptr;
8469   DependentTemplateName *QTN
8470     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8471 
8472   if (QTN)
8473     return TemplateName(QTN);
8474 
8475   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8476   if (CanonNNS == NNS) {
8477     QTN = new (*this, alignof(DependentTemplateName))
8478         DependentTemplateName(NNS, Operator);
8479   } else {
8480     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8481     QTN = new (*this, alignof(DependentTemplateName))
8482         DependentTemplateName(NNS, Operator, Canon);
8483 
8484     DependentTemplateName *CheckQTN
8485       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8486     assert(!CheckQTN && "Dependent template name canonicalization broken");
8487     (void)CheckQTN;
8488   }
8489 
8490   DependentTemplateNames.InsertNode(QTN, InsertPos);
8491   return TemplateName(QTN);
8492 }
8493 
8494 TemplateName
8495 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8496                                          TemplateName replacement) const {
8497   llvm::FoldingSetNodeID ID;
8498   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8499 
8500   void *insertPos = nullptr;
8501   SubstTemplateTemplateParmStorage *subst
8502     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8503 
8504   if (!subst) {
8505     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8506     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8507   }
8508 
8509   return TemplateName(subst);
8510 }
8511 
8512 TemplateName
8513 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8514                                        const TemplateArgument &ArgPack) const {
8515   auto &Self = const_cast<ASTContext &>(*this);
8516   llvm::FoldingSetNodeID ID;
8517   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8518 
8519   void *InsertPos = nullptr;
8520   SubstTemplateTemplateParmPackStorage *Subst
8521     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8522 
8523   if (!Subst) {
8524     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8525                                                            ArgPack.pack_size(),
8526                                                          ArgPack.pack_begin());
8527     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8528   }
8529 
8530   return TemplateName(Subst);
8531 }
8532 
8533 /// getFromTargetType - Given one of the integer types provided by
8534 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8535 /// is actually a value of type @c TargetInfo::IntType.
8536 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8537   switch (Type) {
8538   case TargetInfo::NoInt: return {};
8539   case TargetInfo::SignedChar: return SignedCharTy;
8540   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8541   case TargetInfo::SignedShort: return ShortTy;
8542   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8543   case TargetInfo::SignedInt: return IntTy;
8544   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8545   case TargetInfo::SignedLong: return LongTy;
8546   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8547   case TargetInfo::SignedLongLong: return LongLongTy;
8548   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8549   }
8550 
8551   llvm_unreachable("Unhandled TargetInfo::IntType value");
8552 }
8553 
8554 //===----------------------------------------------------------------------===//
8555 //                        Type Predicates.
8556 //===----------------------------------------------------------------------===//
8557 
8558 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8559 /// garbage collection attribute.
8560 ///
8561 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8562   if (getLangOpts().getGC() == LangOptions::NonGC)
8563     return Qualifiers::GCNone;
8564 
8565   assert(getLangOpts().ObjC);
8566   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8567 
8568   // Default behaviour under objective-C's gc is for ObjC pointers
8569   // (or pointers to them) be treated as though they were declared
8570   // as __strong.
8571   if (GCAttrs == Qualifiers::GCNone) {
8572     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8573       return Qualifiers::Strong;
8574     else if (Ty->isPointerType())
8575       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8576   } else {
8577     // It's not valid to set GC attributes on anything that isn't a
8578     // pointer.
8579 #ifndef NDEBUG
8580     QualType CT = Ty->getCanonicalTypeInternal();
8581     while (const auto *AT = dyn_cast<ArrayType>(CT))
8582       CT = AT->getElementType();
8583     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8584 #endif
8585   }
8586   return GCAttrs;
8587 }
8588 
8589 //===----------------------------------------------------------------------===//
8590 //                        Type Compatibility Testing
8591 //===----------------------------------------------------------------------===//
8592 
8593 /// areCompatVectorTypes - Return true if the two specified vector types are
8594 /// compatible.
8595 static bool areCompatVectorTypes(const VectorType *LHS,
8596                                  const VectorType *RHS) {
8597   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8598   return LHS->getElementType() == RHS->getElementType() &&
8599          LHS->getNumElements() == RHS->getNumElements();
8600 }
8601 
8602 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8603 /// compatible.
8604 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8605                                  const ConstantMatrixType *RHS) {
8606   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8607   return LHS->getElementType() == RHS->getElementType() &&
8608          LHS->getNumRows() == RHS->getNumRows() &&
8609          LHS->getNumColumns() == RHS->getNumColumns();
8610 }
8611 
8612 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8613                                           QualType SecondVec) {
8614   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8615   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8616 
8617   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8618     return true;
8619 
8620   // Treat Neon vector types and most AltiVec vector types as if they are the
8621   // equivalent GCC vector types.
8622   const auto *First = FirstVec->castAs<VectorType>();
8623   const auto *Second = SecondVec->castAs<VectorType>();
8624   if (First->getNumElements() == Second->getNumElements() &&
8625       hasSameType(First->getElementType(), Second->getElementType()) &&
8626       First->getVectorKind() != VectorType::AltiVecPixel &&
8627       First->getVectorKind() != VectorType::AltiVecBool &&
8628       Second->getVectorKind() != VectorType::AltiVecPixel &&
8629       Second->getVectorKind() != VectorType::AltiVecBool &&
8630       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8631       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
8632       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
8633       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
8634     return true;
8635 
8636   return false;
8637 }
8638 
8639 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
8640                                        QualType SecondType) {
8641   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8642           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8643          "Expected SVE builtin type and vector type!");
8644 
8645   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
8646     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
8647       if (const auto *VT = SecondType->getAs<VectorType>()) {
8648         // Predicates have the same representation as uint8 so we also have to
8649         // check the kind to make these types incompatible.
8650         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
8651           return BT->getKind() == BuiltinType::SveBool;
8652         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
8653           return VT->getElementType().getCanonicalType() ==
8654                  FirstType->getSveEltType(*this);
8655         else if (VT->getVectorKind() == VectorType::GenericVector)
8656           return getTypeSize(SecondType) == getLangOpts().ArmSveVectorBits &&
8657                  hasSameType(VT->getElementType(),
8658                              getBuiltinVectorTypeInfo(BT).ElementType);
8659       }
8660     }
8661     return false;
8662   };
8663 
8664   return IsValidCast(FirstType, SecondType) ||
8665          IsValidCast(SecondType, FirstType);
8666 }
8667 
8668 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
8669                                           QualType SecondType) {
8670   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
8671           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
8672          "Expected SVE builtin type and vector type!");
8673 
8674   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
8675     if (!FirstType->getAs<BuiltinType>())
8676       return false;
8677 
8678     const auto *VecTy = SecondType->getAs<VectorType>();
8679     if (VecTy &&
8680         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
8681          VecTy->getVectorKind() == VectorType::GenericVector)) {
8682       const LangOptions::LaxVectorConversionKind LVCKind =
8683           getLangOpts().getLaxVectorConversions();
8684 
8685       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
8686       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
8687       // converts to VLAT and VLAT implicitly converts to GNUT."
8688       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
8689       // predicates.
8690       if (VecTy->getVectorKind() == VectorType::GenericVector &&
8691           getTypeSize(SecondType) != getLangOpts().ArmSveVectorBits)
8692         return false;
8693 
8694       // If -flax-vector-conversions=all is specified, the types are
8695       // certainly compatible.
8696       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
8697         return true;
8698 
8699       // If -flax-vector-conversions=integer is specified, the types are
8700       // compatible if the elements are integer types.
8701       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
8702         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
8703                FirstType->getSveEltType(*this)->isIntegerType();
8704     }
8705 
8706     return false;
8707   };
8708 
8709   return IsLaxCompatible(FirstType, SecondType) ||
8710          IsLaxCompatible(SecondType, FirstType);
8711 }
8712 
8713 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8714   while (true) {
8715     // __strong id
8716     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8717       if (Attr->getAttrKind() == attr::ObjCOwnership)
8718         return true;
8719 
8720       Ty = Attr->getModifiedType();
8721 
8722     // X *__strong (...)
8723     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8724       Ty = Paren->getInnerType();
8725 
8726     // We do not want to look through typedefs, typeof(expr),
8727     // typeof(type), or any other way that the type is somehow
8728     // abstracted.
8729     } else {
8730       return false;
8731     }
8732   }
8733 }
8734 
8735 //===----------------------------------------------------------------------===//
8736 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8737 //===----------------------------------------------------------------------===//
8738 
8739 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8740 /// inheritance hierarchy of 'rProto'.
8741 bool
8742 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8743                                            ObjCProtocolDecl *rProto) const {
8744   if (declaresSameEntity(lProto, rProto))
8745     return true;
8746   for (auto *PI : rProto->protocols())
8747     if (ProtocolCompatibleWithProtocol(lProto, PI))
8748       return true;
8749   return false;
8750 }
8751 
8752 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8753 /// Class<pr1, ...>.
8754 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8755     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8756   for (auto *lhsProto : lhs->quals()) {
8757     bool match = false;
8758     for (auto *rhsProto : rhs->quals()) {
8759       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8760         match = true;
8761         break;
8762       }
8763     }
8764     if (!match)
8765       return false;
8766   }
8767   return true;
8768 }
8769 
8770 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8771 /// ObjCQualifiedIDType.
8772 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8773     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8774     bool compare) {
8775   // Allow id<P..> and an 'id' in all cases.
8776   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8777     return true;
8778 
8779   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8780   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8781       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8782     return false;
8783 
8784   if (lhs->isObjCQualifiedIdType()) {
8785     if (rhs->qual_empty()) {
8786       // If the RHS is a unqualified interface pointer "NSString*",
8787       // make sure we check the class hierarchy.
8788       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8789         for (auto *I : lhs->quals()) {
8790           // when comparing an id<P> on lhs with a static type on rhs,
8791           // see if static class implements all of id's protocols, directly or
8792           // through its super class and categories.
8793           if (!rhsID->ClassImplementsProtocol(I, true))
8794             return false;
8795         }
8796       }
8797       // If there are no qualifiers and no interface, we have an 'id'.
8798       return true;
8799     }
8800     // Both the right and left sides have qualifiers.
8801     for (auto *lhsProto : lhs->quals()) {
8802       bool match = false;
8803 
8804       // when comparing an id<P> on lhs with a static type on rhs,
8805       // see if static class implements all of id's protocols, directly or
8806       // through its super class and categories.
8807       for (auto *rhsProto : rhs->quals()) {
8808         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8809             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8810           match = true;
8811           break;
8812         }
8813       }
8814       // If the RHS is a qualified interface pointer "NSString<P>*",
8815       // make sure we check the class hierarchy.
8816       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8817         for (auto *I : lhs->quals()) {
8818           // when comparing an id<P> on lhs with a static type on rhs,
8819           // see if static class implements all of id's protocols, directly or
8820           // through its super class and categories.
8821           if (rhsID->ClassImplementsProtocol(I, true)) {
8822             match = true;
8823             break;
8824           }
8825         }
8826       }
8827       if (!match)
8828         return false;
8829     }
8830 
8831     return true;
8832   }
8833 
8834   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8835 
8836   if (lhs->getInterfaceType()) {
8837     // If both the right and left sides have qualifiers.
8838     for (auto *lhsProto : lhs->quals()) {
8839       bool match = false;
8840 
8841       // when comparing an id<P> on rhs with a static type on lhs,
8842       // see if static class implements all of id's protocols, directly or
8843       // through its super class and categories.
8844       // First, lhs protocols in the qualifier list must be found, direct
8845       // or indirect in rhs's qualifier list or it is a mismatch.
8846       for (auto *rhsProto : rhs->quals()) {
8847         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8848             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8849           match = true;
8850           break;
8851         }
8852       }
8853       if (!match)
8854         return false;
8855     }
8856 
8857     // Static class's protocols, or its super class or category protocols
8858     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8859     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8860       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8861       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8862       // This is rather dubious but matches gcc's behavior. If lhs has
8863       // no type qualifier and its class has no static protocol(s)
8864       // assume that it is mismatch.
8865       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8866         return false;
8867       for (auto *lhsProto : LHSInheritedProtocols) {
8868         bool match = false;
8869         for (auto *rhsProto : rhs->quals()) {
8870           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8871               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8872             match = true;
8873             break;
8874           }
8875         }
8876         if (!match)
8877           return false;
8878       }
8879     }
8880     return true;
8881   }
8882   return false;
8883 }
8884 
8885 /// canAssignObjCInterfaces - Return true if the two interface types are
8886 /// compatible for assignment from RHS to LHS.  This handles validation of any
8887 /// protocol qualifiers on the LHS or RHS.
8888 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8889                                          const ObjCObjectPointerType *RHSOPT) {
8890   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8891   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8892 
8893   // If either type represents the built-in 'id' type, return true.
8894   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8895     return true;
8896 
8897   // Function object that propagates a successful result or handles
8898   // __kindof types.
8899   auto finish = [&](bool succeeded) -> bool {
8900     if (succeeded)
8901       return true;
8902 
8903     if (!RHS->isKindOfType())
8904       return false;
8905 
8906     // Strip off __kindof and protocol qualifiers, then check whether
8907     // we can assign the other way.
8908     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8909                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8910   };
8911 
8912   // Casts from or to id<P> are allowed when the other side has compatible
8913   // protocols.
8914   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8915     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8916   }
8917 
8918   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8919   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8920     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8921   }
8922 
8923   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8924   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8925     return true;
8926   }
8927 
8928   // If we have 2 user-defined types, fall into that path.
8929   if (LHS->getInterface() && RHS->getInterface()) {
8930     return finish(canAssignObjCInterfaces(LHS, RHS));
8931   }
8932 
8933   return false;
8934 }
8935 
8936 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8937 /// for providing type-safety for objective-c pointers used to pass/return
8938 /// arguments in block literals. When passed as arguments, passing 'A*' where
8939 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8940 /// not OK. For the return type, the opposite is not OK.
8941 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8942                                          const ObjCObjectPointerType *LHSOPT,
8943                                          const ObjCObjectPointerType *RHSOPT,
8944                                          bool BlockReturnType) {
8945 
8946   // Function object that propagates a successful result or handles
8947   // __kindof types.
8948   auto finish = [&](bool succeeded) -> bool {
8949     if (succeeded)
8950       return true;
8951 
8952     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8953     if (!Expected->isKindOfType())
8954       return false;
8955 
8956     // Strip off __kindof and protocol qualifiers, then check whether
8957     // we can assign the other way.
8958     return canAssignObjCInterfacesInBlockPointer(
8959              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8960              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8961              BlockReturnType);
8962   };
8963 
8964   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8965     return true;
8966 
8967   if (LHSOPT->isObjCBuiltinType()) {
8968     return finish(RHSOPT->isObjCBuiltinType() ||
8969                   RHSOPT->isObjCQualifiedIdType());
8970   }
8971 
8972   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8973     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8974       // Use for block parameters previous type checking for compatibility.
8975       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8976                     // Or corrected type checking as in non-compat mode.
8977                     (!BlockReturnType &&
8978                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8979     else
8980       return finish(ObjCQualifiedIdTypesAreCompatible(
8981           (BlockReturnType ? LHSOPT : RHSOPT),
8982           (BlockReturnType ? RHSOPT : LHSOPT), false));
8983   }
8984 
8985   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8986   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8987   if (LHS && RHS)  { // We have 2 user-defined types.
8988     if (LHS != RHS) {
8989       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8990         return finish(BlockReturnType);
8991       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8992         return finish(!BlockReturnType);
8993     }
8994     else
8995       return true;
8996   }
8997   return false;
8998 }
8999 
9000 /// Comparison routine for Objective-C protocols to be used with
9001 /// llvm::array_pod_sort.
9002 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9003                                       ObjCProtocolDecl * const *rhs) {
9004   return (*lhs)->getName().compare((*rhs)->getName());
9005 }
9006 
9007 /// getIntersectionOfProtocols - This routine finds the intersection of set
9008 /// of protocols inherited from two distinct objective-c pointer objects with
9009 /// the given common base.
9010 /// It is used to build composite qualifier list of the composite type of
9011 /// the conditional expression involving two objective-c pointer objects.
9012 static
9013 void getIntersectionOfProtocols(ASTContext &Context,
9014                                 const ObjCInterfaceDecl *CommonBase,
9015                                 const ObjCObjectPointerType *LHSOPT,
9016                                 const ObjCObjectPointerType *RHSOPT,
9017       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9018 
9019   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9020   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9021   assert(LHS->getInterface() && "LHS must have an interface base");
9022   assert(RHS->getInterface() && "RHS must have an interface base");
9023 
9024   // Add all of the protocols for the LHS.
9025   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9026 
9027   // Start with the protocol qualifiers.
9028   for (auto proto : LHS->quals()) {
9029     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9030   }
9031 
9032   // Also add the protocols associated with the LHS interface.
9033   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9034 
9035   // Add all of the protocols for the RHS.
9036   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9037 
9038   // Start with the protocol qualifiers.
9039   for (auto proto : RHS->quals()) {
9040     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9041   }
9042 
9043   // Also add the protocols associated with the RHS interface.
9044   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9045 
9046   // Compute the intersection of the collected protocol sets.
9047   for (auto proto : LHSProtocolSet) {
9048     if (RHSProtocolSet.count(proto))
9049       IntersectionSet.push_back(proto);
9050   }
9051 
9052   // Compute the set of protocols that is implied by either the common type or
9053   // the protocols within the intersection.
9054   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9055   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9056 
9057   // Remove any implied protocols from the list of inherited protocols.
9058   if (!ImpliedProtocols.empty()) {
9059     IntersectionSet.erase(
9060       std::remove_if(IntersectionSet.begin(),
9061                      IntersectionSet.end(),
9062                      [&](ObjCProtocolDecl *proto) -> bool {
9063                        return ImpliedProtocols.count(proto) > 0;
9064                      }),
9065       IntersectionSet.end());
9066   }
9067 
9068   // Sort the remaining protocols by name.
9069   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9070                        compareObjCProtocolsByName);
9071 }
9072 
9073 /// Determine whether the first type is a subtype of the second.
9074 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9075                                      QualType rhs) {
9076   // Common case: two object pointers.
9077   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9078   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9079   if (lhsOPT && rhsOPT)
9080     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9081 
9082   // Two block pointers.
9083   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9084   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9085   if (lhsBlock && rhsBlock)
9086     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9087 
9088   // If either is an unqualified 'id' and the other is a block, it's
9089   // acceptable.
9090   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9091       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9092     return true;
9093 
9094   return false;
9095 }
9096 
9097 // Check that the given Objective-C type argument lists are equivalent.
9098 static bool sameObjCTypeArgs(ASTContext &ctx,
9099                              const ObjCInterfaceDecl *iface,
9100                              ArrayRef<QualType> lhsArgs,
9101                              ArrayRef<QualType> rhsArgs,
9102                              bool stripKindOf) {
9103   if (lhsArgs.size() != rhsArgs.size())
9104     return false;
9105 
9106   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9107   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9108     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9109       continue;
9110 
9111     switch (typeParams->begin()[i]->getVariance()) {
9112     case ObjCTypeParamVariance::Invariant:
9113       if (!stripKindOf ||
9114           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9115                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9116         return false;
9117       }
9118       break;
9119 
9120     case ObjCTypeParamVariance::Covariant:
9121       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9122         return false;
9123       break;
9124 
9125     case ObjCTypeParamVariance::Contravariant:
9126       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9127         return false;
9128       break;
9129     }
9130   }
9131 
9132   return true;
9133 }
9134 
9135 QualType ASTContext::areCommonBaseCompatible(
9136            const ObjCObjectPointerType *Lptr,
9137            const ObjCObjectPointerType *Rptr) {
9138   const ObjCObjectType *LHS = Lptr->getObjectType();
9139   const ObjCObjectType *RHS = Rptr->getObjectType();
9140   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9141   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9142 
9143   if (!LDecl || !RDecl)
9144     return {};
9145 
9146   // When either LHS or RHS is a kindof type, we should return a kindof type.
9147   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9148   // kindof(A).
9149   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9150 
9151   // Follow the left-hand side up the class hierarchy until we either hit a
9152   // root or find the RHS. Record the ancestors in case we don't find it.
9153   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9154     LHSAncestors;
9155   while (true) {
9156     // Record this ancestor. We'll need this if the common type isn't in the
9157     // path from the LHS to the root.
9158     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9159 
9160     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9161       // Get the type arguments.
9162       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9163       bool anyChanges = false;
9164       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9165         // Both have type arguments, compare them.
9166         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9167                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9168                               /*stripKindOf=*/true))
9169           return {};
9170       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9171         // If only one has type arguments, the result will not have type
9172         // arguments.
9173         LHSTypeArgs = {};
9174         anyChanges = true;
9175       }
9176 
9177       // Compute the intersection of protocols.
9178       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9179       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9180                                  Protocols);
9181       if (!Protocols.empty())
9182         anyChanges = true;
9183 
9184       // If anything in the LHS will have changed, build a new result type.
9185       // If we need to return a kindof type but LHS is not a kindof type, we
9186       // build a new result type.
9187       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9188         QualType Result = getObjCInterfaceType(LHS->getInterface());
9189         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9190                                    anyKindOf || LHS->isKindOfType());
9191         return getObjCObjectPointerType(Result);
9192       }
9193 
9194       return getObjCObjectPointerType(QualType(LHS, 0));
9195     }
9196 
9197     // Find the superclass.
9198     QualType LHSSuperType = LHS->getSuperClassType();
9199     if (LHSSuperType.isNull())
9200       break;
9201 
9202     LHS = LHSSuperType->castAs<ObjCObjectType>();
9203   }
9204 
9205   // We didn't find anything by following the LHS to its root; now check
9206   // the RHS against the cached set of ancestors.
9207   while (true) {
9208     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9209     if (KnownLHS != LHSAncestors.end()) {
9210       LHS = KnownLHS->second;
9211 
9212       // Get the type arguments.
9213       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9214       bool anyChanges = false;
9215       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9216         // Both have type arguments, compare them.
9217         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9218                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9219                               /*stripKindOf=*/true))
9220           return {};
9221       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9222         // If only one has type arguments, the result will not have type
9223         // arguments.
9224         RHSTypeArgs = {};
9225         anyChanges = true;
9226       }
9227 
9228       // Compute the intersection of protocols.
9229       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9230       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9231                                  Protocols);
9232       if (!Protocols.empty())
9233         anyChanges = true;
9234 
9235       // If we need to return a kindof type but RHS is not a kindof type, we
9236       // build a new result type.
9237       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9238         QualType Result = getObjCInterfaceType(RHS->getInterface());
9239         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9240                                    anyKindOf || RHS->isKindOfType());
9241         return getObjCObjectPointerType(Result);
9242       }
9243 
9244       return getObjCObjectPointerType(QualType(RHS, 0));
9245     }
9246 
9247     // Find the superclass of the RHS.
9248     QualType RHSSuperType = RHS->getSuperClassType();
9249     if (RHSSuperType.isNull())
9250       break;
9251 
9252     RHS = RHSSuperType->castAs<ObjCObjectType>();
9253   }
9254 
9255   return {};
9256 }
9257 
9258 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9259                                          const ObjCObjectType *RHS) {
9260   assert(LHS->getInterface() && "LHS is not an interface type");
9261   assert(RHS->getInterface() && "RHS is not an interface type");
9262 
9263   // Verify that the base decls are compatible: the RHS must be a subclass of
9264   // the LHS.
9265   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9266   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9267   if (!IsSuperClass)
9268     return false;
9269 
9270   // If the LHS has protocol qualifiers, determine whether all of them are
9271   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9272   // LHS).
9273   if (LHS->getNumProtocols() > 0) {
9274     // OK if conversion of LHS to SuperClass results in narrowing of types
9275     // ; i.e., SuperClass may implement at least one of the protocols
9276     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9277     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9278     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9279     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9280     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9281     // qualifiers.
9282     for (auto *RHSPI : RHS->quals())
9283       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9284     // If there is no protocols associated with RHS, it is not a match.
9285     if (SuperClassInheritedProtocols.empty())
9286       return false;
9287 
9288     for (const auto *LHSProto : LHS->quals()) {
9289       bool SuperImplementsProtocol = false;
9290       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9291         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9292           SuperImplementsProtocol = true;
9293           break;
9294         }
9295       if (!SuperImplementsProtocol)
9296         return false;
9297     }
9298   }
9299 
9300   // If the LHS is specialized, we may need to check type arguments.
9301   if (LHS->isSpecialized()) {
9302     // Follow the superclass chain until we've matched the LHS class in the
9303     // hierarchy. This substitutes type arguments through.
9304     const ObjCObjectType *RHSSuper = RHS;
9305     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9306       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9307 
9308     // If the RHS is specializd, compare type arguments.
9309     if (RHSSuper->isSpecialized() &&
9310         !sameObjCTypeArgs(*this, LHS->getInterface(),
9311                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9312                           /*stripKindOf=*/true)) {
9313       return false;
9314     }
9315   }
9316 
9317   return true;
9318 }
9319 
9320 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9321   // get the "pointed to" types
9322   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9323   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9324 
9325   if (!LHSOPT || !RHSOPT)
9326     return false;
9327 
9328   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9329          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9330 }
9331 
9332 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9333   return canAssignObjCInterfaces(
9334       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9335       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9336 }
9337 
9338 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9339 /// both shall have the identically qualified version of a compatible type.
9340 /// C99 6.2.7p1: Two types have compatible types if their types are the
9341 /// same. See 6.7.[2,3,5] for additional rules.
9342 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9343                                     bool CompareUnqualified) {
9344   if (getLangOpts().CPlusPlus)
9345     return hasSameType(LHS, RHS);
9346 
9347   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9348 }
9349 
9350 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9351   return typesAreCompatible(LHS, RHS);
9352 }
9353 
9354 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9355   return !mergeTypes(LHS, RHS, true).isNull();
9356 }
9357 
9358 /// mergeTransparentUnionType - if T is a transparent union type and a member
9359 /// of T is compatible with SubType, return the merged type, else return
9360 /// QualType()
9361 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9362                                                bool OfBlockPointer,
9363                                                bool Unqualified) {
9364   if (const RecordType *UT = T->getAsUnionType()) {
9365     RecordDecl *UD = UT->getDecl();
9366     if (UD->hasAttr<TransparentUnionAttr>()) {
9367       for (const auto *I : UD->fields()) {
9368         QualType ET = I->getType().getUnqualifiedType();
9369         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9370         if (!MT.isNull())
9371           return MT;
9372       }
9373     }
9374   }
9375 
9376   return {};
9377 }
9378 
9379 /// mergeFunctionParameterTypes - merge two types which appear as function
9380 /// parameter types
9381 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9382                                                  bool OfBlockPointer,
9383                                                  bool Unqualified) {
9384   // GNU extension: two types are compatible if they appear as a function
9385   // argument, one of the types is a transparent union type and the other
9386   // type is compatible with a union member
9387   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9388                                               Unqualified);
9389   if (!lmerge.isNull())
9390     return lmerge;
9391 
9392   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9393                                               Unqualified);
9394   if (!rmerge.isNull())
9395     return rmerge;
9396 
9397   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9398 }
9399 
9400 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9401                                         bool OfBlockPointer, bool Unqualified,
9402                                         bool AllowCXX) {
9403   const auto *lbase = lhs->castAs<FunctionType>();
9404   const auto *rbase = rhs->castAs<FunctionType>();
9405   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9406   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9407   bool allLTypes = true;
9408   bool allRTypes = true;
9409 
9410   // Check return type
9411   QualType retType;
9412   if (OfBlockPointer) {
9413     QualType RHS = rbase->getReturnType();
9414     QualType LHS = lbase->getReturnType();
9415     bool UnqualifiedResult = Unqualified;
9416     if (!UnqualifiedResult)
9417       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9418     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9419   }
9420   else
9421     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9422                          Unqualified);
9423   if (retType.isNull())
9424     return {};
9425 
9426   if (Unqualified)
9427     retType = retType.getUnqualifiedType();
9428 
9429   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9430   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9431   if (Unqualified) {
9432     LRetType = LRetType.getUnqualifiedType();
9433     RRetType = RRetType.getUnqualifiedType();
9434   }
9435 
9436   if (getCanonicalType(retType) != LRetType)
9437     allLTypes = false;
9438   if (getCanonicalType(retType) != RRetType)
9439     allRTypes = false;
9440 
9441   // FIXME: double check this
9442   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9443   //                           rbase->getRegParmAttr() != 0 &&
9444   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9445   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9446   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9447 
9448   // Compatible functions must have compatible calling conventions
9449   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9450     return {};
9451 
9452   // Regparm is part of the calling convention.
9453   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9454     return {};
9455   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9456     return {};
9457 
9458   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9459     return {};
9460   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9461     return {};
9462   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9463     return {};
9464 
9465   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9466   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9467 
9468   if (lbaseInfo.getNoReturn() != NoReturn)
9469     allLTypes = false;
9470   if (rbaseInfo.getNoReturn() != NoReturn)
9471     allRTypes = false;
9472 
9473   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9474 
9475   if (lproto && rproto) { // two C99 style function prototypes
9476     assert((AllowCXX ||
9477             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9478            "C++ shouldn't be here");
9479     // Compatible functions must have the same number of parameters
9480     if (lproto->getNumParams() != rproto->getNumParams())
9481       return {};
9482 
9483     // Variadic and non-variadic functions aren't compatible
9484     if (lproto->isVariadic() != rproto->isVariadic())
9485       return {};
9486 
9487     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9488       return {};
9489 
9490     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9491     bool canUseLeft, canUseRight;
9492     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9493                                newParamInfos))
9494       return {};
9495 
9496     if (!canUseLeft)
9497       allLTypes = false;
9498     if (!canUseRight)
9499       allRTypes = false;
9500 
9501     // Check parameter type compatibility
9502     SmallVector<QualType, 10> types;
9503     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9504       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9505       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9506       QualType paramType = mergeFunctionParameterTypes(
9507           lParamType, rParamType, OfBlockPointer, Unqualified);
9508       if (paramType.isNull())
9509         return {};
9510 
9511       if (Unqualified)
9512         paramType = paramType.getUnqualifiedType();
9513 
9514       types.push_back(paramType);
9515       if (Unqualified) {
9516         lParamType = lParamType.getUnqualifiedType();
9517         rParamType = rParamType.getUnqualifiedType();
9518       }
9519 
9520       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9521         allLTypes = false;
9522       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9523         allRTypes = false;
9524     }
9525 
9526     if (allLTypes) return lhs;
9527     if (allRTypes) return rhs;
9528 
9529     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9530     EPI.ExtInfo = einfo;
9531     EPI.ExtParameterInfos =
9532         newParamInfos.empty() ? nullptr : newParamInfos.data();
9533     return getFunctionType(retType, types, EPI);
9534   }
9535 
9536   if (lproto) allRTypes = false;
9537   if (rproto) allLTypes = false;
9538 
9539   const FunctionProtoType *proto = lproto ? lproto : rproto;
9540   if (proto) {
9541     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9542     if (proto->isVariadic())
9543       return {};
9544     // Check that the types are compatible with the types that
9545     // would result from default argument promotions (C99 6.7.5.3p15).
9546     // The only types actually affected are promotable integer
9547     // types and floats, which would be passed as a different
9548     // type depending on whether the prototype is visible.
9549     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9550       QualType paramTy = proto->getParamType(i);
9551 
9552       // Look at the converted type of enum types, since that is the type used
9553       // to pass enum values.
9554       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9555         paramTy = Enum->getDecl()->getIntegerType();
9556         if (paramTy.isNull())
9557           return {};
9558       }
9559 
9560       if (paramTy->isPromotableIntegerType() ||
9561           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9562         return {};
9563     }
9564 
9565     if (allLTypes) return lhs;
9566     if (allRTypes) return rhs;
9567 
9568     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9569     EPI.ExtInfo = einfo;
9570     return getFunctionType(retType, proto->getParamTypes(), EPI);
9571   }
9572 
9573   if (allLTypes) return lhs;
9574   if (allRTypes) return rhs;
9575   return getFunctionNoProtoType(retType, einfo);
9576 }
9577 
9578 /// Given that we have an enum type and a non-enum type, try to merge them.
9579 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9580                                      QualType other, bool isBlockReturnType) {
9581   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9582   // a signed integer type, or an unsigned integer type.
9583   // Compatibility is based on the underlying type, not the promotion
9584   // type.
9585   QualType underlyingType = ET->getDecl()->getIntegerType();
9586   if (underlyingType.isNull())
9587     return {};
9588   if (Context.hasSameType(underlyingType, other))
9589     return other;
9590 
9591   // In block return types, we're more permissive and accept any
9592   // integral type of the same size.
9593   if (isBlockReturnType && other->isIntegerType() &&
9594       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9595     return other;
9596 
9597   return {};
9598 }
9599 
9600 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9601                                 bool OfBlockPointer,
9602                                 bool Unqualified, bool BlockReturnType) {
9603   // C++ [expr]: If an expression initially has the type "reference to T", the
9604   // type is adjusted to "T" prior to any further analysis, the expression
9605   // designates the object or function denoted by the reference, and the
9606   // expression is an lvalue unless the reference is an rvalue reference and
9607   // the expression is a function call (possibly inside parentheses).
9608   if (LHS->getAs<ReferenceType>() || RHS->getAs<ReferenceType>())
9609     return {};
9610 
9611   if (Unqualified) {
9612     LHS = LHS.getUnqualifiedType();
9613     RHS = RHS.getUnqualifiedType();
9614   }
9615 
9616   QualType LHSCan = getCanonicalType(LHS),
9617            RHSCan = getCanonicalType(RHS);
9618 
9619   // If two types are identical, they are compatible.
9620   if (LHSCan == RHSCan)
9621     return LHS;
9622 
9623   // If the qualifiers are different, the types aren't compatible... mostly.
9624   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9625   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9626   if (LQuals != RQuals) {
9627     // If any of these qualifiers are different, we have a type
9628     // mismatch.
9629     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9630         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9631         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9632         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9633       return {};
9634 
9635     // Exactly one GC qualifier difference is allowed: __strong is
9636     // okay if the other type has no GC qualifier but is an Objective
9637     // C object pointer (i.e. implicitly strong by default).  We fix
9638     // this by pretending that the unqualified type was actually
9639     // qualified __strong.
9640     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9641     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9642     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9643 
9644     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9645       return {};
9646 
9647     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9648       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9649     }
9650     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9651       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9652     }
9653     return {};
9654   }
9655 
9656   // Okay, qualifiers are equal.
9657 
9658   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9659   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9660 
9661   // We want to consider the two function types to be the same for these
9662   // comparisons, just force one to the other.
9663   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9664   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9665 
9666   // Same as above for arrays
9667   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9668     LHSClass = Type::ConstantArray;
9669   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9670     RHSClass = Type::ConstantArray;
9671 
9672   // ObjCInterfaces are just specialized ObjCObjects.
9673   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9674   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9675 
9676   // Canonicalize ExtVector -> Vector.
9677   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9678   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9679 
9680   // If the canonical type classes don't match.
9681   if (LHSClass != RHSClass) {
9682     // Note that we only have special rules for turning block enum
9683     // returns into block int returns, not vice-versa.
9684     if (const auto *ETy = LHS->getAs<EnumType>()) {
9685       return mergeEnumWithInteger(*this, ETy, RHS, false);
9686     }
9687     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9688       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9689     }
9690     // allow block pointer type to match an 'id' type.
9691     if (OfBlockPointer && !BlockReturnType) {
9692        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9693          return LHS;
9694       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9695         return RHS;
9696     }
9697 
9698     return {};
9699   }
9700 
9701   // The canonical type classes match.
9702   switch (LHSClass) {
9703 #define TYPE(Class, Base)
9704 #define ABSTRACT_TYPE(Class, Base)
9705 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9706 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9707 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9708 #include "clang/AST/TypeNodes.inc"
9709     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9710 
9711   case Type::Auto:
9712   case Type::DeducedTemplateSpecialization:
9713   case Type::LValueReference:
9714   case Type::RValueReference:
9715   case Type::MemberPointer:
9716     llvm_unreachable("C++ should never be in mergeTypes");
9717 
9718   case Type::ObjCInterface:
9719   case Type::IncompleteArray:
9720   case Type::VariableArray:
9721   case Type::FunctionProto:
9722   case Type::ExtVector:
9723     llvm_unreachable("Types are eliminated above");
9724 
9725   case Type::Pointer:
9726   {
9727     // Merge two pointer types, while trying to preserve typedef info
9728     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9729     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9730     if (Unqualified) {
9731       LHSPointee = LHSPointee.getUnqualifiedType();
9732       RHSPointee = RHSPointee.getUnqualifiedType();
9733     }
9734     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9735                                      Unqualified);
9736     if (ResultType.isNull())
9737       return {};
9738     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9739       return LHS;
9740     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9741       return RHS;
9742     return getPointerType(ResultType);
9743   }
9744   case Type::BlockPointer:
9745   {
9746     // Merge two block pointer types, while trying to preserve typedef info
9747     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9748     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9749     if (Unqualified) {
9750       LHSPointee = LHSPointee.getUnqualifiedType();
9751       RHSPointee = RHSPointee.getUnqualifiedType();
9752     }
9753     if (getLangOpts().OpenCL) {
9754       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9755       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9756       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9757       // 6.12.5) thus the following check is asymmetric.
9758       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9759         return {};
9760       LHSPteeQual.removeAddressSpace();
9761       RHSPteeQual.removeAddressSpace();
9762       LHSPointee =
9763           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9764       RHSPointee =
9765           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9766     }
9767     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9768                                      Unqualified);
9769     if (ResultType.isNull())
9770       return {};
9771     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9772       return LHS;
9773     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9774       return RHS;
9775     return getBlockPointerType(ResultType);
9776   }
9777   case Type::Atomic:
9778   {
9779     // Merge two pointer types, while trying to preserve typedef info
9780     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9781     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9782     if (Unqualified) {
9783       LHSValue = LHSValue.getUnqualifiedType();
9784       RHSValue = RHSValue.getUnqualifiedType();
9785     }
9786     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9787                                      Unqualified);
9788     if (ResultType.isNull())
9789       return {};
9790     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9791       return LHS;
9792     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9793       return RHS;
9794     return getAtomicType(ResultType);
9795   }
9796   case Type::ConstantArray:
9797   {
9798     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9799     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9800     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9801       return {};
9802 
9803     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9804     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9805     if (Unqualified) {
9806       LHSElem = LHSElem.getUnqualifiedType();
9807       RHSElem = RHSElem.getUnqualifiedType();
9808     }
9809 
9810     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9811     if (ResultType.isNull())
9812       return {};
9813 
9814     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9815     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9816 
9817     // If either side is a variable array, and both are complete, check whether
9818     // the current dimension is definite.
9819     if (LVAT || RVAT) {
9820       auto SizeFetch = [this](const VariableArrayType* VAT,
9821           const ConstantArrayType* CAT)
9822           -> std::pair<bool,llvm::APInt> {
9823         if (VAT) {
9824           Optional<llvm::APSInt> TheInt;
9825           Expr *E = VAT->getSizeExpr();
9826           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
9827             return std::make_pair(true, *TheInt);
9828           return std::make_pair(false, llvm::APSInt());
9829         }
9830         if (CAT)
9831           return std::make_pair(true, CAT->getSize());
9832         return std::make_pair(false, llvm::APInt());
9833       };
9834 
9835       bool HaveLSize, HaveRSize;
9836       llvm::APInt LSize, RSize;
9837       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9838       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9839       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9840         return {}; // Definite, but unequal, array dimension
9841     }
9842 
9843     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9844       return LHS;
9845     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9846       return RHS;
9847     if (LCAT)
9848       return getConstantArrayType(ResultType, LCAT->getSize(),
9849                                   LCAT->getSizeExpr(),
9850                                   ArrayType::ArraySizeModifier(), 0);
9851     if (RCAT)
9852       return getConstantArrayType(ResultType, RCAT->getSize(),
9853                                   RCAT->getSizeExpr(),
9854                                   ArrayType::ArraySizeModifier(), 0);
9855     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9856       return LHS;
9857     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9858       return RHS;
9859     if (LVAT) {
9860       // FIXME: This isn't correct! But tricky to implement because
9861       // the array's size has to be the size of LHS, but the type
9862       // has to be different.
9863       return LHS;
9864     }
9865     if (RVAT) {
9866       // FIXME: This isn't correct! But tricky to implement because
9867       // the array's size has to be the size of RHS, but the type
9868       // has to be different.
9869       return RHS;
9870     }
9871     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9872     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9873     return getIncompleteArrayType(ResultType,
9874                                   ArrayType::ArraySizeModifier(), 0);
9875   }
9876   case Type::FunctionNoProto:
9877     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9878   case Type::Record:
9879   case Type::Enum:
9880     return {};
9881   case Type::Builtin:
9882     // Only exactly equal builtin types are compatible, which is tested above.
9883     return {};
9884   case Type::Complex:
9885     // Distinct complex types are incompatible.
9886     return {};
9887   case Type::Vector:
9888     // FIXME: The merged type should be an ExtVector!
9889     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9890                              RHSCan->castAs<VectorType>()))
9891       return LHS;
9892     return {};
9893   case Type::ConstantMatrix:
9894     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9895                              RHSCan->castAs<ConstantMatrixType>()))
9896       return LHS;
9897     return {};
9898   case Type::ObjCObject: {
9899     // Check if the types are assignment compatible.
9900     // FIXME: This should be type compatibility, e.g. whether
9901     // "LHS x; RHS x;" at global scope is legal.
9902     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9903                                 RHS->castAs<ObjCObjectType>()))
9904       return LHS;
9905     return {};
9906   }
9907   case Type::ObjCObjectPointer:
9908     if (OfBlockPointer) {
9909       if (canAssignObjCInterfacesInBlockPointer(
9910               LHS->castAs<ObjCObjectPointerType>(),
9911               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9912         return LHS;
9913       return {};
9914     }
9915     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9916                                 RHS->castAs<ObjCObjectPointerType>()))
9917       return LHS;
9918     return {};
9919   case Type::Pipe:
9920     assert(LHS != RHS &&
9921            "Equivalent pipe types should have already been handled!");
9922     return {};
9923   case Type::ExtInt: {
9924     // Merge two ext-int types, while trying to preserve typedef info.
9925     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9926     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9927     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9928     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9929 
9930     // Like unsigned/int, shouldn't have a type if they dont match.
9931     if (LHSUnsigned != RHSUnsigned)
9932       return {};
9933 
9934     if (LHSBits != RHSBits)
9935       return {};
9936     return LHS;
9937   }
9938   }
9939 
9940   llvm_unreachable("Invalid Type::Class!");
9941 }
9942 
9943 bool ASTContext::mergeExtParameterInfo(
9944     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9945     bool &CanUseFirst, bool &CanUseSecond,
9946     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9947   assert(NewParamInfos.empty() && "param info list not empty");
9948   CanUseFirst = CanUseSecond = true;
9949   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9950   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9951 
9952   // Fast path: if the first type doesn't have ext parameter infos,
9953   // we match if and only if the second type also doesn't have them.
9954   if (!FirstHasInfo && !SecondHasInfo)
9955     return true;
9956 
9957   bool NeedParamInfo = false;
9958   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9959                           : SecondFnType->getExtParameterInfos().size();
9960 
9961   for (size_t I = 0; I < E; ++I) {
9962     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9963     if (FirstHasInfo)
9964       FirstParam = FirstFnType->getExtParameterInfo(I);
9965     if (SecondHasInfo)
9966       SecondParam = SecondFnType->getExtParameterInfo(I);
9967 
9968     // Cannot merge unless everything except the noescape flag matches.
9969     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9970       return false;
9971 
9972     bool FirstNoEscape = FirstParam.isNoEscape();
9973     bool SecondNoEscape = SecondParam.isNoEscape();
9974     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9975     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9976     if (NewParamInfos.back().getOpaqueValue())
9977       NeedParamInfo = true;
9978     if (FirstNoEscape != IsNoEscape)
9979       CanUseFirst = false;
9980     if (SecondNoEscape != IsNoEscape)
9981       CanUseSecond = false;
9982   }
9983 
9984   if (!NeedParamInfo)
9985     NewParamInfos.clear();
9986 
9987   return true;
9988 }
9989 
9990 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9991   ObjCLayouts[CD] = nullptr;
9992 }
9993 
9994 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9995 /// 'RHS' attributes and returns the merged version; including for function
9996 /// return types.
9997 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9998   QualType LHSCan = getCanonicalType(LHS),
9999   RHSCan = getCanonicalType(RHS);
10000   // If two types are identical, they are compatible.
10001   if (LHSCan == RHSCan)
10002     return LHS;
10003   if (RHSCan->isFunctionType()) {
10004     if (!LHSCan->isFunctionType())
10005       return {};
10006     QualType OldReturnType =
10007         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10008     QualType NewReturnType =
10009         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10010     QualType ResReturnType =
10011       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10012     if (ResReturnType.isNull())
10013       return {};
10014     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10015       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10016       // In either case, use OldReturnType to build the new function type.
10017       const auto *F = LHS->castAs<FunctionType>();
10018       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10019         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10020         EPI.ExtInfo = getFunctionExtInfo(LHS);
10021         QualType ResultType =
10022             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10023         return ResultType;
10024       }
10025     }
10026     return {};
10027   }
10028 
10029   // If the qualifiers are different, the types can still be merged.
10030   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10031   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10032   if (LQuals != RQuals) {
10033     // If any of these qualifiers are different, we have a type mismatch.
10034     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10035         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10036       return {};
10037 
10038     // Exactly one GC qualifier difference is allowed: __strong is
10039     // okay if the other type has no GC qualifier but is an Objective
10040     // C object pointer (i.e. implicitly strong by default).  We fix
10041     // this by pretending that the unqualified type was actually
10042     // qualified __strong.
10043     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10044     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10045     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10046 
10047     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10048       return {};
10049 
10050     if (GC_L == Qualifiers::Strong)
10051       return LHS;
10052     if (GC_R == Qualifiers::Strong)
10053       return RHS;
10054     return {};
10055   }
10056 
10057   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10058     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10059     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10060     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10061     if (ResQT == LHSBaseQT)
10062       return LHS;
10063     if (ResQT == RHSBaseQT)
10064       return RHS;
10065   }
10066   return {};
10067 }
10068 
10069 //===----------------------------------------------------------------------===//
10070 //                         Integer Predicates
10071 //===----------------------------------------------------------------------===//
10072 
10073 unsigned ASTContext::getIntWidth(QualType T) const {
10074   if (const auto *ET = T->getAs<EnumType>())
10075     T = ET->getDecl()->getIntegerType();
10076   if (T->isBooleanType())
10077     return 1;
10078   if(const auto *EIT = T->getAs<ExtIntType>())
10079     return EIT->getNumBits();
10080   // For builtin types, just use the standard type sizing method
10081   return (unsigned)getTypeSize(T);
10082 }
10083 
10084 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10085   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10086          "Unexpected type");
10087 
10088   // Turn <4 x signed int> -> <4 x unsigned int>
10089   if (const auto *VTy = T->getAs<VectorType>())
10090     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10091                          VTy->getNumElements(), VTy->getVectorKind());
10092 
10093   // For enums, we return the unsigned version of the base type.
10094   if (const auto *ETy = T->getAs<EnumType>())
10095     T = ETy->getDecl()->getIntegerType();
10096 
10097   switch (T->castAs<BuiltinType>()->getKind()) {
10098   case BuiltinType::Char_S:
10099   case BuiltinType::SChar:
10100     return UnsignedCharTy;
10101   case BuiltinType::Short:
10102     return UnsignedShortTy;
10103   case BuiltinType::Int:
10104     return UnsignedIntTy;
10105   case BuiltinType::Long:
10106     return UnsignedLongTy;
10107   case BuiltinType::LongLong:
10108     return UnsignedLongLongTy;
10109   case BuiltinType::Int128:
10110     return UnsignedInt128Ty;
10111   // wchar_t is special. It is either signed or not, but when it's signed,
10112   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10113   // version of it's underlying type instead.
10114   case BuiltinType::WChar_S:
10115     return getUnsignedWCharType();
10116 
10117   case BuiltinType::ShortAccum:
10118     return UnsignedShortAccumTy;
10119   case BuiltinType::Accum:
10120     return UnsignedAccumTy;
10121   case BuiltinType::LongAccum:
10122     return UnsignedLongAccumTy;
10123   case BuiltinType::SatShortAccum:
10124     return SatUnsignedShortAccumTy;
10125   case BuiltinType::SatAccum:
10126     return SatUnsignedAccumTy;
10127   case BuiltinType::SatLongAccum:
10128     return SatUnsignedLongAccumTy;
10129   case BuiltinType::ShortFract:
10130     return UnsignedShortFractTy;
10131   case BuiltinType::Fract:
10132     return UnsignedFractTy;
10133   case BuiltinType::LongFract:
10134     return UnsignedLongFractTy;
10135   case BuiltinType::SatShortFract:
10136     return SatUnsignedShortFractTy;
10137   case BuiltinType::SatFract:
10138     return SatUnsignedFractTy;
10139   case BuiltinType::SatLongFract:
10140     return SatUnsignedLongFractTy;
10141   default:
10142     llvm_unreachable("Unexpected signed integer or fixed point type");
10143   }
10144 }
10145 
10146 ASTMutationListener::~ASTMutationListener() = default;
10147 
10148 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10149                                             QualType ReturnType) {}
10150 
10151 //===----------------------------------------------------------------------===//
10152 //                          Builtin Type Computation
10153 //===----------------------------------------------------------------------===//
10154 
10155 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10156 /// pointer over the consumed characters.  This returns the resultant type.  If
10157 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10158 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10159 /// a vector of "i*".
10160 ///
10161 /// RequiresICE is filled in on return to indicate whether the value is required
10162 /// to be an Integer Constant Expression.
10163 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10164                                   ASTContext::GetBuiltinTypeError &Error,
10165                                   bool &RequiresICE,
10166                                   bool AllowTypeModifiers) {
10167   // Modifiers.
10168   int HowLong = 0;
10169   bool Signed = false, Unsigned = false;
10170   RequiresICE = false;
10171 
10172   // Read the prefixed modifiers first.
10173   bool Done = false;
10174   #ifndef NDEBUG
10175   bool IsSpecial = false;
10176   #endif
10177   while (!Done) {
10178     switch (*Str++) {
10179     default: Done = true; --Str; break;
10180     case 'I':
10181       RequiresICE = true;
10182       break;
10183     case 'S':
10184       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10185       assert(!Signed && "Can't use 'S' modifier multiple times!");
10186       Signed = true;
10187       break;
10188     case 'U':
10189       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10190       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10191       Unsigned = true;
10192       break;
10193     case 'L':
10194       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10195       assert(HowLong <= 2 && "Can't have LLLL modifier");
10196       ++HowLong;
10197       break;
10198     case 'N':
10199       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10200       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10201       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10202       #ifndef NDEBUG
10203       IsSpecial = true;
10204       #endif
10205       if (Context.getTargetInfo().getLongWidth() == 32)
10206         ++HowLong;
10207       break;
10208     case 'W':
10209       // This modifier represents int64 type.
10210       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10211       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10212       #ifndef NDEBUG
10213       IsSpecial = true;
10214       #endif
10215       switch (Context.getTargetInfo().getInt64Type()) {
10216       default:
10217         llvm_unreachable("Unexpected integer type");
10218       case TargetInfo::SignedLong:
10219         HowLong = 1;
10220         break;
10221       case TargetInfo::SignedLongLong:
10222         HowLong = 2;
10223         break;
10224       }
10225       break;
10226     case 'Z':
10227       // This modifier represents int32 type.
10228       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10229       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10230       #ifndef NDEBUG
10231       IsSpecial = true;
10232       #endif
10233       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10234       default:
10235         llvm_unreachable("Unexpected integer type");
10236       case TargetInfo::SignedInt:
10237         HowLong = 0;
10238         break;
10239       case TargetInfo::SignedLong:
10240         HowLong = 1;
10241         break;
10242       case TargetInfo::SignedLongLong:
10243         HowLong = 2;
10244         break;
10245       }
10246       break;
10247     case 'O':
10248       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10249       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10250       #ifndef NDEBUG
10251       IsSpecial = true;
10252       #endif
10253       if (Context.getLangOpts().OpenCL)
10254         HowLong = 1;
10255       else
10256         HowLong = 2;
10257       break;
10258     }
10259   }
10260 
10261   QualType Type;
10262 
10263   // Read the base type.
10264   switch (*Str++) {
10265   default: llvm_unreachable("Unknown builtin type letter!");
10266   case 'y':
10267     assert(HowLong == 0 && !Signed && !Unsigned &&
10268            "Bad modifiers used with 'y'!");
10269     Type = Context.BFloat16Ty;
10270     break;
10271   case 'v':
10272     assert(HowLong == 0 && !Signed && !Unsigned &&
10273            "Bad modifiers used with 'v'!");
10274     Type = Context.VoidTy;
10275     break;
10276   case 'h':
10277     assert(HowLong == 0 && !Signed && !Unsigned &&
10278            "Bad modifiers used with 'h'!");
10279     Type = Context.HalfTy;
10280     break;
10281   case 'f':
10282     assert(HowLong == 0 && !Signed && !Unsigned &&
10283            "Bad modifiers used with 'f'!");
10284     Type = Context.FloatTy;
10285     break;
10286   case 'd':
10287     assert(HowLong < 3 && !Signed && !Unsigned &&
10288            "Bad modifiers used with 'd'!");
10289     if (HowLong == 1)
10290       Type = Context.LongDoubleTy;
10291     else if (HowLong == 2)
10292       Type = Context.Float128Ty;
10293     else
10294       Type = Context.DoubleTy;
10295     break;
10296   case 's':
10297     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10298     if (Unsigned)
10299       Type = Context.UnsignedShortTy;
10300     else
10301       Type = Context.ShortTy;
10302     break;
10303   case 'i':
10304     if (HowLong == 3)
10305       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10306     else if (HowLong == 2)
10307       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10308     else if (HowLong == 1)
10309       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10310     else
10311       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10312     break;
10313   case 'c':
10314     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10315     if (Signed)
10316       Type = Context.SignedCharTy;
10317     else if (Unsigned)
10318       Type = Context.UnsignedCharTy;
10319     else
10320       Type = Context.CharTy;
10321     break;
10322   case 'b': // boolean
10323     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10324     Type = Context.BoolTy;
10325     break;
10326   case 'z':  // size_t.
10327     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10328     Type = Context.getSizeType();
10329     break;
10330   case 'w':  // wchar_t.
10331     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
10332     Type = Context.getWideCharType();
10333     break;
10334   case 'F':
10335     Type = Context.getCFConstantStringType();
10336     break;
10337   case 'G':
10338     Type = Context.getObjCIdType();
10339     break;
10340   case 'H':
10341     Type = Context.getObjCSelType();
10342     break;
10343   case 'M':
10344     Type = Context.getObjCSuperType();
10345     break;
10346   case 'a':
10347     Type = Context.getBuiltinVaListType();
10348     assert(!Type.isNull() && "builtin va list type not initialized!");
10349     break;
10350   case 'A':
10351     // This is a "reference" to a va_list; however, what exactly
10352     // this means depends on how va_list is defined. There are two
10353     // different kinds of va_list: ones passed by value, and ones
10354     // passed by reference.  An example of a by-value va_list is
10355     // x86, where va_list is a char*. An example of by-ref va_list
10356     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10357     // we want this argument to be a char*&; for x86-64, we want
10358     // it to be a __va_list_tag*.
10359     Type = Context.getBuiltinVaListType();
10360     assert(!Type.isNull() && "builtin va list type not initialized!");
10361     if (Type->isArrayType())
10362       Type = Context.getArrayDecayedType(Type);
10363     else
10364       Type = Context.getLValueReferenceType(Type);
10365     break;
10366   case 'q': {
10367     char *End;
10368     unsigned NumElements = strtoul(Str, &End, 10);
10369     assert(End != Str && "Missing vector size");
10370     Str = End;
10371 
10372     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10373                                              RequiresICE, false);
10374     assert(!RequiresICE && "Can't require vector ICE");
10375 
10376     Type = Context.getScalableVectorType(ElementType, NumElements);
10377     break;
10378   }
10379   case 'V': {
10380     char *End;
10381     unsigned NumElements = strtoul(Str, &End, 10);
10382     assert(End != Str && "Missing vector size");
10383     Str = End;
10384 
10385     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10386                                              RequiresICE, false);
10387     assert(!RequiresICE && "Can't require vector ICE");
10388 
10389     // TODO: No way to make AltiVec vectors in builtins yet.
10390     Type = Context.getVectorType(ElementType, NumElements,
10391                                  VectorType::GenericVector);
10392     break;
10393   }
10394   case 'E': {
10395     char *End;
10396 
10397     unsigned NumElements = strtoul(Str, &End, 10);
10398     assert(End != Str && "Missing vector size");
10399 
10400     Str = End;
10401 
10402     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10403                                              false);
10404     Type = Context.getExtVectorType(ElementType, NumElements);
10405     break;
10406   }
10407   case 'X': {
10408     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10409                                              false);
10410     assert(!RequiresICE && "Can't require complex ICE");
10411     Type = Context.getComplexType(ElementType);
10412     break;
10413   }
10414   case 'Y':
10415     Type = Context.getPointerDiffType();
10416     break;
10417   case 'P':
10418     Type = Context.getFILEType();
10419     if (Type.isNull()) {
10420       Error = ASTContext::GE_Missing_stdio;
10421       return {};
10422     }
10423     break;
10424   case 'J':
10425     if (Signed)
10426       Type = Context.getsigjmp_bufType();
10427     else
10428       Type = Context.getjmp_bufType();
10429 
10430     if (Type.isNull()) {
10431       Error = ASTContext::GE_Missing_setjmp;
10432       return {};
10433     }
10434     break;
10435   case 'K':
10436     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10437     Type = Context.getucontext_tType();
10438 
10439     if (Type.isNull()) {
10440       Error = ASTContext::GE_Missing_ucontext;
10441       return {};
10442     }
10443     break;
10444   case 'p':
10445     Type = Context.getProcessIDType();
10446     break;
10447   }
10448 
10449   // If there are modifiers and if we're allowed to parse them, go for it.
10450   Done = !AllowTypeModifiers;
10451   while (!Done) {
10452     switch (char c = *Str++) {
10453     default: Done = true; --Str; break;
10454     case '*':
10455     case '&': {
10456       // Both pointers and references can have their pointee types
10457       // qualified with an address space.
10458       char *End;
10459       unsigned AddrSpace = strtoul(Str, &End, 10);
10460       if (End != Str) {
10461         // Note AddrSpace == 0 is not the same as an unspecified address space.
10462         Type = Context.getAddrSpaceQualType(
10463           Type,
10464           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10465         Str = End;
10466       }
10467       if (c == '*')
10468         Type = Context.getPointerType(Type);
10469       else
10470         Type = Context.getLValueReferenceType(Type);
10471       break;
10472     }
10473     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10474     case 'C':
10475       Type = Type.withConst();
10476       break;
10477     case 'D':
10478       Type = Context.getVolatileType(Type);
10479       break;
10480     case 'R':
10481       Type = Type.withRestrict();
10482       break;
10483     }
10484   }
10485 
10486   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10487          "Integer constant 'I' type must be an integer");
10488 
10489   return Type;
10490 }
10491 
10492 // On some targets such as PowerPC, some of the builtins are defined with custom
10493 // type decriptors for target-dependent types. These descriptors are decoded in
10494 // other functions, but it may be useful to be able to fall back to default
10495 // descriptor decoding to define builtins mixing target-dependent and target-
10496 // independent types. This function allows decoding one type descriptor with
10497 // default decoding.
10498 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
10499                                    GetBuiltinTypeError &Error, bool &RequireICE,
10500                                    bool AllowTypeModifiers) const {
10501   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
10502 }
10503 
10504 /// GetBuiltinType - Return the type for the specified builtin.
10505 QualType ASTContext::GetBuiltinType(unsigned Id,
10506                                     GetBuiltinTypeError &Error,
10507                                     unsigned *IntegerConstantArgs) const {
10508   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10509   if (TypeStr[0] == '\0') {
10510     Error = GE_Missing_type;
10511     return {};
10512   }
10513 
10514   SmallVector<QualType, 8> ArgTypes;
10515 
10516   bool RequiresICE = false;
10517   Error = GE_None;
10518   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10519                                        RequiresICE, true);
10520   if (Error != GE_None)
10521     return {};
10522 
10523   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10524 
10525   while (TypeStr[0] && TypeStr[0] != '.') {
10526     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10527     if (Error != GE_None)
10528       return {};
10529 
10530     // If this argument is required to be an IntegerConstantExpression and the
10531     // caller cares, fill in the bitmask we return.
10532     if (RequiresICE && IntegerConstantArgs)
10533       *IntegerConstantArgs |= 1 << ArgTypes.size();
10534 
10535     // Do array -> pointer decay.  The builtin should use the decayed type.
10536     if (Ty->isArrayType())
10537       Ty = getArrayDecayedType(Ty);
10538 
10539     ArgTypes.push_back(Ty);
10540   }
10541 
10542   if (Id == Builtin::BI__GetExceptionInfo)
10543     return {};
10544 
10545   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10546          "'.' should only occur at end of builtin type list!");
10547 
10548   bool Variadic = (TypeStr[0] == '.');
10549 
10550   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10551       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10552   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10553 
10554 
10555   // We really shouldn't be making a no-proto type here.
10556   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10557     return getFunctionNoProtoType(ResType, EI);
10558 
10559   FunctionProtoType::ExtProtoInfo EPI;
10560   EPI.ExtInfo = EI;
10561   EPI.Variadic = Variadic;
10562   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10563     EPI.ExceptionSpec.Type =
10564         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10565 
10566   return getFunctionType(ResType, ArgTypes, EPI);
10567 }
10568 
10569 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10570                                              const FunctionDecl *FD) {
10571   if (!FD->isExternallyVisible())
10572     return GVA_Internal;
10573 
10574   // Non-user-provided functions get emitted as weak definitions with every
10575   // use, no matter whether they've been explicitly instantiated etc.
10576   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10577     if (!MD->isUserProvided())
10578       return GVA_DiscardableODR;
10579 
10580   GVALinkage External;
10581   switch (FD->getTemplateSpecializationKind()) {
10582   case TSK_Undeclared:
10583   case TSK_ExplicitSpecialization:
10584     External = GVA_StrongExternal;
10585     break;
10586 
10587   case TSK_ExplicitInstantiationDefinition:
10588     return GVA_StrongODR;
10589 
10590   // C++11 [temp.explicit]p10:
10591   //   [ Note: The intent is that an inline function that is the subject of
10592   //   an explicit instantiation declaration will still be implicitly
10593   //   instantiated when used so that the body can be considered for
10594   //   inlining, but that no out-of-line copy of the inline function would be
10595   //   generated in the translation unit. -- end note ]
10596   case TSK_ExplicitInstantiationDeclaration:
10597     return GVA_AvailableExternally;
10598 
10599   case TSK_ImplicitInstantiation:
10600     External = GVA_DiscardableODR;
10601     break;
10602   }
10603 
10604   if (!FD->isInlined())
10605     return External;
10606 
10607   if ((!Context.getLangOpts().CPlusPlus &&
10608        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10609        !FD->hasAttr<DLLExportAttr>()) ||
10610       FD->hasAttr<GNUInlineAttr>()) {
10611     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10612 
10613     // GNU or C99 inline semantics. Determine whether this symbol should be
10614     // externally visible.
10615     if (FD->isInlineDefinitionExternallyVisible())
10616       return External;
10617 
10618     // C99 inline semantics, where the symbol is not externally visible.
10619     return GVA_AvailableExternally;
10620   }
10621 
10622   // Functions specified with extern and inline in -fms-compatibility mode
10623   // forcibly get emitted.  While the body of the function cannot be later
10624   // replaced, the function definition cannot be discarded.
10625   if (FD->isMSExternInline())
10626     return GVA_StrongODR;
10627 
10628   return GVA_DiscardableODR;
10629 }
10630 
10631 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10632                                                 const Decl *D, GVALinkage L) {
10633   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10634   // dllexport/dllimport on inline functions.
10635   if (D->hasAttr<DLLImportAttr>()) {
10636     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10637       return GVA_AvailableExternally;
10638   } else if (D->hasAttr<DLLExportAttr>()) {
10639     if (L == GVA_DiscardableODR)
10640       return GVA_StrongODR;
10641   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
10642     // Device-side functions with __global__ attribute must always be
10643     // visible externally so they can be launched from host.
10644     if (D->hasAttr<CUDAGlobalAttr>() &&
10645         (L == GVA_DiscardableODR || L == GVA_Internal))
10646       return GVA_StrongODR;
10647     // Single source offloading languages like CUDA/HIP need to be able to
10648     // access static device variables from host code of the same compilation
10649     // unit. This is done by externalizing the static variable with a shared
10650     // name between the host and device compilation which is the same for the
10651     // same compilation unit whereas different among different compilation
10652     // units.
10653     if (Context.shouldExternalizeStaticVar(D))
10654       return GVA_StrongExternal;
10655   }
10656   return L;
10657 }
10658 
10659 /// Adjust the GVALinkage for a declaration based on what an external AST source
10660 /// knows about whether there can be other definitions of this declaration.
10661 static GVALinkage
10662 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10663                                           GVALinkage L) {
10664   ExternalASTSource *Source = Ctx.getExternalSource();
10665   if (!Source)
10666     return L;
10667 
10668   switch (Source->hasExternalDefinitions(D)) {
10669   case ExternalASTSource::EK_Never:
10670     // Other translation units rely on us to provide the definition.
10671     if (L == GVA_DiscardableODR)
10672       return GVA_StrongODR;
10673     break;
10674 
10675   case ExternalASTSource::EK_Always:
10676     return GVA_AvailableExternally;
10677 
10678   case ExternalASTSource::EK_ReplyHazy:
10679     break;
10680   }
10681   return L;
10682 }
10683 
10684 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10685   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10686            adjustGVALinkageForAttributes(*this, FD,
10687              basicGVALinkageForFunction(*this, FD)));
10688 }
10689 
10690 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10691                                              const VarDecl *VD) {
10692   if (!VD->isExternallyVisible())
10693     return GVA_Internal;
10694 
10695   if (VD->isStaticLocal()) {
10696     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10697     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10698       LexicalContext = LexicalContext->getLexicalParent();
10699 
10700     // ObjC Blocks can create local variables that don't have a FunctionDecl
10701     // LexicalContext.
10702     if (!LexicalContext)
10703       return GVA_DiscardableODR;
10704 
10705     // Otherwise, let the static local variable inherit its linkage from the
10706     // nearest enclosing function.
10707     auto StaticLocalLinkage =
10708         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10709 
10710     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10711     // be emitted in any object with references to the symbol for the object it
10712     // contains, whether inline or out-of-line."
10713     // Similar behavior is observed with MSVC. An alternative ABI could use
10714     // StrongODR/AvailableExternally to match the function, but none are
10715     // known/supported currently.
10716     if (StaticLocalLinkage == GVA_StrongODR ||
10717         StaticLocalLinkage == GVA_AvailableExternally)
10718       return GVA_DiscardableODR;
10719     return StaticLocalLinkage;
10720   }
10721 
10722   // MSVC treats in-class initialized static data members as definitions.
10723   // By giving them non-strong linkage, out-of-line definitions won't
10724   // cause link errors.
10725   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10726     return GVA_DiscardableODR;
10727 
10728   // Most non-template variables have strong linkage; inline variables are
10729   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10730   GVALinkage StrongLinkage;
10731   switch (Context.getInlineVariableDefinitionKind(VD)) {
10732   case ASTContext::InlineVariableDefinitionKind::None:
10733     StrongLinkage = GVA_StrongExternal;
10734     break;
10735   case ASTContext::InlineVariableDefinitionKind::Weak:
10736   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10737     StrongLinkage = GVA_DiscardableODR;
10738     break;
10739   case ASTContext::InlineVariableDefinitionKind::Strong:
10740     StrongLinkage = GVA_StrongODR;
10741     break;
10742   }
10743 
10744   switch (VD->getTemplateSpecializationKind()) {
10745   case TSK_Undeclared:
10746     return StrongLinkage;
10747 
10748   case TSK_ExplicitSpecialization:
10749     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10750                    VD->isStaticDataMember()
10751                ? GVA_StrongODR
10752                : StrongLinkage;
10753 
10754   case TSK_ExplicitInstantiationDefinition:
10755     return GVA_StrongODR;
10756 
10757   case TSK_ExplicitInstantiationDeclaration:
10758     return GVA_AvailableExternally;
10759 
10760   case TSK_ImplicitInstantiation:
10761     return GVA_DiscardableODR;
10762   }
10763 
10764   llvm_unreachable("Invalid Linkage!");
10765 }
10766 
10767 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10768   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10769            adjustGVALinkageForAttributes(*this, VD,
10770              basicGVALinkageForVariable(*this, VD)));
10771 }
10772 
10773 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10774   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10775     if (!VD->isFileVarDecl())
10776       return false;
10777     // Global named register variables (GNU extension) are never emitted.
10778     if (VD->getStorageClass() == SC_Register)
10779       return false;
10780     if (VD->getDescribedVarTemplate() ||
10781         isa<VarTemplatePartialSpecializationDecl>(VD))
10782       return false;
10783   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10784     // We never need to emit an uninstantiated function template.
10785     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10786       return false;
10787   } else if (isa<PragmaCommentDecl>(D))
10788     return true;
10789   else if (isa<PragmaDetectMismatchDecl>(D))
10790     return true;
10791   else if (isa<OMPRequiresDecl>(D))
10792     return true;
10793   else if (isa<OMPThreadPrivateDecl>(D))
10794     return !D->getDeclContext()->isDependentContext();
10795   else if (isa<OMPAllocateDecl>(D))
10796     return !D->getDeclContext()->isDependentContext();
10797   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10798     return !D->getDeclContext()->isDependentContext();
10799   else if (isa<ImportDecl>(D))
10800     return true;
10801   else
10802     return false;
10803 
10804   // If this is a member of a class template, we do not need to emit it.
10805   if (D->getDeclContext()->isDependentContext())
10806     return false;
10807 
10808   // Weak references don't produce any output by themselves.
10809   if (D->hasAttr<WeakRefAttr>())
10810     return false;
10811 
10812   // Aliases and used decls are required.
10813   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10814     return true;
10815 
10816   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10817     // Forward declarations aren't required.
10818     if (!FD->doesThisDeclarationHaveABody())
10819       return FD->doesDeclarationForceExternallyVisibleDefinition();
10820 
10821     // Constructors and destructors are required.
10822     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10823       return true;
10824 
10825     // The key function for a class is required.  This rule only comes
10826     // into play when inline functions can be key functions, though.
10827     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10828       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10829         const CXXRecordDecl *RD = MD->getParent();
10830         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10831           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10832           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10833             return true;
10834         }
10835       }
10836     }
10837 
10838     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10839 
10840     // static, static inline, always_inline, and extern inline functions can
10841     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10842     // Implicit template instantiations can also be deferred in C++.
10843     return !isDiscardableGVALinkage(Linkage);
10844   }
10845 
10846   const auto *VD = cast<VarDecl>(D);
10847   assert(VD->isFileVarDecl() && "Expected file scoped var");
10848 
10849   // If the decl is marked as `declare target to`, it should be emitted for the
10850   // host and for the device.
10851   if (LangOpts.OpenMP &&
10852       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10853     return true;
10854 
10855   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10856       !isMSStaticDataMemberInlineDefinition(VD))
10857     return false;
10858 
10859   // Variables that can be needed in other TUs are required.
10860   auto Linkage = GetGVALinkageForVariable(VD);
10861   if (!isDiscardableGVALinkage(Linkage))
10862     return true;
10863 
10864   // We never need to emit a variable that is available in another TU.
10865   if (Linkage == GVA_AvailableExternally)
10866     return false;
10867 
10868   // Variables that have destruction with side-effects are required.
10869   if (VD->needsDestruction(*this))
10870     return true;
10871 
10872   // Variables that have initialization with side-effects are required.
10873   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10874       // We can get a value-dependent initializer during error recovery.
10875       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10876     return true;
10877 
10878   // Likewise, variables with tuple-like bindings are required if their
10879   // bindings have side-effects.
10880   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10881     for (const auto *BD : DD->bindings())
10882       if (const auto *BindingVD = BD->getHoldingVar())
10883         if (DeclMustBeEmitted(BindingVD))
10884           return true;
10885 
10886   return false;
10887 }
10888 
10889 void ASTContext::forEachMultiversionedFunctionVersion(
10890     const FunctionDecl *FD,
10891     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10892   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10893   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10894   FD = FD->getMostRecentDecl();
10895   for (auto *CurDecl :
10896        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10897     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10898     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10899         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10900       SeenDecls.insert(CurFD);
10901       Pred(CurFD);
10902     }
10903   }
10904 }
10905 
10906 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10907                                                     bool IsCXXMethod,
10908                                                     bool IsBuiltin) const {
10909   // Pass through to the C++ ABI object
10910   if (IsCXXMethod)
10911     return ABI->getDefaultMethodCallConv(IsVariadic);
10912 
10913   // Builtins ignore user-specified default calling convention and remain the
10914   // Target's default calling convention.
10915   if (!IsBuiltin) {
10916     switch (LangOpts.getDefaultCallingConv()) {
10917     case LangOptions::DCC_None:
10918       break;
10919     case LangOptions::DCC_CDecl:
10920       return CC_C;
10921     case LangOptions::DCC_FastCall:
10922       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10923         return CC_X86FastCall;
10924       break;
10925     case LangOptions::DCC_StdCall:
10926       if (!IsVariadic)
10927         return CC_X86StdCall;
10928       break;
10929     case LangOptions::DCC_VectorCall:
10930       // __vectorcall cannot be applied to variadic functions.
10931       if (!IsVariadic)
10932         return CC_X86VectorCall;
10933       break;
10934     case LangOptions::DCC_RegCall:
10935       // __regcall cannot be applied to variadic functions.
10936       if (!IsVariadic)
10937         return CC_X86RegCall;
10938       break;
10939     }
10940   }
10941   return Target->getDefaultCallingConv();
10942 }
10943 
10944 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10945   // Pass through to the C++ ABI object
10946   return ABI->isNearlyEmpty(RD);
10947 }
10948 
10949 VTableContextBase *ASTContext::getVTableContext() {
10950   if (!VTContext.get()) {
10951     auto ABI = Target->getCXXABI();
10952     if (ABI.isMicrosoft())
10953       VTContext.reset(new MicrosoftVTableContext(*this));
10954     else {
10955       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10956                                  ? ItaniumVTableContext::Relative
10957                                  : ItaniumVTableContext::Pointer;
10958       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10959     }
10960   }
10961   return VTContext.get();
10962 }
10963 
10964 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10965   if (!T)
10966     T = Target;
10967   switch (T->getCXXABI().getKind()) {
10968   case TargetCXXABI::AppleARM64:
10969   case TargetCXXABI::Fuchsia:
10970   case TargetCXXABI::GenericAArch64:
10971   case TargetCXXABI::GenericItanium:
10972   case TargetCXXABI::GenericARM:
10973   case TargetCXXABI::GenericMIPS:
10974   case TargetCXXABI::iOS:
10975   case TargetCXXABI::WebAssembly:
10976   case TargetCXXABI::WatchOS:
10977   case TargetCXXABI::XL:
10978     return ItaniumMangleContext::create(*this, getDiagnostics());
10979   case TargetCXXABI::Microsoft:
10980     return MicrosoftMangleContext::create(*this, getDiagnostics());
10981   }
10982   llvm_unreachable("Unsupported ABI");
10983 }
10984 
10985 CXXABI::~CXXABI() = default;
10986 
10987 size_t ASTContext::getSideTableAllocatedMemory() const {
10988   return ASTRecordLayouts.getMemorySize() +
10989          llvm::capacity_in_bytes(ObjCLayouts) +
10990          llvm::capacity_in_bytes(KeyFunctions) +
10991          llvm::capacity_in_bytes(ObjCImpls) +
10992          llvm::capacity_in_bytes(BlockVarCopyInits) +
10993          llvm::capacity_in_bytes(DeclAttrs) +
10994          llvm::capacity_in_bytes(TemplateOrInstantiation) +
10995          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10996          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10997          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10998          llvm::capacity_in_bytes(OverriddenMethods) +
10999          llvm::capacity_in_bytes(Types) +
11000          llvm::capacity_in_bytes(VariableArrayTypes);
11001 }
11002 
11003 /// getIntTypeForBitwidth -
11004 /// sets integer QualTy according to specified details:
11005 /// bitwidth, signed/unsigned.
11006 /// Returns empty type if there is no appropriate target types.
11007 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11008                                            unsigned Signed) const {
11009   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11010   CanQualType QualTy = getFromTargetType(Ty);
11011   if (!QualTy && DestWidth == 128)
11012     return Signed ? Int128Ty : UnsignedInt128Ty;
11013   return QualTy;
11014 }
11015 
11016 /// getRealTypeForBitwidth -
11017 /// sets floating point QualTy according to specified bitwidth.
11018 /// Returns empty type if there is no appropriate target types.
11019 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11020                                             bool ExplicitIEEE) const {
11021   TargetInfo::RealType Ty =
11022       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
11023   switch (Ty) {
11024   case TargetInfo::Float:
11025     return FloatTy;
11026   case TargetInfo::Double:
11027     return DoubleTy;
11028   case TargetInfo::LongDouble:
11029     return LongDoubleTy;
11030   case TargetInfo::Float128:
11031     return Float128Ty;
11032   case TargetInfo::NoFloat:
11033     return {};
11034   }
11035 
11036   llvm_unreachable("Unhandled TargetInfo::RealType value");
11037 }
11038 
11039 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11040   if (Number > 1)
11041     MangleNumbers[ND] = Number;
11042 }
11043 
11044 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11045   auto I = MangleNumbers.find(ND);
11046   return I != MangleNumbers.end() ? I->second : 1;
11047 }
11048 
11049 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11050   if (Number > 1)
11051     StaticLocalNumbers[VD] = Number;
11052 }
11053 
11054 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11055   auto I = StaticLocalNumbers.find(VD);
11056   return I != StaticLocalNumbers.end() ? I->second : 1;
11057 }
11058 
11059 MangleNumberingContext &
11060 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11061   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11062   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11063   if (!MCtx)
11064     MCtx = createMangleNumberingContext();
11065   return *MCtx;
11066 }
11067 
11068 MangleNumberingContext &
11069 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11070   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11071   std::unique_ptr<MangleNumberingContext> &MCtx =
11072       ExtraMangleNumberingContexts[D];
11073   if (!MCtx)
11074     MCtx = createMangleNumberingContext();
11075   return *MCtx;
11076 }
11077 
11078 std::unique_ptr<MangleNumberingContext>
11079 ASTContext::createMangleNumberingContext() const {
11080   return ABI->createMangleNumberingContext();
11081 }
11082 
11083 const CXXConstructorDecl *
11084 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11085   return ABI->getCopyConstructorForExceptionObject(
11086       cast<CXXRecordDecl>(RD->getFirstDecl()));
11087 }
11088 
11089 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11090                                                       CXXConstructorDecl *CD) {
11091   return ABI->addCopyConstructorForExceptionObject(
11092       cast<CXXRecordDecl>(RD->getFirstDecl()),
11093       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11094 }
11095 
11096 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11097                                                  TypedefNameDecl *DD) {
11098   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11099 }
11100 
11101 TypedefNameDecl *
11102 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11103   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11104 }
11105 
11106 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11107                                                 DeclaratorDecl *DD) {
11108   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11109 }
11110 
11111 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11112   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11113 }
11114 
11115 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11116   ParamIndices[D] = index;
11117 }
11118 
11119 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11120   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11121   assert(I != ParamIndices.end() &&
11122          "ParmIndices lacks entry set by ParmVarDecl");
11123   return I->second;
11124 }
11125 
11126 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11127                                                unsigned Length) const {
11128   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11129   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11130     EltTy = EltTy.withConst();
11131 
11132   EltTy = adjustStringLiteralBaseType(EltTy);
11133 
11134   // Get an array type for the string, according to C99 6.4.5. This includes
11135   // the null terminator character.
11136   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11137                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11138 }
11139 
11140 StringLiteral *
11141 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11142   StringLiteral *&Result = StringLiteralCache[Key];
11143   if (!Result)
11144     Result = StringLiteral::Create(
11145         *this, Key, StringLiteral::Ascii,
11146         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11147         SourceLocation());
11148   return Result;
11149 }
11150 
11151 MSGuidDecl *
11152 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11153   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11154 
11155   llvm::FoldingSetNodeID ID;
11156   MSGuidDecl::Profile(ID, Parts);
11157 
11158   void *InsertPos;
11159   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11160     return Existing;
11161 
11162   QualType GUIDType = getMSGuidType().withConst();
11163   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11164   MSGuidDecls.InsertNode(New, InsertPos);
11165   return New;
11166 }
11167 
11168 TemplateParamObjectDecl *
11169 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11170   assert(T->isRecordType() && "template param object of unexpected type");
11171 
11172   // C++ [temp.param]p8:
11173   //   [...] a static storage duration object of type 'const T' [...]
11174   T.addConst();
11175 
11176   llvm::FoldingSetNodeID ID;
11177   TemplateParamObjectDecl::Profile(ID, T, V);
11178 
11179   void *InsertPos;
11180   if (TemplateParamObjectDecl *Existing =
11181           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11182     return Existing;
11183 
11184   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11185   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11186   return New;
11187 }
11188 
11189 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11190   const llvm::Triple &T = getTargetInfo().getTriple();
11191   if (!T.isOSDarwin())
11192     return false;
11193 
11194   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11195       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11196     return false;
11197 
11198   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11199   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11200   uint64_t Size = sizeChars.getQuantity();
11201   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11202   unsigned Align = alignChars.getQuantity();
11203   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11204   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11205 }
11206 
11207 bool
11208 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11209                                 const ObjCMethodDecl *MethodImpl) {
11210   // No point trying to match an unavailable/deprecated mothod.
11211   if (MethodDecl->hasAttr<UnavailableAttr>()
11212       || MethodDecl->hasAttr<DeprecatedAttr>())
11213     return false;
11214   if (MethodDecl->getObjCDeclQualifier() !=
11215       MethodImpl->getObjCDeclQualifier())
11216     return false;
11217   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11218     return false;
11219 
11220   if (MethodDecl->param_size() != MethodImpl->param_size())
11221     return false;
11222 
11223   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11224        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11225        EF = MethodDecl->param_end();
11226        IM != EM && IF != EF; ++IM, ++IF) {
11227     const ParmVarDecl *DeclVar = (*IF);
11228     const ParmVarDecl *ImplVar = (*IM);
11229     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11230       return false;
11231     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11232       return false;
11233   }
11234 
11235   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11236 }
11237 
11238 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11239   LangAS AS;
11240   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11241     AS = LangAS::Default;
11242   else
11243     AS = QT->getPointeeType().getAddressSpace();
11244 
11245   return getTargetInfo().getNullPointerValue(AS);
11246 }
11247 
11248 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11249   if (isTargetAddressSpace(AS))
11250     return toTargetAddressSpace(AS);
11251   else
11252     return (*AddrSpaceMap)[(unsigned)AS];
11253 }
11254 
11255 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11256   assert(Ty->isFixedPointType());
11257 
11258   if (Ty->isSaturatedFixedPointType()) return Ty;
11259 
11260   switch (Ty->castAs<BuiltinType>()->getKind()) {
11261     default:
11262       llvm_unreachable("Not a fixed point type!");
11263     case BuiltinType::ShortAccum:
11264       return SatShortAccumTy;
11265     case BuiltinType::Accum:
11266       return SatAccumTy;
11267     case BuiltinType::LongAccum:
11268       return SatLongAccumTy;
11269     case BuiltinType::UShortAccum:
11270       return SatUnsignedShortAccumTy;
11271     case BuiltinType::UAccum:
11272       return SatUnsignedAccumTy;
11273     case BuiltinType::ULongAccum:
11274       return SatUnsignedLongAccumTy;
11275     case BuiltinType::ShortFract:
11276       return SatShortFractTy;
11277     case BuiltinType::Fract:
11278       return SatFractTy;
11279     case BuiltinType::LongFract:
11280       return SatLongFractTy;
11281     case BuiltinType::UShortFract:
11282       return SatUnsignedShortFractTy;
11283     case BuiltinType::UFract:
11284       return SatUnsignedFractTy;
11285     case BuiltinType::ULongFract:
11286       return SatUnsignedLongFractTy;
11287   }
11288 }
11289 
11290 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
11291   if (LangOpts.OpenCL)
11292     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
11293 
11294   if (LangOpts.CUDA)
11295     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
11296 
11297   return getLangASFromTargetAS(AS);
11298 }
11299 
11300 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
11301 // doesn't include ASTContext.h
11302 template
11303 clang::LazyGenerationalUpdatePtr<
11304     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
11305 clang::LazyGenerationalUpdatePtr<
11306     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
11307         const clang::ASTContext &Ctx, Decl *Value);
11308 
11309 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
11310   assert(Ty->isFixedPointType());
11311 
11312   const TargetInfo &Target = getTargetInfo();
11313   switch (Ty->castAs<BuiltinType>()->getKind()) {
11314     default:
11315       llvm_unreachable("Not a fixed point type!");
11316     case BuiltinType::ShortAccum:
11317     case BuiltinType::SatShortAccum:
11318       return Target.getShortAccumScale();
11319     case BuiltinType::Accum:
11320     case BuiltinType::SatAccum:
11321       return Target.getAccumScale();
11322     case BuiltinType::LongAccum:
11323     case BuiltinType::SatLongAccum:
11324       return Target.getLongAccumScale();
11325     case BuiltinType::UShortAccum:
11326     case BuiltinType::SatUShortAccum:
11327       return Target.getUnsignedShortAccumScale();
11328     case BuiltinType::UAccum:
11329     case BuiltinType::SatUAccum:
11330       return Target.getUnsignedAccumScale();
11331     case BuiltinType::ULongAccum:
11332     case BuiltinType::SatULongAccum:
11333       return Target.getUnsignedLongAccumScale();
11334     case BuiltinType::ShortFract:
11335     case BuiltinType::SatShortFract:
11336       return Target.getShortFractScale();
11337     case BuiltinType::Fract:
11338     case BuiltinType::SatFract:
11339       return Target.getFractScale();
11340     case BuiltinType::LongFract:
11341     case BuiltinType::SatLongFract:
11342       return Target.getLongFractScale();
11343     case BuiltinType::UShortFract:
11344     case BuiltinType::SatUShortFract:
11345       return Target.getUnsignedShortFractScale();
11346     case BuiltinType::UFract:
11347     case BuiltinType::SatUFract:
11348       return Target.getUnsignedFractScale();
11349     case BuiltinType::ULongFract:
11350     case BuiltinType::SatULongFract:
11351       return Target.getUnsignedLongFractScale();
11352   }
11353 }
11354 
11355 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
11356   assert(Ty->isFixedPointType());
11357 
11358   const TargetInfo &Target = getTargetInfo();
11359   switch (Ty->castAs<BuiltinType>()->getKind()) {
11360     default:
11361       llvm_unreachable("Not a fixed point type!");
11362     case BuiltinType::ShortAccum:
11363     case BuiltinType::SatShortAccum:
11364       return Target.getShortAccumIBits();
11365     case BuiltinType::Accum:
11366     case BuiltinType::SatAccum:
11367       return Target.getAccumIBits();
11368     case BuiltinType::LongAccum:
11369     case BuiltinType::SatLongAccum:
11370       return Target.getLongAccumIBits();
11371     case BuiltinType::UShortAccum:
11372     case BuiltinType::SatUShortAccum:
11373       return Target.getUnsignedShortAccumIBits();
11374     case BuiltinType::UAccum:
11375     case BuiltinType::SatUAccum:
11376       return Target.getUnsignedAccumIBits();
11377     case BuiltinType::ULongAccum:
11378     case BuiltinType::SatULongAccum:
11379       return Target.getUnsignedLongAccumIBits();
11380     case BuiltinType::ShortFract:
11381     case BuiltinType::SatShortFract:
11382     case BuiltinType::Fract:
11383     case BuiltinType::SatFract:
11384     case BuiltinType::LongFract:
11385     case BuiltinType::SatLongFract:
11386     case BuiltinType::UShortFract:
11387     case BuiltinType::SatUShortFract:
11388     case BuiltinType::UFract:
11389     case BuiltinType::SatUFract:
11390     case BuiltinType::ULongFract:
11391     case BuiltinType::SatULongFract:
11392       return 0;
11393   }
11394 }
11395 
11396 llvm::FixedPointSemantics
11397 ASTContext::getFixedPointSemantics(QualType Ty) const {
11398   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11399          "Can only get the fixed point semantics for a "
11400          "fixed point or integer type.");
11401   if (Ty->isIntegerType())
11402     return llvm::FixedPointSemantics::GetIntegerSemantics(
11403         getIntWidth(Ty), Ty->isSignedIntegerType());
11404 
11405   bool isSigned = Ty->isSignedFixedPointType();
11406   return llvm::FixedPointSemantics(
11407       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11408       Ty->isSaturatedFixedPointType(),
11409       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11410 }
11411 
11412 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11413   assert(Ty->isFixedPointType());
11414   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
11415 }
11416 
11417 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11418   assert(Ty->isFixedPointType());
11419   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
11420 }
11421 
11422 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11423   assert(Ty->isUnsignedFixedPointType() &&
11424          "Expected unsigned fixed point type");
11425 
11426   switch (Ty->castAs<BuiltinType>()->getKind()) {
11427   case BuiltinType::UShortAccum:
11428     return ShortAccumTy;
11429   case BuiltinType::UAccum:
11430     return AccumTy;
11431   case BuiltinType::ULongAccum:
11432     return LongAccumTy;
11433   case BuiltinType::SatUShortAccum:
11434     return SatShortAccumTy;
11435   case BuiltinType::SatUAccum:
11436     return SatAccumTy;
11437   case BuiltinType::SatULongAccum:
11438     return SatLongAccumTy;
11439   case BuiltinType::UShortFract:
11440     return ShortFractTy;
11441   case BuiltinType::UFract:
11442     return FractTy;
11443   case BuiltinType::ULongFract:
11444     return LongFractTy;
11445   case BuiltinType::SatUShortFract:
11446     return SatShortFractTy;
11447   case BuiltinType::SatUFract:
11448     return SatFractTy;
11449   case BuiltinType::SatULongFract:
11450     return SatLongFractTy;
11451   default:
11452     llvm_unreachable("Unexpected unsigned fixed point type");
11453   }
11454 }
11455 
11456 ParsedTargetAttr
11457 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11458   assert(TD != nullptr);
11459   ParsedTargetAttr ParsedAttr = TD->parse();
11460 
11461   ParsedAttr.Features.erase(
11462       llvm::remove_if(ParsedAttr.Features,
11463                       [&](const std::string &Feat) {
11464                         return !Target->isValidFeatureName(
11465                             StringRef{Feat}.substr(1));
11466                       }),
11467       ParsedAttr.Features.end());
11468   return ParsedAttr;
11469 }
11470 
11471 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11472                                        const FunctionDecl *FD) const {
11473   if (FD)
11474     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11475   else
11476     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11477                            Target->getTargetOpts().CPU,
11478                            Target->getTargetOpts().Features);
11479 }
11480 
11481 // Fills in the supplied string map with the set of target features for the
11482 // passed in function.
11483 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11484                                        GlobalDecl GD) const {
11485   StringRef TargetCPU = Target->getTargetOpts().CPU;
11486   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11487   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11488     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11489 
11490     // Make a copy of the features as passed on the command line into the
11491     // beginning of the additional features from the function to override.
11492     ParsedAttr.Features.insert(
11493         ParsedAttr.Features.begin(),
11494         Target->getTargetOpts().FeaturesAsWritten.begin(),
11495         Target->getTargetOpts().FeaturesAsWritten.end());
11496 
11497     if (ParsedAttr.Architecture != "" &&
11498         Target->isValidCPUName(ParsedAttr.Architecture))
11499       TargetCPU = ParsedAttr.Architecture;
11500 
11501     // Now populate the feature map, first with the TargetCPU which is either
11502     // the default or a new one from the target attribute string. Then we'll use
11503     // the passed in features (FeaturesAsWritten) along with the new ones from
11504     // the attribute.
11505     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11506                            ParsedAttr.Features);
11507   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11508     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11509     Target->getCPUSpecificCPUDispatchFeatures(
11510         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11511     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11512     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11513   } else {
11514     FeatureMap = Target->getTargetOpts().FeatureMap;
11515   }
11516 }
11517 
11518 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11519   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11520   return *OMPTraitInfoVector.back();
11521 }
11522 
11523 const StreamingDiagnostic &clang::
11524 operator<<(const StreamingDiagnostic &DB,
11525            const ASTContext::SectionInfo &Section) {
11526   if (Section.Decl)
11527     return DB << Section.Decl;
11528   return DB << "a prior #pragma section";
11529 }
11530 
11531 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
11532   bool IsStaticVar =
11533       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
11534   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
11535                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
11536                              (D->hasAttr<CUDAConstantAttr>() &&
11537                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
11538   // CUDA/HIP: static managed variables need to be externalized since it is
11539   // a declaration in IR, therefore cannot have internal linkage.
11540   return IsStaticVar &&
11541          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
11542 }
11543 
11544 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
11545   return mayExternalizeStaticVar(D) &&
11546          (D->hasAttr<HIPManagedAttr>() ||
11547           CUDAStaticDeviceVarReferencedByHost.count(cast<VarDecl>(D)));
11548 }
11549 
11550 StringRef ASTContext::getCUIDHash() const {
11551   if (!CUIDHash.empty())
11552     return CUIDHash;
11553   if (LangOpts.CUID.empty())
11554     return StringRef();
11555   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
11556   return CUIDHash;
11557 }
11558