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