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,
105   Float16Rank,
106   HalfRank,
107   FloatRank,
108   DoubleRank,
109   LongDoubleRank,
110   Float128Rank,
111   Ibm128Rank
112 };
113 
114 /// \returns location that is relevant when searching for Doc comments related
115 /// to \p D.
116 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
117                                                  SourceManager &SourceMgr) {
118   assert(D);
119 
120   // User can not attach documentation to implicit declarations.
121   if (D->isImplicit())
122     return {};
123 
124   // User can not attach documentation to implicit instantiations.
125   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
126     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
127       return {};
128   }
129 
130   if (const auto *VD = dyn_cast<VarDecl>(D)) {
131     if (VD->isStaticDataMember() &&
132         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
133       return {};
134   }
135 
136   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
137     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
138       return {};
139   }
140 
141   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
142     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
143     if (TSK == TSK_ImplicitInstantiation ||
144         TSK == TSK_Undeclared)
145       return {};
146   }
147 
148   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
149     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
150       return {};
151   }
152   if (const auto *TD = dyn_cast<TagDecl>(D)) {
153     // When tag declaration (but not definition!) is part of the
154     // decl-specifier-seq of some other declaration, it doesn't get comment
155     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
156       return {};
157   }
158   // TODO: handle comments for function parameters properly.
159   if (isa<ParmVarDecl>(D))
160     return {};
161 
162   // TODO: we could look up template parameter documentation in the template
163   // documentation.
164   if (isa<TemplateTypeParmDecl>(D) ||
165       isa<NonTypeTemplateParmDecl>(D) ||
166       isa<TemplateTemplateParmDecl>(D))
167     return {};
168 
169   // Find declaration location.
170   // For Objective-C declarations we generally don't expect to have multiple
171   // declarators, thus use declaration starting location as the "declaration
172   // location".
173   // For all other declarations multiple declarators are used quite frequently,
174   // so we use the location of the identifier as the "declaration location".
175   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
176       isa<ObjCPropertyDecl>(D) ||
177       isa<RedeclarableTemplateDecl>(D) ||
178       isa<ClassTemplateSpecializationDecl>(D) ||
179       // Allow association with Y across {} in `typedef struct X {} Y`.
180       isa<TypedefDecl>(D))
181     return D->getBeginLoc();
182 
183   const SourceLocation DeclLoc = D->getLocation();
184   if (DeclLoc.isMacroID()) {
185     if (isa<TypedefDecl>(D)) {
186       // If location of the typedef name is in a macro, it is because being
187       // declared via a macro. Try using declaration's starting location as
188       // the "declaration location".
189       return D->getBeginLoc();
190     }
191 
192     if (const auto *TD = dyn_cast<TagDecl>(D)) {
193       // If location of the tag decl is inside a macro, but the spelling of
194       // the tag name comes from a macro argument, it looks like a special
195       // macro like NS_ENUM is being used to define the tag decl.  In that
196       // case, adjust the source location to the expansion loc so that we can
197       // attach the comment to the tag decl.
198       if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
199         return SourceMgr.getExpansionLoc(DeclLoc);
200     }
201   }
202 
203   return DeclLoc;
204 }
205 
206 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
207     const Decl *D, const SourceLocation RepresentativeLocForDecl,
208     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
209   // If the declaration doesn't map directly to a location in a file, we
210   // can't find the comment.
211   if (RepresentativeLocForDecl.isInvalid() ||
212       !RepresentativeLocForDecl.isFileID())
213     return nullptr;
214 
215   // If there are no comments anywhere, we won't find anything.
216   if (CommentsInTheFile.empty())
217     return nullptr;
218 
219   // Decompose the location for the declaration and find the beginning of the
220   // file buffer.
221   const std::pair<FileID, unsigned> DeclLocDecomp =
222       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
223 
224   // Slow path.
225   auto OffsetCommentBehindDecl =
226       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
227 
228   // First check whether we have a trailing comment.
229   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
230     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
231     if ((CommentBehindDecl->isDocumentation() ||
232          LangOpts.CommentOpts.ParseAllComments) &&
233         CommentBehindDecl->isTrailingComment() &&
234         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
235          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
236 
237       // Check that Doxygen trailing comment comes after the declaration, starts
238       // on the same line and in the same file as the declaration.
239       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
240           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
241                                        OffsetCommentBehindDecl->first)) {
242         return CommentBehindDecl;
243       }
244     }
245   }
246 
247   // The comment just after the declaration was not a trailing comment.
248   // Let's look at the previous comment.
249   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
250     return nullptr;
251 
252   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
253   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
254 
255   // Check that we actually have a non-member Doxygen comment.
256   if (!(CommentBeforeDecl->isDocumentation() ||
257         LangOpts.CommentOpts.ParseAllComments) ||
258       CommentBeforeDecl->isTrailingComment())
259     return nullptr;
260 
261   // Decompose the end of the comment.
262   const unsigned CommentEndOffset =
263       Comments.getCommentEndOffset(CommentBeforeDecl);
264 
265   // Get the corresponding buffer.
266   bool Invalid = false;
267   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
268                                                &Invalid).data();
269   if (Invalid)
270     return nullptr;
271 
272   // Extract text between the comment and declaration.
273   StringRef Text(Buffer + CommentEndOffset,
274                  DeclLocDecomp.second - CommentEndOffset);
275 
276   // There should be no other declarations or preprocessor directives between
277   // comment and declaration.
278   if (Text.find_first_of(";{}#@") != StringRef::npos)
279     return nullptr;
280 
281   return CommentBeforeDecl;
282 }
283 
284 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
285   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
286 
287   // If the declaration doesn't map directly to a location in a file, we
288   // can't find the comment.
289   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
290     return nullptr;
291 
292   if (ExternalSource && !CommentsLoaded) {
293     ExternalSource->ReadComments();
294     CommentsLoaded = true;
295   }
296 
297   if (Comments.empty())
298     return nullptr;
299 
300   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
301   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
302   if (!CommentsInThisFile || CommentsInThisFile->empty())
303     return nullptr;
304 
305   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
306 }
307 
308 void ASTContext::addComment(const RawComment &RC) {
309   assert(LangOpts.RetainCommentsFromSystemHeaders ||
310          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
311   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
312 }
313 
314 /// If we have a 'templated' declaration for a template, adjust 'D' to
315 /// refer to the actual template.
316 /// If we have an implicit instantiation, adjust 'D' to refer to template.
317 static const Decl &adjustDeclToTemplate(const Decl &D) {
318   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
319     // Is this function declaration part of a function template?
320     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
321       return *FTD;
322 
323     // Nothing to do if function is not an implicit instantiation.
324     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
325       return D;
326 
327     // Function is an implicit instantiation of a function template?
328     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
329       return *FTD;
330 
331     // Function is instantiated from a member definition of a class template?
332     if (const FunctionDecl *MemberDecl =
333             FD->getInstantiatedFromMemberFunction())
334       return *MemberDecl;
335 
336     return D;
337   }
338   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
339     // Static data member is instantiated from a member definition of a class
340     // template?
341     if (VD->isStaticDataMember())
342       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
343         return *MemberDecl;
344 
345     return D;
346   }
347   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
348     // Is this class declaration part of a class template?
349     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
350       return *CTD;
351 
352     // Class is an implicit instantiation of a class template or partial
353     // specialization?
354     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
355       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
356         return D;
357       llvm::PointerUnion<ClassTemplateDecl *,
358                          ClassTemplatePartialSpecializationDecl *>
359           PU = CTSD->getSpecializedTemplateOrPartial();
360       return PU.is<ClassTemplateDecl *>()
361                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
362                  : *static_cast<const Decl *>(
363                        PU.get<ClassTemplatePartialSpecializationDecl *>());
364     }
365 
366     // Class is instantiated from a member definition of a class template?
367     if (const MemberSpecializationInfo *Info =
368             CRD->getMemberSpecializationInfo())
369       return *Info->getInstantiatedFrom();
370 
371     return D;
372   }
373   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
374     // Enum is instantiated from a member definition of a class template?
375     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
376       return *MemberDecl;
377 
378     return D;
379   }
380   // FIXME: Adjust alias templates?
381   return D;
382 }
383 
384 const RawComment *ASTContext::getRawCommentForAnyRedecl(
385                                                 const Decl *D,
386                                                 const Decl **OriginalDecl) const {
387   if (!D) {
388     if (OriginalDecl)
389       OriginalDecl = nullptr;
390     return nullptr;
391   }
392 
393   D = &adjustDeclToTemplate(*D);
394 
395   // Any comment directly attached to D?
396   {
397     auto DeclComment = DeclRawComments.find(D);
398     if (DeclComment != DeclRawComments.end()) {
399       if (OriginalDecl)
400         *OriginalDecl = D;
401       return DeclComment->second;
402     }
403   }
404 
405   // Any comment attached to any redeclaration of D?
406   const Decl *CanonicalD = D->getCanonicalDecl();
407   if (!CanonicalD)
408     return nullptr;
409 
410   {
411     auto RedeclComment = RedeclChainComments.find(CanonicalD);
412     if (RedeclComment != RedeclChainComments.end()) {
413       if (OriginalDecl)
414         *OriginalDecl = RedeclComment->second;
415       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
416       assert(CommentAtRedecl != DeclRawComments.end() &&
417              "This decl is supposed to have comment attached.");
418       return CommentAtRedecl->second;
419     }
420   }
421 
422   // Any redeclarations of D that we haven't checked for comments yet?
423   // We can't use DenseMap::iterator directly since it'd get invalid.
424   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
425     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
426     if (LookupRes != CommentlessRedeclChains.end())
427       return LookupRes->second;
428     return nullptr;
429   }();
430 
431   for (const auto Redecl : D->redecls()) {
432     assert(Redecl);
433     // Skip all redeclarations that have been checked previously.
434     if (LastCheckedRedecl) {
435       if (LastCheckedRedecl == Redecl) {
436         LastCheckedRedecl = nullptr;
437       }
438       continue;
439     }
440     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
441     if (RedeclComment) {
442       cacheRawCommentForDecl(*Redecl, *RedeclComment);
443       if (OriginalDecl)
444         *OriginalDecl = Redecl;
445       return RedeclComment;
446     }
447     CommentlessRedeclChains[CanonicalD] = Redecl;
448   }
449 
450   if (OriginalDecl)
451     *OriginalDecl = nullptr;
452   return nullptr;
453 }
454 
455 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
456                                         const RawComment &Comment) const {
457   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
458   DeclRawComments.try_emplace(&OriginalD, &Comment);
459   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
460   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
461   CommentlessRedeclChains.erase(CanonicalDecl);
462 }
463 
464 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
465                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
466   const DeclContext *DC = ObjCMethod->getDeclContext();
467   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
468     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
469     if (!ID)
470       return;
471     // Add redeclared method here.
472     for (const auto *Ext : ID->known_extensions()) {
473       if (ObjCMethodDecl *RedeclaredMethod =
474             Ext->getMethod(ObjCMethod->getSelector(),
475                                   ObjCMethod->isInstanceMethod()))
476         Redeclared.push_back(RedeclaredMethod);
477     }
478   }
479 }
480 
481 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
482                                                  const Preprocessor *PP) {
483   if (Comments.empty() || Decls.empty())
484     return;
485 
486   FileID File;
487   for (Decl *D : Decls) {
488     SourceLocation Loc = D->getLocation();
489     if (Loc.isValid()) {
490       // See if there are any new comments that are not attached to a decl.
491       // The location doesn't have to be precise - we care only about the file.
492       File = SourceMgr.getDecomposedLoc(Loc).first;
493       break;
494     }
495   }
496 
497   if (File.isInvalid())
498     return;
499 
500   auto CommentsInThisFile = Comments.getCommentsInFile(File);
501   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
502       CommentsInThisFile->rbegin()->second->isAttached())
503     return;
504 
505   // There is at least one comment not attached to a decl.
506   // Maybe it should be attached to one of Decls?
507   //
508   // Note that this way we pick up not only comments that precede the
509   // declaration, but also comments that *follow* the declaration -- thanks to
510   // the lookahead in the lexer: we've consumed the semicolon and looked
511   // ahead through comments.
512 
513   for (const Decl *D : Decls) {
514     assert(D);
515     if (D->isInvalidDecl())
516       continue;
517 
518     D = &adjustDeclToTemplate(*D);
519 
520     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
521 
522     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
523       continue;
524 
525     if (DeclRawComments.count(D) > 0)
526       continue;
527 
528     if (RawComment *const DocComment =
529             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
530       cacheRawCommentForDecl(*D, *DocComment);
531       comments::FullComment *FC = DocComment->parse(*this, PP, D);
532       ParsedComments[D->getCanonicalDecl()] = FC;
533     }
534   }
535 }
536 
537 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
538                                                     const Decl *D) const {
539   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
540   ThisDeclInfo->CommentDecl = D;
541   ThisDeclInfo->IsFilled = false;
542   ThisDeclInfo->fill();
543   ThisDeclInfo->CommentDecl = FC->getDecl();
544   if (!ThisDeclInfo->TemplateParameters)
545     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
546   comments::FullComment *CFC =
547     new (*this) comments::FullComment(FC->getBlocks(),
548                                       ThisDeclInfo);
549   return CFC;
550 }
551 
552 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
553   const RawComment *RC = getRawCommentForDeclNoCache(D);
554   return RC ? RC->parse(*this, nullptr, D) : nullptr;
555 }
556 
557 comments::FullComment *ASTContext::getCommentForDecl(
558                                               const Decl *D,
559                                               const Preprocessor *PP) const {
560   if (!D || D->isInvalidDecl())
561     return nullptr;
562   D = &adjustDeclToTemplate(*D);
563 
564   const Decl *Canonical = D->getCanonicalDecl();
565   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
566       ParsedComments.find(Canonical);
567 
568   if (Pos != ParsedComments.end()) {
569     if (Canonical != D) {
570       comments::FullComment *FC = Pos->second;
571       comments::FullComment *CFC = cloneFullComment(FC, D);
572       return CFC;
573     }
574     return Pos->second;
575   }
576 
577   const Decl *OriginalDecl = nullptr;
578 
579   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
580   if (!RC) {
581     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
582       SmallVector<const NamedDecl*, 8> Overridden;
583       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
584       if (OMD && OMD->isPropertyAccessor())
585         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
586           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
587             return cloneFullComment(FC, D);
588       if (OMD)
589         addRedeclaredMethods(OMD, Overridden);
590       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
591       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
592         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
593           return cloneFullComment(FC, D);
594     }
595     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
596       // Attach any tag type's documentation to its typedef if latter
597       // does not have one of its own.
598       QualType QT = TD->getUnderlyingType();
599       if (const auto *TT = QT->getAs<TagType>())
600         if (const Decl *TD = TT->getDecl())
601           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
602             return cloneFullComment(FC, D);
603     }
604     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
605       while (IC->getSuperClass()) {
606         IC = IC->getSuperClass();
607         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608           return cloneFullComment(FC, D);
609       }
610     }
611     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
612       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
613         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
614           return cloneFullComment(FC, D);
615     }
616     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
617       if (!(RD = RD->getDefinition()))
618         return nullptr;
619       // Check non-virtual bases.
620       for (const auto &I : RD->bases()) {
621         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
622           continue;
623         QualType Ty = I.getType();
624         if (Ty.isNull())
625           continue;
626         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
627           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
628             continue;
629 
630           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
631             return cloneFullComment(FC, D);
632         }
633       }
634       // Check virtual bases.
635       for (const auto &I : RD->vbases()) {
636         if (I.getAccessSpecifier() != AS_public)
637           continue;
638         QualType Ty = I.getType();
639         if (Ty.isNull())
640           continue;
641         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
642           if (!(VirtualBase= VirtualBase->getDefinition()))
643             continue;
644           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
645             return cloneFullComment(FC, D);
646         }
647       }
648     }
649     return nullptr;
650   }
651 
652   // If the RawComment was attached to other redeclaration of this Decl, we
653   // should parse the comment in context of that other Decl.  This is important
654   // because comments can contain references to parameter names which can be
655   // different across redeclarations.
656   if (D != OriginalDecl && OriginalDecl)
657     return getCommentForDecl(OriginalDecl, PP);
658 
659   comments::FullComment *FC = RC->parse(*this, PP, D);
660   ParsedComments[Canonical] = FC;
661   return FC;
662 }
663 
664 void
665 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
666                                                    const ASTContext &C,
667                                                TemplateTemplateParmDecl *Parm) {
668   ID.AddInteger(Parm->getDepth());
669   ID.AddInteger(Parm->getPosition());
670   ID.AddBoolean(Parm->isParameterPack());
671 
672   TemplateParameterList *Params = Parm->getTemplateParameters();
673   ID.AddInteger(Params->size());
674   for (TemplateParameterList::const_iterator P = Params->begin(),
675                                           PEnd = Params->end();
676        P != PEnd; ++P) {
677     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
678       ID.AddInteger(0);
679       ID.AddBoolean(TTP->isParameterPack());
680       const TypeConstraint *TC = TTP->getTypeConstraint();
681       ID.AddBoolean(TC != nullptr);
682       if (TC)
683         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
684                                                         /*Canonical=*/true);
685       if (TTP->isExpandedParameterPack()) {
686         ID.AddBoolean(true);
687         ID.AddInteger(TTP->getNumExpansionParameters());
688       } else
689         ID.AddBoolean(false);
690       continue;
691     }
692 
693     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
694       ID.AddInteger(1);
695       ID.AddBoolean(NTTP->isParameterPack());
696       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
697       if (NTTP->isExpandedParameterPack()) {
698         ID.AddBoolean(true);
699         ID.AddInteger(NTTP->getNumExpansionTypes());
700         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
701           QualType T = NTTP->getExpansionType(I);
702           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
703         }
704       } else
705         ID.AddBoolean(false);
706       continue;
707     }
708 
709     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
710     ID.AddInteger(2);
711     Profile(ID, C, TTP);
712   }
713   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
714   ID.AddBoolean(RequiresClause != nullptr);
715   if (RequiresClause)
716     RequiresClause->Profile(ID, C, /*Canonical=*/true);
717 }
718 
719 static Expr *
720 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
721                                           QualType ConstrainedType) {
722   // This is a bit ugly - we need to form a new immediately-declared
723   // constraint that references the new parameter; this would ideally
724   // require semantic analysis (e.g. template<C T> struct S {}; - the
725   // converted arguments of C<T> could be an argument pack if C is
726   // declared as template<typename... T> concept C = ...).
727   // We don't have semantic analysis here so we dig deep into the
728   // ready-made constraint expr and change the thing manually.
729   ConceptSpecializationExpr *CSE;
730   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
731     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
732   else
733     CSE = cast<ConceptSpecializationExpr>(IDC);
734   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
735   SmallVector<TemplateArgument, 3> NewConverted;
736   NewConverted.reserve(OldConverted.size());
737   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
738     // The case:
739     // template<typename... T> concept C = true;
740     // template<C<int> T> struct S; -> constraint is C<{T, int}>
741     NewConverted.push_back(ConstrainedType);
742     llvm::append_range(NewConverted,
743                        OldConverted.front().pack_elements().drop_front(1));
744     TemplateArgument NewPack(NewConverted);
745 
746     NewConverted.clear();
747     NewConverted.push_back(NewPack);
748     assert(OldConverted.size() == 1 &&
749            "Template parameter pack should be the last parameter");
750   } else {
751     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
752            "Unexpected first argument kind for immediately-declared "
753            "constraint");
754     NewConverted.push_back(ConstrainedType);
755     llvm::append_range(NewConverted, OldConverted.drop_front(1));
756   }
757   Expr *NewIDC = ConceptSpecializationExpr::Create(
758       C, CSE->getNamedConcept(), NewConverted, nullptr,
759       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
760 
761   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
762     NewIDC = new (C) CXXFoldExpr(
763         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
764         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
765         SourceLocation(), /*NumExpansions=*/None);
766   return NewIDC;
767 }
768 
769 TemplateTemplateParmDecl *
770 ASTContext::getCanonicalTemplateTemplateParmDecl(
771                                           TemplateTemplateParmDecl *TTP) const {
772   // Check if we already have a canonical template template parameter.
773   llvm::FoldingSetNodeID ID;
774   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
775   void *InsertPos = nullptr;
776   CanonicalTemplateTemplateParm *Canonical
777     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
778   if (Canonical)
779     return Canonical->getParam();
780 
781   // Build a canonical template parameter list.
782   TemplateParameterList *Params = TTP->getTemplateParameters();
783   SmallVector<NamedDecl *, 4> CanonParams;
784   CanonParams.reserve(Params->size());
785   for (TemplateParameterList::const_iterator P = Params->begin(),
786                                           PEnd = Params->end();
787        P != PEnd; ++P) {
788     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
789       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
790           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
791           TTP->getDepth(), TTP->getIndex(), nullptr, false,
792           TTP->isParameterPack(), TTP->hasTypeConstraint(),
793           TTP->isExpandedParameterPack() ?
794           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
795       if (const auto *TC = TTP->getTypeConstraint()) {
796         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
797         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
798                 *this, TC->getImmediatelyDeclaredConstraint(),
799                 ParamAsArgument);
800         TemplateArgumentListInfo CanonArgsAsWritten;
801         if (auto *Args = TC->getTemplateArgsAsWritten())
802           for (const auto &ArgLoc : Args->arguments())
803             CanonArgsAsWritten.addArgument(
804                 TemplateArgumentLoc(ArgLoc.getArgument(),
805                                     TemplateArgumentLocInfo()));
806         NewTTP->setTypeConstraint(
807             NestedNameSpecifierLoc(),
808             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
809                                 SourceLocation()), /*FoundDecl=*/nullptr,
810             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
811             // simply omit the ArgsAsWritten
812             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
813       }
814       CanonParams.push_back(NewTTP);
815     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
816       QualType T = getCanonicalType(NTTP->getType());
817       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
818       NonTypeTemplateParmDecl *Param;
819       if (NTTP->isExpandedParameterPack()) {
820         SmallVector<QualType, 2> ExpandedTypes;
821         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
822         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
823           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
824           ExpandedTInfos.push_back(
825                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
826         }
827 
828         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
829                                                 SourceLocation(),
830                                                 SourceLocation(),
831                                                 NTTP->getDepth(),
832                                                 NTTP->getPosition(), nullptr,
833                                                 T,
834                                                 TInfo,
835                                                 ExpandedTypes,
836                                                 ExpandedTInfos);
837       } else {
838         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
839                                                 SourceLocation(),
840                                                 SourceLocation(),
841                                                 NTTP->getDepth(),
842                                                 NTTP->getPosition(), nullptr,
843                                                 T,
844                                                 NTTP->isParameterPack(),
845                                                 TInfo);
846       }
847       if (AutoType *AT = T->getContainedAutoType()) {
848         if (AT->isConstrained()) {
849           Param->setPlaceholderTypeConstraint(
850               canonicalizeImmediatelyDeclaredConstraint(
851                   *this, NTTP->getPlaceholderTypeConstraint(), T));
852         }
853       }
854       CanonParams.push_back(Param);
855 
856     } else
857       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
858                                            cast<TemplateTemplateParmDecl>(*P)));
859   }
860 
861   Expr *CanonRequiresClause = nullptr;
862   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
863     CanonRequiresClause = RequiresClause;
864 
865   TemplateTemplateParmDecl *CanonTTP
866     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
867                                        SourceLocation(), TTP->getDepth(),
868                                        TTP->getPosition(),
869                                        TTP->isParameterPack(),
870                                        nullptr,
871                          TemplateParameterList::Create(*this, SourceLocation(),
872                                                        SourceLocation(),
873                                                        CanonParams,
874                                                        SourceLocation(),
875                                                        CanonRequiresClause));
876 
877   // Get the new insert position for the node we care about.
878   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
879   assert(!Canonical && "Shouldn't be in the map!");
880   (void)Canonical;
881 
882   // Create the canonical template template parameter entry.
883   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
884   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
885   return CanonTTP;
886 }
887 
888 TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
889   auto Kind = getTargetInfo().getCXXABI().getKind();
890   return getLangOpts().CXXABI.value_or(Kind);
891 }
892 
893 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
894   if (!LangOpts.CPlusPlus) return nullptr;
895 
896   switch (getCXXABIKind()) {
897   case TargetCXXABI::AppleARM64:
898   case TargetCXXABI::Fuchsia:
899   case TargetCXXABI::GenericARM: // Same as Itanium at this level
900   case TargetCXXABI::iOS:
901   case TargetCXXABI::WatchOS:
902   case TargetCXXABI::GenericAArch64:
903   case TargetCXXABI::GenericMIPS:
904   case TargetCXXABI::GenericItanium:
905   case TargetCXXABI::WebAssembly:
906   case TargetCXXABI::XL:
907     return CreateItaniumCXXABI(*this);
908   case TargetCXXABI::Microsoft:
909     return CreateMicrosoftCXXABI(*this);
910   }
911   llvm_unreachable("Invalid CXXABI type!");
912 }
913 
914 interp::Context &ASTContext::getInterpContext() {
915   if (!InterpContext) {
916     InterpContext.reset(new interp::Context(*this));
917   }
918   return *InterpContext.get();
919 }
920 
921 ParentMapContext &ASTContext::getParentMapContext() {
922   if (!ParentMapCtx)
923     ParentMapCtx.reset(new ParentMapContext(*this));
924   return *ParentMapCtx.get();
925 }
926 
927 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
928                                            const LangOptions &LOpts) {
929   if (LOpts.FakeAddressSpaceMap) {
930     // The fake address space map must have a distinct entry for each
931     // language-specific address space.
932     static const unsigned FakeAddrSpaceMap[] = {
933         0,  // Default
934         1,  // opencl_global
935         3,  // opencl_local
936         2,  // opencl_constant
937         0,  // opencl_private
938         4,  // opencl_generic
939         5,  // opencl_global_device
940         6,  // opencl_global_host
941         7,  // cuda_device
942         8,  // cuda_constant
943         9,  // cuda_shared
944         1,  // sycl_global
945         5,  // sycl_global_device
946         6,  // sycl_global_host
947         3,  // sycl_local
948         0,  // sycl_private
949         10, // ptr32_sptr
950         11, // ptr32_uptr
951         12  // ptr64
952     };
953     return &FakeAddrSpaceMap;
954   } else {
955     return &T.getAddressSpaceMap();
956   }
957 }
958 
959 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
960                                           const LangOptions &LangOpts) {
961   switch (LangOpts.getAddressSpaceMapMangling()) {
962   case LangOptions::ASMM_Target:
963     return TI.useAddressSpaceMapMangling();
964   case LangOptions::ASMM_On:
965     return true;
966   case LangOptions::ASMM_Off:
967     return false;
968   }
969   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
970 }
971 
972 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
973                        IdentifierTable &idents, SelectorTable &sels,
974                        Builtin::Context &builtins, TranslationUnitKind TUKind)
975     : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
976       FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
977       TemplateSpecializationTypes(this_()),
978       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
979       SubstTemplateTemplateParmPacks(this_()),
980       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
981       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
982       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
983                                         LangOpts.XRayNeverInstrumentFiles,
984                                         LangOpts.XRayAttrListFiles, SM)),
985       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
986       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
987       BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
988       Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
989       CompCategories(this_()), LastSDM(nullptr, 0) {
990   addTranslationUnitDecl();
991 }
992 
993 void ASTContext::cleanup() {
994   // Release the DenseMaps associated with DeclContext objects.
995   // FIXME: Is this the ideal solution?
996   ReleaseDeclContextMaps();
997 
998   // Call all of the deallocation functions on all of their targets.
999   for (auto &Pair : Deallocations)
1000     (Pair.first)(Pair.second);
1001   Deallocations.clear();
1002 
1003   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
1004   // because they can contain DenseMaps.
1005   for (llvm::DenseMap<const ObjCContainerDecl*,
1006        const ASTRecordLayout*>::iterator
1007        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
1008     // Increment in loop to prevent using deallocated memory.
1009     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1010       R->Destroy(*this);
1011   ObjCLayouts.clear();
1012 
1013   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1014        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1015     // Increment in loop to prevent using deallocated memory.
1016     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1017       R->Destroy(*this);
1018   }
1019   ASTRecordLayouts.clear();
1020 
1021   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1022                                                     AEnd = DeclAttrs.end();
1023        A != AEnd; ++A)
1024     A->second->~AttrVec();
1025   DeclAttrs.clear();
1026 
1027   for (const auto &Value : ModuleInitializers)
1028     Value.second->~PerModuleInitializers();
1029   ModuleInitializers.clear();
1030 }
1031 
1032 ASTContext::~ASTContext() { cleanup(); }
1033 
1034 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1035   TraversalScope = TopLevelDecls;
1036   getParentMapContext().clear();
1037 }
1038 
1039 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1040   Deallocations.push_back({Callback, Data});
1041 }
1042 
1043 void
1044 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1045   ExternalSource = std::move(Source);
1046 }
1047 
1048 void ASTContext::PrintStats() const {
1049   llvm::errs() << "\n*** AST Context Stats:\n";
1050   llvm::errs() << "  " << Types.size() << " types total.\n";
1051 
1052   unsigned counts[] = {
1053 #define TYPE(Name, Parent) 0,
1054 #define ABSTRACT_TYPE(Name, Parent)
1055 #include "clang/AST/TypeNodes.inc"
1056     0 // Extra
1057   };
1058 
1059   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1060     Type *T = Types[i];
1061     counts[(unsigned)T->getTypeClass()]++;
1062   }
1063 
1064   unsigned Idx = 0;
1065   unsigned TotalBytes = 0;
1066 #define TYPE(Name, Parent)                                              \
1067   if (counts[Idx])                                                      \
1068     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1069                  << " types, " << sizeof(Name##Type) << " each "        \
1070                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1071                  << " bytes)\n";                                        \
1072   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1073   ++Idx;
1074 #define ABSTRACT_TYPE(Name, Parent)
1075 #include "clang/AST/TypeNodes.inc"
1076 
1077   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1078 
1079   // Implicit special member functions.
1080   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1081                << NumImplicitDefaultConstructors
1082                << " implicit default constructors created\n";
1083   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1084                << NumImplicitCopyConstructors
1085                << " implicit copy constructors created\n";
1086   if (getLangOpts().CPlusPlus)
1087     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1088                  << NumImplicitMoveConstructors
1089                  << " implicit move constructors created\n";
1090   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1091                << NumImplicitCopyAssignmentOperators
1092                << " implicit copy assignment operators created\n";
1093   if (getLangOpts().CPlusPlus)
1094     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1095                  << NumImplicitMoveAssignmentOperators
1096                  << " implicit move assignment operators created\n";
1097   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1098                << NumImplicitDestructors
1099                << " implicit destructors created\n";
1100 
1101   if (ExternalSource) {
1102     llvm::errs() << "\n";
1103     ExternalSource->PrintStats();
1104   }
1105 
1106   BumpAlloc.PrintStats();
1107 }
1108 
1109 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1110                                            bool NotifyListeners) {
1111   if (NotifyListeners)
1112     if (auto *Listener = getASTMutationListener())
1113       Listener->RedefinedHiddenDefinition(ND, M);
1114 
1115   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1116 }
1117 
1118 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1119   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1120   if (It == MergedDefModules.end())
1121     return;
1122 
1123   auto &Merged = It->second;
1124   llvm::DenseSet<Module*> Found;
1125   for (Module *&M : Merged)
1126     if (!Found.insert(M).second)
1127       M = nullptr;
1128   llvm::erase_value(Merged, nullptr);
1129 }
1130 
1131 ArrayRef<Module *>
1132 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1133   auto MergedIt =
1134       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1135   if (MergedIt == MergedDefModules.end())
1136     return None;
1137   return MergedIt->second;
1138 }
1139 
1140 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1141   if (LazyInitializers.empty())
1142     return;
1143 
1144   auto *Source = Ctx.getExternalSource();
1145   assert(Source && "lazy initializers but no external source");
1146 
1147   auto LazyInits = std::move(LazyInitializers);
1148   LazyInitializers.clear();
1149 
1150   for (auto ID : LazyInits)
1151     Initializers.push_back(Source->GetExternalDecl(ID));
1152 
1153   assert(LazyInitializers.empty() &&
1154          "GetExternalDecl for lazy module initializer added more inits");
1155 }
1156 
1157 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1158   // One special case: if we add a module initializer that imports another
1159   // module, and that module's only initializer is an ImportDecl, simplify.
1160   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1161     auto It = ModuleInitializers.find(ID->getImportedModule());
1162 
1163     // Maybe the ImportDecl does nothing at all. (Common case.)
1164     if (It == ModuleInitializers.end())
1165       return;
1166 
1167     // Maybe the ImportDecl only imports another ImportDecl.
1168     auto &Imported = *It->second;
1169     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1170       Imported.resolve(*this);
1171       auto *OnlyDecl = Imported.Initializers.front();
1172       if (isa<ImportDecl>(OnlyDecl))
1173         D = OnlyDecl;
1174     }
1175   }
1176 
1177   auto *&Inits = ModuleInitializers[M];
1178   if (!Inits)
1179     Inits = new (*this) PerModuleInitializers;
1180   Inits->Initializers.push_back(D);
1181 }
1182 
1183 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1184   auto *&Inits = ModuleInitializers[M];
1185   if (!Inits)
1186     Inits = new (*this) PerModuleInitializers;
1187   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1188                                  IDs.begin(), IDs.end());
1189 }
1190 
1191 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1192   auto It = ModuleInitializers.find(M);
1193   if (It == ModuleInitializers.end())
1194     return None;
1195 
1196   auto *Inits = It->second;
1197   Inits->resolve(*this);
1198   return Inits->Initializers;
1199 }
1200 
1201 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1202   if (!ExternCContext)
1203     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1204 
1205   return ExternCContext;
1206 }
1207 
1208 BuiltinTemplateDecl *
1209 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1210                                      const IdentifierInfo *II) const {
1211   auto *BuiltinTemplate =
1212       BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1213   BuiltinTemplate->setImplicit();
1214   getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1215 
1216   return BuiltinTemplate;
1217 }
1218 
1219 BuiltinTemplateDecl *
1220 ASTContext::getMakeIntegerSeqDecl() const {
1221   if (!MakeIntegerSeqDecl)
1222     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1223                                                   getMakeIntegerSeqName());
1224   return MakeIntegerSeqDecl;
1225 }
1226 
1227 BuiltinTemplateDecl *
1228 ASTContext::getTypePackElementDecl() const {
1229   if (!TypePackElementDecl)
1230     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1231                                                    getTypePackElementName());
1232   return TypePackElementDecl;
1233 }
1234 
1235 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1236                                             RecordDecl::TagKind TK) const {
1237   SourceLocation Loc;
1238   RecordDecl *NewDecl;
1239   if (getLangOpts().CPlusPlus)
1240     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1241                                     Loc, &Idents.get(Name));
1242   else
1243     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1244                                  &Idents.get(Name));
1245   NewDecl->setImplicit();
1246   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1247       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1248   return NewDecl;
1249 }
1250 
1251 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1252                                               StringRef Name) const {
1253   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1254   TypedefDecl *NewDecl = TypedefDecl::Create(
1255       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1256       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1257   NewDecl->setImplicit();
1258   return NewDecl;
1259 }
1260 
1261 TypedefDecl *ASTContext::getInt128Decl() const {
1262   if (!Int128Decl)
1263     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1264   return Int128Decl;
1265 }
1266 
1267 TypedefDecl *ASTContext::getUInt128Decl() const {
1268   if (!UInt128Decl)
1269     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1270   return UInt128Decl;
1271 }
1272 
1273 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1274   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1275   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1276   Types.push_back(Ty);
1277 }
1278 
1279 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1280                                   const TargetInfo *AuxTarget) {
1281   assert((!this->Target || this->Target == &Target) &&
1282          "Incorrect target reinitialization");
1283   assert(VoidTy.isNull() && "Context reinitialized?");
1284 
1285   this->Target = &Target;
1286   this->AuxTarget = AuxTarget;
1287 
1288   ABI.reset(createCXXABI(Target));
1289   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1290   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1291 
1292   // C99 6.2.5p19.
1293   InitBuiltinType(VoidTy,              BuiltinType::Void);
1294 
1295   // C99 6.2.5p2.
1296   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1297   // C99 6.2.5p3.
1298   if (LangOpts.CharIsSigned)
1299     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1300   else
1301     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1302   // C99 6.2.5p4.
1303   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1304   InitBuiltinType(ShortTy,             BuiltinType::Short);
1305   InitBuiltinType(IntTy,               BuiltinType::Int);
1306   InitBuiltinType(LongTy,              BuiltinType::Long);
1307   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1308 
1309   // C99 6.2.5p6.
1310   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1311   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1312   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1313   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1314   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1315 
1316   // C99 6.2.5p10.
1317   InitBuiltinType(FloatTy,             BuiltinType::Float);
1318   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1319   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1320 
1321   // GNU extension, __float128 for IEEE quadruple precision
1322   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1323 
1324   // __ibm128 for IBM extended precision
1325   InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1326 
1327   // C11 extension ISO/IEC TS 18661-3
1328   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1329 
1330   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1331   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1332   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1333   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1334   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1335   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1336   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1337   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1338   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1339   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1340   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1341   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1342   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1343   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1344   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1345   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1346   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1347   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1348   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1349   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1350   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1351   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1352   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1353   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1354   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1355 
1356   // GNU extension, 128-bit integers.
1357   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1358   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1359 
1360   // C++ 3.9.1p5
1361   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1362     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1363   else  // -fshort-wchar makes wchar_t be unsigned.
1364     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1365   if (LangOpts.CPlusPlus && LangOpts.WChar)
1366     WideCharTy = WCharTy;
1367   else {
1368     // C99 (or C++ using -fno-wchar).
1369     WideCharTy = getFromTargetType(Target.getWCharType());
1370   }
1371 
1372   WIntTy = getFromTargetType(Target.getWIntType());
1373 
1374   // C++20 (proposed)
1375   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1376 
1377   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1379   else // C99
1380     Char16Ty = getFromTargetType(Target.getChar16Type());
1381 
1382   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1383     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1384   else // C99
1385     Char32Ty = getFromTargetType(Target.getChar32Type());
1386 
1387   // Placeholder type for type-dependent expressions whose type is
1388   // completely unknown. No code should ever check a type against
1389   // DependentTy and users should never see it; however, it is here to
1390   // help diagnose failures to properly check for type-dependent
1391   // expressions.
1392   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1393 
1394   // Placeholder type for functions.
1395   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1396 
1397   // Placeholder type for bound members.
1398   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1399 
1400   // Placeholder type for pseudo-objects.
1401   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1402 
1403   // "any" type; useful for debugger-like clients.
1404   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1405 
1406   // Placeholder type for unbridged ARC casts.
1407   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1408 
1409   // Placeholder type for builtin functions.
1410   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1411 
1412   // Placeholder type for OMP array sections.
1413   if (LangOpts.OpenMP) {
1414     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1415     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417   }
1418   if (LangOpts.MatrixTypes)
1419     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1420 
1421   // Builtin types for 'id', 'Class', and 'SEL'.
1422   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1423   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1424   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1425 
1426   if (LangOpts.OpenCL) {
1427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1428     InitBuiltinType(SingletonId, BuiltinType::Id);
1429 #include "clang/Basic/OpenCLImageTypes.def"
1430 
1431     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1432     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1433     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1434     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1435     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1436 
1437 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1438     InitBuiltinType(Id##Ty, BuiltinType::Id);
1439 #include "clang/Basic/OpenCLExtensionTypes.def"
1440   }
1441 
1442   if (Target.hasAArch64SVETypes()) {
1443 #define SVE_TYPE(Name, Id, SingletonId) \
1444     InitBuiltinType(SingletonId, BuiltinType::Id);
1445 #include "clang/Basic/AArch64SVEACLETypes.def"
1446   }
1447 
1448   if (Target.getTriple().isPPC64()) {
1449 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450       InitBuiltinType(Id##Ty, BuiltinType::Id);
1451 #include "clang/Basic/PPCTypes.def"
1452 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453     InitBuiltinType(Id##Ty, BuiltinType::Id);
1454 #include "clang/Basic/PPCTypes.def"
1455   }
1456 
1457   if (Target.hasRISCVVTypes()) {
1458 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1459   InitBuiltinType(SingletonId, BuiltinType::Id);
1460 #include "clang/Basic/RISCVVTypes.def"
1461   }
1462 
1463   // Builtin type for __objc_yes and __objc_no
1464   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1465                        SignedCharTy : BoolTy);
1466 
1467   ObjCConstantStringType = QualType();
1468 
1469   ObjCSuperType = QualType();
1470 
1471   // void * type
1472   if (LangOpts.OpenCLGenericAddressSpace) {
1473     auto Q = VoidTy.getQualifiers();
1474     Q.setAddressSpace(LangAS::opencl_generic);
1475     VoidPtrTy = getPointerType(getCanonicalType(
1476         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1477   } else {
1478     VoidPtrTy = getPointerType(VoidTy);
1479   }
1480 
1481   // nullptr type (C++0x 2.14.7)
1482   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1483 
1484   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1485   InitBuiltinType(HalfTy, BuiltinType::Half);
1486 
1487   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1488 
1489   // Builtin type used to help define __builtin_va_list.
1490   VaListTagDecl = nullptr;
1491 
1492   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1493   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1494     MSGuidTagDecl = buildImplicitRecord("_GUID");
1495     getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1496   }
1497 }
1498 
1499 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1500   return SourceMgr.getDiagnostics();
1501 }
1502 
1503 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1504   AttrVec *&Result = DeclAttrs[D];
1505   if (!Result) {
1506     void *Mem = Allocate(sizeof(AttrVec));
1507     Result = new (Mem) AttrVec;
1508   }
1509 
1510   return *Result;
1511 }
1512 
1513 /// Erase the attributes corresponding to the given declaration.
1514 void ASTContext::eraseDeclAttrs(const Decl *D) {
1515   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1516   if (Pos != DeclAttrs.end()) {
1517     Pos->second->~AttrVec();
1518     DeclAttrs.erase(Pos);
1519   }
1520 }
1521 
1522 // FIXME: Remove ?
1523 MemberSpecializationInfo *
1524 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1525   assert(Var->isStaticDataMember() && "Not a static data member");
1526   return getTemplateOrSpecializationInfo(Var)
1527       .dyn_cast<MemberSpecializationInfo *>();
1528 }
1529 
1530 ASTContext::TemplateOrSpecializationInfo
1531 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1532   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1533       TemplateOrInstantiation.find(Var);
1534   if (Pos == TemplateOrInstantiation.end())
1535     return {};
1536 
1537   return Pos->second;
1538 }
1539 
1540 void
1541 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1542                                                 TemplateSpecializationKind TSK,
1543                                           SourceLocation PointOfInstantiation) {
1544   assert(Inst->isStaticDataMember() && "Not a static data member");
1545   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1546   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1547                                             Tmpl, TSK, PointOfInstantiation));
1548 }
1549 
1550 void
1551 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1552                                             TemplateOrSpecializationInfo TSI) {
1553   assert(!TemplateOrInstantiation[Inst] &&
1554          "Already noted what the variable was instantiated from");
1555   TemplateOrInstantiation[Inst] = TSI;
1556 }
1557 
1558 NamedDecl *
1559 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1560   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1561   if (Pos == InstantiatedFromUsingDecl.end())
1562     return nullptr;
1563 
1564   return Pos->second;
1565 }
1566 
1567 void
1568 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1569   assert((isa<UsingDecl>(Pattern) ||
1570           isa<UnresolvedUsingValueDecl>(Pattern) ||
1571           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1572          "pattern decl is not a using decl");
1573   assert((isa<UsingDecl>(Inst) ||
1574           isa<UnresolvedUsingValueDecl>(Inst) ||
1575           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1576          "instantiation did not produce a using decl");
1577   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1578   InstantiatedFromUsingDecl[Inst] = Pattern;
1579 }
1580 
1581 UsingEnumDecl *
1582 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1583   auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
1584   if (Pos == InstantiatedFromUsingEnumDecl.end())
1585     return nullptr;
1586 
1587   return Pos->second;
1588 }
1589 
1590 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1591                                                   UsingEnumDecl *Pattern) {
1592   assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1593   InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1594 }
1595 
1596 UsingShadowDecl *
1597 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1598   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1599     = InstantiatedFromUsingShadowDecl.find(Inst);
1600   if (Pos == InstantiatedFromUsingShadowDecl.end())
1601     return nullptr;
1602 
1603   return Pos->second;
1604 }
1605 
1606 void
1607 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1608                                                UsingShadowDecl *Pattern) {
1609   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611 }
1612 
1613 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1614   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1615     = InstantiatedFromUnnamedFieldDecl.find(Field);
1616   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1617     return nullptr;
1618 
1619   return Pos->second;
1620 }
1621 
1622 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1623                                                      FieldDecl *Tmpl) {
1624   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1625   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1626   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1627          "Already noted what unnamed field was instantiated from");
1628 
1629   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1630 }
1631 
1632 ASTContext::overridden_cxx_method_iterator
1633 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1634   return overridden_methods(Method).begin();
1635 }
1636 
1637 ASTContext::overridden_cxx_method_iterator
1638 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1639   return overridden_methods(Method).end();
1640 }
1641 
1642 unsigned
1643 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1644   auto Range = overridden_methods(Method);
1645   return Range.end() - Range.begin();
1646 }
1647 
1648 ASTContext::overridden_method_range
1649 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1650   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1651       OverriddenMethods.find(Method->getCanonicalDecl());
1652   if (Pos == OverriddenMethods.end())
1653     return overridden_method_range(nullptr, nullptr);
1654   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1655 }
1656 
1657 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1658                                      const CXXMethodDecl *Overridden) {
1659   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1660   OverriddenMethods[Method].push_back(Overridden);
1661 }
1662 
1663 void ASTContext::getOverriddenMethods(
1664                       const NamedDecl *D,
1665                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1666   assert(D);
1667 
1668   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1669     Overridden.append(overridden_methods_begin(CXXMethod),
1670                       overridden_methods_end(CXXMethod));
1671     return;
1672   }
1673 
1674   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1675   if (!Method)
1676     return;
1677 
1678   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1679   Method->getOverriddenMethods(OverDecls);
1680   Overridden.append(OverDecls.begin(), OverDecls.end());
1681 }
1682 
1683 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1684   assert(!Import->getNextLocalImport() &&
1685          "Import declaration already in the chain");
1686   assert(!Import->isFromASTFile() && "Non-local import declaration");
1687   if (!FirstLocalImport) {
1688     FirstLocalImport = Import;
1689     LastLocalImport = Import;
1690     return;
1691   }
1692 
1693   LastLocalImport->setNextLocalImport(Import);
1694   LastLocalImport = Import;
1695 }
1696 
1697 //===----------------------------------------------------------------------===//
1698 //                         Type Sizing and Analysis
1699 //===----------------------------------------------------------------------===//
1700 
1701 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1702 /// scalar floating point type.
1703 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1704   switch (T->castAs<BuiltinType>()->getKind()) {
1705   default:
1706     llvm_unreachable("Not a floating point type!");
1707   case BuiltinType::BFloat16:
1708     return Target->getBFloat16Format();
1709   case BuiltinType::Float16:
1710     return Target->getHalfFormat();
1711   case BuiltinType::Half:
1712     // For HLSL, when the native half type is disabled, half will be treat as
1713     // float.
1714     if (getLangOpts().HLSL)
1715       if (getLangOpts().NativeHalfType)
1716         return Target->getHalfFormat();
1717       else
1718         return Target->getFloatFormat();
1719     else
1720       return Target->getHalfFormat();
1721   case BuiltinType::Float:      return Target->getFloatFormat();
1722   case BuiltinType::Double:     return Target->getDoubleFormat();
1723   case BuiltinType::Ibm128:
1724     return Target->getIbm128Format();
1725   case BuiltinType::LongDouble:
1726     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1727       return AuxTarget->getLongDoubleFormat();
1728     return Target->getLongDoubleFormat();
1729   case BuiltinType::Float128:
1730     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1731       return AuxTarget->getFloat128Format();
1732     return Target->getFloat128Format();
1733   }
1734 }
1735 
1736 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1737   unsigned Align = Target->getCharWidth();
1738 
1739   bool UseAlignAttrOnly = false;
1740   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1741     Align = AlignFromAttr;
1742 
1743     // __attribute__((aligned)) can increase or decrease alignment
1744     // *except* on a struct or struct member, where it only increases
1745     // alignment unless 'packed' is also specified.
1746     //
1747     // It is an error for alignas to decrease alignment, so we can
1748     // ignore that possibility;  Sema should diagnose it.
1749     if (isa<FieldDecl>(D)) {
1750       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1751         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1752     } else {
1753       UseAlignAttrOnly = true;
1754     }
1755   }
1756   else if (isa<FieldDecl>(D))
1757       UseAlignAttrOnly =
1758         D->hasAttr<PackedAttr>() ||
1759         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1760 
1761   // If we're using the align attribute only, just ignore everything
1762   // else about the declaration and its type.
1763   if (UseAlignAttrOnly) {
1764     // do nothing
1765   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1766     QualType T = VD->getType();
1767     if (const auto *RT = T->getAs<ReferenceType>()) {
1768       if (ForAlignof)
1769         T = RT->getPointeeType();
1770       else
1771         T = getPointerType(RT->getPointeeType());
1772     }
1773     QualType BaseT = getBaseElementType(T);
1774     if (T->isFunctionType())
1775       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1776     else if (!BaseT->isIncompleteType()) {
1777       // Adjust alignments of declarations with array type by the
1778       // large-array alignment on the target.
1779       if (const ArrayType *arrayType = getAsArrayType(T)) {
1780         unsigned MinWidth = Target->getLargeArrayMinWidth();
1781         if (!ForAlignof && MinWidth) {
1782           if (isa<VariableArrayType>(arrayType))
1783             Align = std::max(Align, Target->getLargeArrayAlign());
1784           else if (isa<ConstantArrayType>(arrayType) &&
1785                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1786             Align = std::max(Align, Target->getLargeArrayAlign());
1787         }
1788       }
1789       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1790       if (BaseT.getQualifiers().hasUnaligned())
1791         Align = Target->getCharWidth();
1792       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1793         if (VD->hasGlobalStorage() && !ForAlignof) {
1794           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1795           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1796         }
1797       }
1798     }
1799 
1800     // Fields can be subject to extra alignment constraints, like if
1801     // the field is packed, the struct is packed, or the struct has a
1802     // a max-field-alignment constraint (#pragma pack).  So calculate
1803     // the actual alignment of the field within the struct, and then
1804     // (as we're expected to) constrain that by the alignment of the type.
1805     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1806       const RecordDecl *Parent = Field->getParent();
1807       // We can only produce a sensible answer if the record is valid.
1808       if (!Parent->isInvalidDecl()) {
1809         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1810 
1811         // Start with the record's overall alignment.
1812         unsigned FieldAlign = toBits(Layout.getAlignment());
1813 
1814         // Use the GCD of that and the offset within the record.
1815         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1816         if (Offset > 0) {
1817           // Alignment is always a power of 2, so the GCD will be a power of 2,
1818           // which means we get to do this crazy thing instead of Euclid's.
1819           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1820           if (LowBitOfOffset < FieldAlign)
1821             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1822         }
1823 
1824         Align = std::min(Align, FieldAlign);
1825       }
1826     }
1827   }
1828 
1829   // Some targets have hard limitation on the maximum requestable alignment in
1830   // aligned attribute for static variables.
1831   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1832   const auto *VD = dyn_cast<VarDecl>(D);
1833   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1834     Align = std::min(Align, MaxAlignedAttr);
1835 
1836   return toCharUnitsFromBits(Align);
1837 }
1838 
1839 CharUnits ASTContext::getExnObjectAlignment() const {
1840   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1841 }
1842 
1843 // getTypeInfoDataSizeInChars - Return the size of a type, in
1844 // chars. If the type is a record, its data size is returned.  This is
1845 // the size of the memcpy that's performed when assigning this type
1846 // using a trivial copy/move assignment operator.
1847 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1848   TypeInfoChars Info = getTypeInfoInChars(T);
1849 
1850   // In C++, objects can sometimes be allocated into the tail padding
1851   // of a base-class subobject.  We decide whether that's possible
1852   // during class layout, so here we can just trust the layout results.
1853   if (getLangOpts().CPlusPlus) {
1854     if (const auto *RT = T->getAs<RecordType>()) {
1855       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1856       Info.Width = layout.getDataSize();
1857     }
1858   }
1859 
1860   return Info;
1861 }
1862 
1863 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1864 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1865 TypeInfoChars
1866 static getConstantArrayInfoInChars(const ASTContext &Context,
1867                                    const ConstantArrayType *CAT) {
1868   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1869   uint64_t Size = CAT->getSize().getZExtValue();
1870   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1871               (uint64_t)(-1)/Size) &&
1872          "Overflow in array type char size evaluation");
1873   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1874   unsigned Align = EltInfo.Align.getQuantity();
1875   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1876       Context.getTargetInfo().getPointerWidth(0) == 64)
1877     Width = llvm::alignTo(Width, Align);
1878   return TypeInfoChars(CharUnits::fromQuantity(Width),
1879                        CharUnits::fromQuantity(Align),
1880                        EltInfo.AlignRequirement);
1881 }
1882 
1883 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1884   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1885     return getConstantArrayInfoInChars(*this, CAT);
1886   TypeInfo Info = getTypeInfo(T);
1887   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1888                        toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1889 }
1890 
1891 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1892   return getTypeInfoInChars(T.getTypePtr());
1893 }
1894 
1895 bool ASTContext::isAlignmentRequired(const Type *T) const {
1896   return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1897 }
1898 
1899 bool ASTContext::isAlignmentRequired(QualType T) const {
1900   return isAlignmentRequired(T.getTypePtr());
1901 }
1902 
1903 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1904                                          bool NeedsPreferredAlignment) const {
1905   // An alignment on a typedef overrides anything else.
1906   if (const auto *TT = T->getAs<TypedefType>())
1907     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1908       return Align;
1909 
1910   // If we have an (array of) complete type, we're done.
1911   T = getBaseElementType(T);
1912   if (!T->isIncompleteType())
1913     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1914 
1915   // If we had an array type, its element type might be a typedef
1916   // type with an alignment attribute.
1917   if (const auto *TT = T->getAs<TypedefType>())
1918     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1919       return Align;
1920 
1921   // Otherwise, see if the declaration of the type had an attribute.
1922   if (const auto *TT = T->getAs<TagType>())
1923     return TT->getDecl()->getMaxAlignment();
1924 
1925   return 0;
1926 }
1927 
1928 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1929   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1930   if (I != MemoizedTypeInfo.end())
1931     return I->second;
1932 
1933   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1934   TypeInfo TI = getTypeInfoImpl(T);
1935   MemoizedTypeInfo[T] = TI;
1936   return TI;
1937 }
1938 
1939 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1940 /// method does not work on incomplete types.
1941 ///
1942 /// FIXME: Pointers into different addr spaces could have different sizes and
1943 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1944 /// should take a QualType, &c.
1945 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1946   uint64_t Width = 0;
1947   unsigned Align = 8;
1948   AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1949   unsigned AS = 0;
1950   switch (T->getTypeClass()) {
1951 #define TYPE(Class, Base)
1952 #define ABSTRACT_TYPE(Class, Base)
1953 #define NON_CANONICAL_TYPE(Class, Base)
1954 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1955 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1956   case Type::Class:                                                            \
1957   assert(!T->isDependentType() && "should not see dependent types here");      \
1958   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1959 #include "clang/AST/TypeNodes.inc"
1960     llvm_unreachable("Should not see dependent types");
1961 
1962   case Type::FunctionNoProto:
1963   case Type::FunctionProto:
1964     // GCC extension: alignof(function) = 32 bits
1965     Width = 0;
1966     Align = 32;
1967     break;
1968 
1969   case Type::IncompleteArray:
1970   case Type::VariableArray:
1971   case Type::ConstantArray: {
1972     // Model non-constant sized arrays as size zero, but track the alignment.
1973     uint64_t Size = 0;
1974     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1975       Size = CAT->getSize().getZExtValue();
1976 
1977     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1978     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1979            "Overflow in array type bit size evaluation");
1980     Width = EltInfo.Width * Size;
1981     Align = EltInfo.Align;
1982     AlignRequirement = EltInfo.AlignRequirement;
1983     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1984         getTargetInfo().getPointerWidth(0) == 64)
1985       Width = llvm::alignTo(Width, Align);
1986     break;
1987   }
1988 
1989   case Type::ExtVector:
1990   case Type::Vector: {
1991     const auto *VT = cast<VectorType>(T);
1992     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1993     Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1994                                       : EltInfo.Width * VT->getNumElements();
1995     // Enforce at least byte alignment.
1996     Align = std::max<unsigned>(8, Width);
1997 
1998     // If the alignment is not a power of 2, round up to the next power of 2.
1999     // This happens for non-power-of-2 length vectors.
2000     if (Align & (Align-1)) {
2001       Align = llvm::NextPowerOf2(Align);
2002       Width = llvm::alignTo(Width, Align);
2003     }
2004     // Adjust the alignment based on the target max.
2005     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2006     if (TargetVectorAlign && TargetVectorAlign < Align)
2007       Align = TargetVectorAlign;
2008     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
2009       // Adjust the alignment for fixed-length SVE vectors. This is important
2010       // for non-power-of-2 vector lengths.
2011       Align = 128;
2012     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
2013       // Adjust the alignment for fixed-length SVE predicates.
2014       Align = 16;
2015     break;
2016   }
2017 
2018   case Type::ConstantMatrix: {
2019     const auto *MT = cast<ConstantMatrixType>(T);
2020     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2021     // The internal layout of a matrix value is implementation defined.
2022     // Initially be ABI compatible with arrays with respect to alignment and
2023     // size.
2024     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2025     Align = ElementInfo.Align;
2026     break;
2027   }
2028 
2029   case Type::Builtin:
2030     switch (cast<BuiltinType>(T)->getKind()) {
2031     default: llvm_unreachable("Unknown builtin type!");
2032     case BuiltinType::Void:
2033       // GCC extension: alignof(void) = 8 bits.
2034       Width = 0;
2035       Align = 8;
2036       break;
2037     case BuiltinType::Bool:
2038       Width = Target->getBoolWidth();
2039       Align = Target->getBoolAlign();
2040       break;
2041     case BuiltinType::Char_S:
2042     case BuiltinType::Char_U:
2043     case BuiltinType::UChar:
2044     case BuiltinType::SChar:
2045     case BuiltinType::Char8:
2046       Width = Target->getCharWidth();
2047       Align = Target->getCharAlign();
2048       break;
2049     case BuiltinType::WChar_S:
2050     case BuiltinType::WChar_U:
2051       Width = Target->getWCharWidth();
2052       Align = Target->getWCharAlign();
2053       break;
2054     case BuiltinType::Char16:
2055       Width = Target->getChar16Width();
2056       Align = Target->getChar16Align();
2057       break;
2058     case BuiltinType::Char32:
2059       Width = Target->getChar32Width();
2060       Align = Target->getChar32Align();
2061       break;
2062     case BuiltinType::UShort:
2063     case BuiltinType::Short:
2064       Width = Target->getShortWidth();
2065       Align = Target->getShortAlign();
2066       break;
2067     case BuiltinType::UInt:
2068     case BuiltinType::Int:
2069       Width = Target->getIntWidth();
2070       Align = Target->getIntAlign();
2071       break;
2072     case BuiltinType::ULong:
2073     case BuiltinType::Long:
2074       Width = Target->getLongWidth();
2075       Align = Target->getLongAlign();
2076       break;
2077     case BuiltinType::ULongLong:
2078     case BuiltinType::LongLong:
2079       Width = Target->getLongLongWidth();
2080       Align = Target->getLongLongAlign();
2081       break;
2082     case BuiltinType::Int128:
2083     case BuiltinType::UInt128:
2084       Width = 128;
2085       Align = 128; // int128_t is 128-bit aligned on all targets.
2086       break;
2087     case BuiltinType::ShortAccum:
2088     case BuiltinType::UShortAccum:
2089     case BuiltinType::SatShortAccum:
2090     case BuiltinType::SatUShortAccum:
2091       Width = Target->getShortAccumWidth();
2092       Align = Target->getShortAccumAlign();
2093       break;
2094     case BuiltinType::Accum:
2095     case BuiltinType::UAccum:
2096     case BuiltinType::SatAccum:
2097     case BuiltinType::SatUAccum:
2098       Width = Target->getAccumWidth();
2099       Align = Target->getAccumAlign();
2100       break;
2101     case BuiltinType::LongAccum:
2102     case BuiltinType::ULongAccum:
2103     case BuiltinType::SatLongAccum:
2104     case BuiltinType::SatULongAccum:
2105       Width = Target->getLongAccumWidth();
2106       Align = Target->getLongAccumAlign();
2107       break;
2108     case BuiltinType::ShortFract:
2109     case BuiltinType::UShortFract:
2110     case BuiltinType::SatShortFract:
2111     case BuiltinType::SatUShortFract:
2112       Width = Target->getShortFractWidth();
2113       Align = Target->getShortFractAlign();
2114       break;
2115     case BuiltinType::Fract:
2116     case BuiltinType::UFract:
2117     case BuiltinType::SatFract:
2118     case BuiltinType::SatUFract:
2119       Width = Target->getFractWidth();
2120       Align = Target->getFractAlign();
2121       break;
2122     case BuiltinType::LongFract:
2123     case BuiltinType::ULongFract:
2124     case BuiltinType::SatLongFract:
2125     case BuiltinType::SatULongFract:
2126       Width = Target->getLongFractWidth();
2127       Align = Target->getLongFractAlign();
2128       break;
2129     case BuiltinType::BFloat16:
2130       if (Target->hasBFloat16Type()) {
2131         Width = Target->getBFloat16Width();
2132         Align = Target->getBFloat16Align();
2133       }
2134       break;
2135     case BuiltinType::Float16:
2136     case BuiltinType::Half:
2137       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2138           !getLangOpts().OpenMPIsDevice) {
2139         Width = Target->getHalfWidth();
2140         Align = Target->getHalfAlign();
2141       } else {
2142         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2143                "Expected OpenMP device compilation.");
2144         Width = AuxTarget->getHalfWidth();
2145         Align = AuxTarget->getHalfAlign();
2146       }
2147       break;
2148     case BuiltinType::Float:
2149       Width = Target->getFloatWidth();
2150       Align = Target->getFloatAlign();
2151       break;
2152     case BuiltinType::Double:
2153       Width = Target->getDoubleWidth();
2154       Align = Target->getDoubleAlign();
2155       break;
2156     case BuiltinType::Ibm128:
2157       Width = Target->getIbm128Width();
2158       Align = Target->getIbm128Align();
2159       break;
2160     case BuiltinType::LongDouble:
2161       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2162           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2163            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2164         Width = AuxTarget->getLongDoubleWidth();
2165         Align = AuxTarget->getLongDoubleAlign();
2166       } else {
2167         Width = Target->getLongDoubleWidth();
2168         Align = Target->getLongDoubleAlign();
2169       }
2170       break;
2171     case BuiltinType::Float128:
2172       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2173           !getLangOpts().OpenMPIsDevice) {
2174         Width = Target->getFloat128Width();
2175         Align = Target->getFloat128Align();
2176       } else {
2177         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2178                "Expected OpenMP device compilation.");
2179         Width = AuxTarget->getFloat128Width();
2180         Align = AuxTarget->getFloat128Align();
2181       }
2182       break;
2183     case BuiltinType::NullPtr:
2184       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2185       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2186       break;
2187     case BuiltinType::ObjCId:
2188     case BuiltinType::ObjCClass:
2189     case BuiltinType::ObjCSel:
2190       Width = Target->getPointerWidth(0);
2191       Align = Target->getPointerAlign(0);
2192       break;
2193     case BuiltinType::OCLSampler:
2194     case BuiltinType::OCLEvent:
2195     case BuiltinType::OCLClkEvent:
2196     case BuiltinType::OCLQueue:
2197     case BuiltinType::OCLReserveID:
2198 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2199     case BuiltinType::Id:
2200 #include "clang/Basic/OpenCLImageTypes.def"
2201 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2202   case BuiltinType::Id:
2203 #include "clang/Basic/OpenCLExtensionTypes.def"
2204       AS = getTargetAddressSpace(
2205           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2206       Width = Target->getPointerWidth(AS);
2207       Align = Target->getPointerAlign(AS);
2208       break;
2209     // The SVE types are effectively target-specific.  The length of an
2210     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2211     // of 128 bits.  There is one predicate bit for each vector byte, so the
2212     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2213     //
2214     // Because the length is only known at runtime, we use a dummy value
2215     // of 0 for the static length.  The alignment values are those defined
2216     // by the Procedure Call Standard for the Arm Architecture.
2217 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2218                         IsSigned, IsFP, IsBF)                                  \
2219   case BuiltinType::Id:                                                        \
2220     Width = 0;                                                                 \
2221     Align = 128;                                                               \
2222     break;
2223 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2224   case BuiltinType::Id:                                                        \
2225     Width = 0;                                                                 \
2226     Align = 16;                                                                \
2227     break;
2228 #include "clang/Basic/AArch64SVEACLETypes.def"
2229 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2230   case BuiltinType::Id:                                                        \
2231     Width = Size;                                                              \
2232     Align = Size;                                                              \
2233     break;
2234 #include "clang/Basic/PPCTypes.def"
2235 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2236                         IsFP)                                                  \
2237   case BuiltinType::Id:                                                        \
2238     Width = 0;                                                                 \
2239     Align = ElBits;                                                            \
2240     break;
2241 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2242   case BuiltinType::Id:                                                        \
2243     Width = 0;                                                                 \
2244     Align = 8;                                                                 \
2245     break;
2246 #include "clang/Basic/RISCVVTypes.def"
2247     }
2248     break;
2249   case Type::ObjCObjectPointer:
2250     Width = Target->getPointerWidth(0);
2251     Align = Target->getPointerAlign(0);
2252     break;
2253   case Type::BlockPointer:
2254     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2255     Width = Target->getPointerWidth(AS);
2256     Align = Target->getPointerAlign(AS);
2257     break;
2258   case Type::LValueReference:
2259   case Type::RValueReference:
2260     // alignof and sizeof should never enter this code path here, so we go
2261     // the pointer route.
2262     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2263     Width = Target->getPointerWidth(AS);
2264     Align = Target->getPointerAlign(AS);
2265     break;
2266   case Type::Pointer:
2267     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2268     Width = Target->getPointerWidth(AS);
2269     Align = Target->getPointerAlign(AS);
2270     break;
2271   case Type::MemberPointer: {
2272     const auto *MPT = cast<MemberPointerType>(T);
2273     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2274     Width = MPI.Width;
2275     Align = MPI.Align;
2276     break;
2277   }
2278   case Type::Complex: {
2279     // Complex types have the same alignment as their elements, but twice the
2280     // size.
2281     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2282     Width = EltInfo.Width * 2;
2283     Align = EltInfo.Align;
2284     break;
2285   }
2286   case Type::ObjCObject:
2287     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2288   case Type::Adjusted:
2289   case Type::Decayed:
2290     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2291   case Type::ObjCInterface: {
2292     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2293     if (ObjCI->getDecl()->isInvalidDecl()) {
2294       Width = 8;
2295       Align = 8;
2296       break;
2297     }
2298     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2299     Width = toBits(Layout.getSize());
2300     Align = toBits(Layout.getAlignment());
2301     break;
2302   }
2303   case Type::BitInt: {
2304     const auto *EIT = cast<BitIntType>(T);
2305     Align =
2306         std::min(static_cast<unsigned>(std::max(
2307                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2308                  Target->getLongLongAlign());
2309     Width = llvm::alignTo(EIT->getNumBits(), Align);
2310     break;
2311   }
2312   case Type::Record:
2313   case Type::Enum: {
2314     const auto *TT = cast<TagType>(T);
2315 
2316     if (TT->getDecl()->isInvalidDecl()) {
2317       Width = 8;
2318       Align = 8;
2319       break;
2320     }
2321 
2322     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2323       const EnumDecl *ED = ET->getDecl();
2324       TypeInfo Info =
2325           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2326       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2327         Info.Align = AttrAlign;
2328         Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2329       }
2330       return Info;
2331     }
2332 
2333     const auto *RT = cast<RecordType>(TT);
2334     const RecordDecl *RD = RT->getDecl();
2335     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2336     Width = toBits(Layout.getSize());
2337     Align = toBits(Layout.getAlignment());
2338     AlignRequirement = RD->hasAttr<AlignedAttr>()
2339                            ? AlignRequirementKind::RequiredByRecord
2340                            : AlignRequirementKind::None;
2341     break;
2342   }
2343 
2344   case Type::SubstTemplateTypeParm:
2345     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2346                        getReplacementType().getTypePtr());
2347 
2348   case Type::Auto:
2349   case Type::DeducedTemplateSpecialization: {
2350     const auto *A = cast<DeducedType>(T);
2351     assert(!A->getDeducedType().isNull() &&
2352            "cannot request the size of an undeduced or dependent auto type");
2353     return getTypeInfo(A->getDeducedType().getTypePtr());
2354   }
2355 
2356   case Type::Paren:
2357     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2358 
2359   case Type::MacroQualified:
2360     return getTypeInfo(
2361         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2362 
2363   case Type::ObjCTypeParam:
2364     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2365 
2366   case Type::Using:
2367     return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2368 
2369   case Type::Typedef: {
2370     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2371     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2372     // If the typedef has an aligned attribute on it, it overrides any computed
2373     // alignment we have.  This violates the GCC documentation (which says that
2374     // attribute(aligned) can only round up) but matches its implementation.
2375     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2376       Align = AttrAlign;
2377       AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2378     } else {
2379       Align = Info.Align;
2380       AlignRequirement = Info.AlignRequirement;
2381     }
2382     Width = Info.Width;
2383     break;
2384   }
2385 
2386   case Type::Elaborated:
2387     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2388 
2389   case Type::Attributed:
2390     return getTypeInfo(
2391                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2392 
2393   case Type::BTFTagAttributed:
2394     return getTypeInfo(
2395         cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2396 
2397   case Type::Atomic: {
2398     // Start with the base type information.
2399     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2400     Width = Info.Width;
2401     Align = Info.Align;
2402 
2403     if (!Width) {
2404       // An otherwise zero-sized type should still generate an
2405       // atomic operation.
2406       Width = Target->getCharWidth();
2407       assert(Align);
2408     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2409       // If the size of the type doesn't exceed the platform's max
2410       // atomic promotion width, make the size and alignment more
2411       // favorable to atomic operations:
2412 
2413       // Round the size up to a power of 2.
2414       if (!llvm::isPowerOf2_64(Width))
2415         Width = llvm::NextPowerOf2(Width);
2416 
2417       // Set the alignment equal to the size.
2418       Align = static_cast<unsigned>(Width);
2419     }
2420   }
2421   break;
2422 
2423   case Type::Pipe:
2424     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2425     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2426     break;
2427   }
2428 
2429   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2430   return TypeInfo(Width, Align, AlignRequirement);
2431 }
2432 
2433 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2434   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2435   if (I != MemoizedUnadjustedAlign.end())
2436     return I->second;
2437 
2438   unsigned UnadjustedAlign;
2439   if (const auto *RT = T->getAs<RecordType>()) {
2440     const RecordDecl *RD = RT->getDecl();
2441     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2442     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2443   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2444     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2445     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2446   } else {
2447     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2448   }
2449 
2450   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2451   return UnadjustedAlign;
2452 }
2453 
2454 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2455   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2456   return SimdAlign;
2457 }
2458 
2459 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2460 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2461   return CharUnits::fromQuantity(BitSize / getCharWidth());
2462 }
2463 
2464 /// toBits - Convert a size in characters to a size in characters.
2465 int64_t ASTContext::toBits(CharUnits CharSize) const {
2466   return CharSize.getQuantity() * getCharWidth();
2467 }
2468 
2469 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2470 /// This method does not work on incomplete types.
2471 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2472   return getTypeInfoInChars(T).Width;
2473 }
2474 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2475   return getTypeInfoInChars(T).Width;
2476 }
2477 
2478 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2479 /// characters. This method does not work on incomplete types.
2480 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2481   return toCharUnitsFromBits(getTypeAlign(T));
2482 }
2483 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2484   return toCharUnitsFromBits(getTypeAlign(T));
2485 }
2486 
2487 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2488 /// type, in characters, before alignment adustments. This method does
2489 /// not work on incomplete types.
2490 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2491   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2492 }
2493 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2494   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2495 }
2496 
2497 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2498 /// type for the current target in bits.  This can be different than the ABI
2499 /// alignment in cases where it is beneficial for performance or backwards
2500 /// compatibility preserving to overalign a data type. (Note: despite the name,
2501 /// the preferred alignment is ABI-impacting, and not an optimization.)
2502 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2503   TypeInfo TI = getTypeInfo(T);
2504   unsigned ABIAlign = TI.Align;
2505 
2506   T = T->getBaseElementTypeUnsafe();
2507 
2508   // The preferred alignment of member pointers is that of a pointer.
2509   if (T->isMemberPointerType())
2510     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2511 
2512   if (!Target->allowsLargerPreferedTypeAlignment())
2513     return ABIAlign;
2514 
2515   if (const auto *RT = T->getAs<RecordType>()) {
2516     const RecordDecl *RD = RT->getDecl();
2517 
2518     // When used as part of a typedef, or together with a 'packed' attribute,
2519     // the 'aligned' attribute can be used to decrease alignment. Note that the
2520     // 'packed' case is already taken into consideration when computing the
2521     // alignment, we only need to handle the typedef case here.
2522     if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2523         RD->isInvalidDecl())
2524       return ABIAlign;
2525 
2526     unsigned PreferredAlign = static_cast<unsigned>(
2527         toBits(getASTRecordLayout(RD).PreferredAlignment));
2528     assert(PreferredAlign >= ABIAlign &&
2529            "PreferredAlign should be at least as large as ABIAlign.");
2530     return PreferredAlign;
2531   }
2532 
2533   // Double (and, for targets supporting AIX `power` alignment, long double) and
2534   // long long should be naturally aligned (despite requiring less alignment) if
2535   // possible.
2536   if (const auto *CT = T->getAs<ComplexType>())
2537     T = CT->getElementType().getTypePtr();
2538   if (const auto *ET = T->getAs<EnumType>())
2539     T = ET->getDecl()->getIntegerType().getTypePtr();
2540   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2541       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2542       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2543       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2544        Target->defaultsToAIXPowerAlignment()))
2545     // Don't increase the alignment if an alignment attribute was specified on a
2546     // typedef declaration.
2547     if (!TI.isAlignRequired())
2548       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2549 
2550   return ABIAlign;
2551 }
2552 
2553 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2554 /// for __attribute__((aligned)) on this target, to be used if no alignment
2555 /// value is specified.
2556 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2557   return getTargetInfo().getDefaultAlignForAttributeAligned();
2558 }
2559 
2560 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2561 /// to a global variable of the specified type.
2562 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2563   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2564   return std::max(getPreferredTypeAlign(T),
2565                   getTargetInfo().getMinGlobalAlign(TypeSize));
2566 }
2567 
2568 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2569 /// should be given to a global variable of the specified type.
2570 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2571   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2572 }
2573 
2574 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2575   CharUnits Offset = CharUnits::Zero();
2576   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2577   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2578     Offset += Layout->getBaseClassOffset(Base);
2579     Layout = &getASTRecordLayout(Base);
2580   }
2581   return Offset;
2582 }
2583 
2584 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2585   const ValueDecl *MPD = MP.getMemberPointerDecl();
2586   CharUnits ThisAdjustment = CharUnits::Zero();
2587   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2588   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2589   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2590   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2591     const CXXRecordDecl *Base = RD;
2592     const CXXRecordDecl *Derived = Path[I];
2593     if (DerivedMember)
2594       std::swap(Base, Derived);
2595     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2596     RD = Path[I];
2597   }
2598   if (DerivedMember)
2599     ThisAdjustment = -ThisAdjustment;
2600   return ThisAdjustment;
2601 }
2602 
2603 /// DeepCollectObjCIvars -
2604 /// This routine first collects all declared, but not synthesized, ivars in
2605 /// super class and then collects all ivars, including those synthesized for
2606 /// current class. This routine is used for implementation of current class
2607 /// when all ivars, declared and synthesized are known.
2608 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2609                                       bool leafClass,
2610                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2611   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2612     DeepCollectObjCIvars(SuperClass, false, Ivars);
2613   if (!leafClass) {
2614     llvm::append_range(Ivars, OI->ivars());
2615   } else {
2616     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2617     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2618          Iv= Iv->getNextIvar())
2619       Ivars.push_back(Iv);
2620   }
2621 }
2622 
2623 /// CollectInheritedProtocols - Collect all protocols in current class and
2624 /// those inherited by it.
2625 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2626                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2627   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2628     // We can use protocol_iterator here instead of
2629     // all_referenced_protocol_iterator since we are walking all categories.
2630     for (auto *Proto : OI->all_referenced_protocols()) {
2631       CollectInheritedProtocols(Proto, Protocols);
2632     }
2633 
2634     // Categories of this Interface.
2635     for (const auto *Cat : OI->visible_categories())
2636       CollectInheritedProtocols(Cat, Protocols);
2637 
2638     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2639       while (SD) {
2640         CollectInheritedProtocols(SD, Protocols);
2641         SD = SD->getSuperClass();
2642       }
2643   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2644     for (auto *Proto : OC->protocols()) {
2645       CollectInheritedProtocols(Proto, Protocols);
2646     }
2647   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2648     // Insert the protocol.
2649     if (!Protocols.insert(
2650           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2651       return;
2652 
2653     for (auto *Proto : OP->protocols())
2654       CollectInheritedProtocols(Proto, Protocols);
2655   }
2656 }
2657 
2658 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2659                                                 const RecordDecl *RD) {
2660   assert(RD->isUnion() && "Must be union type");
2661   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2662 
2663   for (const auto *Field : RD->fields()) {
2664     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2665       return false;
2666     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2667     if (FieldSize != UnionSize)
2668       return false;
2669   }
2670   return !RD->field_empty();
2671 }
2672 
2673 static int64_t getSubobjectOffset(const FieldDecl *Field,
2674                                   const ASTContext &Context,
2675                                   const clang::ASTRecordLayout & /*Layout*/) {
2676   return Context.getFieldOffset(Field);
2677 }
2678 
2679 static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2680                                   const ASTContext &Context,
2681                                   const clang::ASTRecordLayout &Layout) {
2682   return Context.toBits(Layout.getBaseClassOffset(RD));
2683 }
2684 
2685 static llvm::Optional<int64_t>
2686 structHasUniqueObjectRepresentations(const ASTContext &Context,
2687                                      const RecordDecl *RD);
2688 
2689 static llvm::Optional<int64_t>
2690 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
2691   if (Field->getType()->isRecordType()) {
2692     const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2693     if (!RD->isUnion())
2694       return structHasUniqueObjectRepresentations(Context, RD);
2695   }
2696 
2697   // A _BitInt type may not be unique if it has padding bits
2698   // but if it is a bitfield the padding bits are not used.
2699   bool IsBitIntType = Field->getType()->isBitIntType();
2700   if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2701       !Context.hasUniqueObjectRepresentations(Field->getType()))
2702     return llvm::None;
2703 
2704   int64_t FieldSizeInBits =
2705       Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2706   if (Field->isBitField()) {
2707     int64_t BitfieldSize = Field->getBitWidthValue(Context);
2708     if (IsBitIntType) {
2709       if ((unsigned)BitfieldSize >
2710           cast<BitIntType>(Field->getType())->getNumBits())
2711         return llvm::None;
2712     } else if (BitfieldSize > FieldSizeInBits) {
2713       return llvm::None;
2714     }
2715     FieldSizeInBits = BitfieldSize;
2716   } else if (IsBitIntType &&
2717              !Context.hasUniqueObjectRepresentations(Field->getType())) {
2718     return llvm::None;
2719   }
2720   return FieldSizeInBits;
2721 }
2722 
2723 static llvm::Optional<int64_t>
2724 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
2725   return structHasUniqueObjectRepresentations(Context, RD);
2726 }
2727 
2728 template <typename RangeT>
2729 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2730     const RangeT &Subobjects, int64_t CurOffsetInBits,
2731     const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2732   for (const auto *Subobject : Subobjects) {
2733     llvm::Optional<int64_t> SizeInBits =
2734         getSubobjectSizeInBits(Subobject, Context);
2735     if (!SizeInBits)
2736       return llvm::None;
2737     if (*SizeInBits != 0) {
2738       int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2739       if (Offset != CurOffsetInBits)
2740         return llvm::None;
2741       CurOffsetInBits += *SizeInBits;
2742     }
2743   }
2744   return CurOffsetInBits;
2745 }
2746 
2747 static llvm::Optional<int64_t>
2748 structHasUniqueObjectRepresentations(const ASTContext &Context,
2749                                      const RecordDecl *RD) {
2750   assert(!RD->isUnion() && "Must be struct/class type");
2751   const auto &Layout = Context.getASTRecordLayout(RD);
2752 
2753   int64_t CurOffsetInBits = 0;
2754   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2755     if (ClassDecl->isDynamicClass())
2756       return llvm::None;
2757 
2758     SmallVector<CXXRecordDecl *, 4> Bases;
2759     for (const auto &Base : ClassDecl->bases()) {
2760       // Empty types can be inherited from, and non-empty types can potentially
2761       // have tail padding, so just make sure there isn't an error.
2762       Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2763     }
2764 
2765     llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2766       return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2767     });
2768 
2769     llvm::Optional<int64_t> OffsetAfterBases =
2770         structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
2771                                                         Context, Layout);
2772     if (!OffsetAfterBases)
2773       return llvm::None;
2774     CurOffsetInBits = *OffsetAfterBases;
2775   }
2776 
2777   llvm::Optional<int64_t> OffsetAfterFields =
2778       structSubobjectsHaveUniqueObjectRepresentations(
2779           RD->fields(), CurOffsetInBits, Context, Layout);
2780   if (!OffsetAfterFields)
2781     return llvm::None;
2782   CurOffsetInBits = *OffsetAfterFields;
2783 
2784   return CurOffsetInBits;
2785 }
2786 
2787 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2788   // C++17 [meta.unary.prop]:
2789   //   The predicate condition for a template specialization
2790   //   has_unique_object_representations<T> shall be
2791   //   satisfied if and only if:
2792   //     (9.1) - T is trivially copyable, and
2793   //     (9.2) - any two objects of type T with the same value have the same
2794   //     object representation, where two objects
2795   //   of array or non-union class type are considered to have the same value
2796   //   if their respective sequences of
2797   //   direct subobjects have the same values, and two objects of union type
2798   //   are considered to have the same
2799   //   value if they have the same active member and the corresponding members
2800   //   have the same value.
2801   //   The set of scalar types for which this condition holds is
2802   //   implementation-defined. [ Note: If a type has padding
2803   //   bits, the condition does not hold; otherwise, the condition holds true
2804   //   for unsigned integral types. -- end note ]
2805   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2806 
2807   // Arrays are unique only if their element type is unique.
2808   if (Ty->isArrayType())
2809     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2810 
2811   // (9.1) - T is trivially copyable...
2812   if (!Ty.isTriviallyCopyableType(*this))
2813     return false;
2814 
2815   // All integrals and enums are unique.
2816   if (Ty->isIntegralOrEnumerationType()) {
2817     // Except _BitInt types that have padding bits.
2818     if (const auto *BIT = dyn_cast<BitIntType>(Ty))
2819       return getTypeSize(BIT) == BIT->getNumBits();
2820 
2821     return true;
2822   }
2823 
2824   // All other pointers are unique.
2825   if (Ty->isPointerType())
2826     return true;
2827 
2828   if (Ty->isMemberPointerType()) {
2829     const auto *MPT = Ty->getAs<MemberPointerType>();
2830     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2831   }
2832 
2833   if (Ty->isRecordType()) {
2834     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2835 
2836     if (Record->isInvalidDecl())
2837       return false;
2838 
2839     if (Record->isUnion())
2840       return unionHasUniqueObjectRepresentations(*this, Record);
2841 
2842     Optional<int64_t> StructSize =
2843         structHasUniqueObjectRepresentations(*this, Record);
2844 
2845     return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2846   }
2847 
2848   // FIXME: More cases to handle here (list by rsmith):
2849   // vectors (careful about, eg, vector of 3 foo)
2850   // _Complex int and friends
2851   // _Atomic T
2852   // Obj-C block pointers
2853   // Obj-C object pointers
2854   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2855   // clk_event_t, queue_t, reserve_id_t)
2856   // There're also Obj-C class types and the Obj-C selector type, but I think it
2857   // makes sense for those to return false here.
2858 
2859   return false;
2860 }
2861 
2862 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2863   unsigned count = 0;
2864   // Count ivars declared in class extension.
2865   for (const auto *Ext : OI->known_extensions())
2866     count += Ext->ivar_size();
2867 
2868   // Count ivar defined in this class's implementation.  This
2869   // includes synthesized ivars.
2870   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2871     count += ImplDecl->ivar_size();
2872 
2873   return count;
2874 }
2875 
2876 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2877   if (!E)
2878     return false;
2879 
2880   // nullptr_t is always treated as null.
2881   if (E->getType()->isNullPtrType()) return true;
2882 
2883   if (E->getType()->isAnyPointerType() &&
2884       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2885                                                 Expr::NPC_ValueDependentIsNull))
2886     return true;
2887 
2888   // Unfortunately, __null has type 'int'.
2889   if (isa<GNUNullExpr>(E)) return true;
2890 
2891   return false;
2892 }
2893 
2894 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2895 /// exists.
2896 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2897   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2898     I = ObjCImpls.find(D);
2899   if (I != ObjCImpls.end())
2900     return cast<ObjCImplementationDecl>(I->second);
2901   return nullptr;
2902 }
2903 
2904 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2905 /// exists.
2906 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2907   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2908     I = ObjCImpls.find(D);
2909   if (I != ObjCImpls.end())
2910     return cast<ObjCCategoryImplDecl>(I->second);
2911   return nullptr;
2912 }
2913 
2914 /// Set the implementation of ObjCInterfaceDecl.
2915 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2916                            ObjCImplementationDecl *ImplD) {
2917   assert(IFaceD && ImplD && "Passed null params");
2918   ObjCImpls[IFaceD] = ImplD;
2919 }
2920 
2921 /// Set the implementation of ObjCCategoryDecl.
2922 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2923                            ObjCCategoryImplDecl *ImplD) {
2924   assert(CatD && ImplD && "Passed null params");
2925   ObjCImpls[CatD] = ImplD;
2926 }
2927 
2928 const ObjCMethodDecl *
2929 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2930   return ObjCMethodRedecls.lookup(MD);
2931 }
2932 
2933 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2934                                             const ObjCMethodDecl *Redecl) {
2935   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2936   ObjCMethodRedecls[MD] = Redecl;
2937 }
2938 
2939 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2940                                               const NamedDecl *ND) const {
2941   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2942     return ID;
2943   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2944     return CD->getClassInterface();
2945   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2946     return IMD->getClassInterface();
2947 
2948   return nullptr;
2949 }
2950 
2951 /// Get the copy initialization expression of VarDecl, or nullptr if
2952 /// none exists.
2953 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2954   assert(VD && "Passed null params");
2955   assert(VD->hasAttr<BlocksAttr>() &&
2956          "getBlockVarCopyInits - not __block var");
2957   auto I = BlockVarCopyInits.find(VD);
2958   if (I != BlockVarCopyInits.end())
2959     return I->second;
2960   return {nullptr, false};
2961 }
2962 
2963 /// Set the copy initialization expression of a block var decl.
2964 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2965                                      bool CanThrow) {
2966   assert(VD && CopyExpr && "Passed null params");
2967   assert(VD->hasAttr<BlocksAttr>() &&
2968          "setBlockVarCopyInits - not __block var");
2969   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2970 }
2971 
2972 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2973                                                  unsigned DataSize) const {
2974   if (!DataSize)
2975     DataSize = TypeLoc::getFullDataSizeForType(T);
2976   else
2977     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2978            "incorrect data size provided to CreateTypeSourceInfo!");
2979 
2980   auto *TInfo =
2981     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2982   new (TInfo) TypeSourceInfo(T);
2983   return TInfo;
2984 }
2985 
2986 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2987                                                      SourceLocation L) const {
2988   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2989   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2990   return DI;
2991 }
2992 
2993 const ASTRecordLayout &
2994 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2995   return getObjCLayout(D, nullptr);
2996 }
2997 
2998 const ASTRecordLayout &
2999 ASTContext::getASTObjCImplementationLayout(
3000                                         const ObjCImplementationDecl *D) const {
3001   return getObjCLayout(D->getClassInterface(), D);
3002 }
3003 
3004 //===----------------------------------------------------------------------===//
3005 //                   Type creation/memoization methods
3006 //===----------------------------------------------------------------------===//
3007 
3008 QualType
3009 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3010   unsigned fastQuals = quals.getFastQualifiers();
3011   quals.removeFastQualifiers();
3012 
3013   // Check if we've already instantiated this type.
3014   llvm::FoldingSetNodeID ID;
3015   ExtQuals::Profile(ID, baseType, quals);
3016   void *insertPos = nullptr;
3017   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3018     assert(eq->getQualifiers() == quals);
3019     return QualType(eq, fastQuals);
3020   }
3021 
3022   // If the base type is not canonical, make the appropriate canonical type.
3023   QualType canon;
3024   if (!baseType->isCanonicalUnqualified()) {
3025     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3026     canonSplit.Quals.addConsistentQualifiers(quals);
3027     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3028 
3029     // Re-find the insert position.
3030     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3031   }
3032 
3033   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
3034   ExtQualNodes.InsertNode(eq, insertPos);
3035   return QualType(eq, fastQuals);
3036 }
3037 
3038 QualType ASTContext::getAddrSpaceQualType(QualType T,
3039                                           LangAS AddressSpace) const {
3040   QualType CanT = getCanonicalType(T);
3041   if (CanT.getAddressSpace() == AddressSpace)
3042     return T;
3043 
3044   // If we are composing extended qualifiers together, merge together
3045   // into one ExtQuals node.
3046   QualifierCollector Quals;
3047   const Type *TypeNode = Quals.strip(T);
3048 
3049   // If this type already has an address space specified, it cannot get
3050   // another one.
3051   assert(!Quals.hasAddressSpace() &&
3052          "Type cannot be in multiple addr spaces!");
3053   Quals.addAddressSpace(AddressSpace);
3054 
3055   return getExtQualType(TypeNode, Quals);
3056 }
3057 
3058 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3059   // If the type is not qualified with an address space, just return it
3060   // immediately.
3061   if (!T.hasAddressSpace())
3062     return T;
3063 
3064   // If we are composing extended qualifiers together, merge together
3065   // into one ExtQuals node.
3066   QualifierCollector Quals;
3067   const Type *TypeNode;
3068 
3069   while (T.hasAddressSpace()) {
3070     TypeNode = Quals.strip(T);
3071 
3072     // If the type no longer has an address space after stripping qualifiers,
3073     // jump out.
3074     if (!QualType(TypeNode, 0).hasAddressSpace())
3075       break;
3076 
3077     // There might be sugar in the way. Strip it and try again.
3078     T = T.getSingleStepDesugaredType(*this);
3079   }
3080 
3081   Quals.removeAddressSpace();
3082 
3083   // Removal of the address space can mean there are no longer any
3084   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3085   // or required.
3086   if (Quals.hasNonFastQualifiers())
3087     return getExtQualType(TypeNode, Quals);
3088   else
3089     return QualType(TypeNode, Quals.getFastQualifiers());
3090 }
3091 
3092 QualType ASTContext::getObjCGCQualType(QualType T,
3093                                        Qualifiers::GC GCAttr) const {
3094   QualType CanT = getCanonicalType(T);
3095   if (CanT.getObjCGCAttr() == GCAttr)
3096     return T;
3097 
3098   if (const auto *ptr = T->getAs<PointerType>()) {
3099     QualType Pointee = ptr->getPointeeType();
3100     if (Pointee->isAnyPointerType()) {
3101       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3102       return getPointerType(ResultType);
3103     }
3104   }
3105 
3106   // If we are composing extended qualifiers together, merge together
3107   // into one ExtQuals node.
3108   QualifierCollector Quals;
3109   const Type *TypeNode = Quals.strip(T);
3110 
3111   // If this type already has an ObjCGC specified, it cannot get
3112   // another one.
3113   assert(!Quals.hasObjCGCAttr() &&
3114          "Type cannot have multiple ObjCGCs!");
3115   Quals.addObjCGCAttr(GCAttr);
3116 
3117   return getExtQualType(TypeNode, Quals);
3118 }
3119 
3120 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3121   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3122     QualType Pointee = Ptr->getPointeeType();
3123     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3124       return getPointerType(removeAddrSpaceQualType(Pointee));
3125     }
3126   }
3127   return T;
3128 }
3129 
3130 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3131                                                    FunctionType::ExtInfo Info) {
3132   if (T->getExtInfo() == Info)
3133     return T;
3134 
3135   QualType Result;
3136   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3137     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3138   } else {
3139     const auto *FPT = cast<FunctionProtoType>(T);
3140     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3141     EPI.ExtInfo = Info;
3142     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3143   }
3144 
3145   return cast<FunctionType>(Result.getTypePtr());
3146 }
3147 
3148 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3149                                                  QualType ResultType) {
3150   FD = FD->getMostRecentDecl();
3151   while (true) {
3152     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3153     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3154     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3155     if (FunctionDecl *Next = FD->getPreviousDecl())
3156       FD = Next;
3157     else
3158       break;
3159   }
3160   if (ASTMutationListener *L = getASTMutationListener())
3161     L->DeducedReturnType(FD, ResultType);
3162 }
3163 
3164 /// Get a function type and produce the equivalent function type with the
3165 /// specified exception specification. Type sugar that can be present on a
3166 /// declaration of a function with an exception specification is permitted
3167 /// and preserved. Other type sugar (for instance, typedefs) is not.
3168 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3169     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3170   // Might have some parens.
3171   if (const auto *PT = dyn_cast<ParenType>(Orig))
3172     return getParenType(
3173         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3174 
3175   // Might be wrapped in a macro qualified type.
3176   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3177     return getMacroQualifiedType(
3178         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3179         MQT->getMacroIdentifier());
3180 
3181   // Might have a calling-convention attribute.
3182   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3183     return getAttributedType(
3184         AT->getAttrKind(),
3185         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3186         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3187 
3188   // Anything else must be a function type. Rebuild it with the new exception
3189   // specification.
3190   const auto *Proto = Orig->castAs<FunctionProtoType>();
3191   return getFunctionType(
3192       Proto->getReturnType(), Proto->getParamTypes(),
3193       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3194 }
3195 
3196 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3197                                                           QualType U) const {
3198   return hasSameType(T, U) ||
3199          (getLangOpts().CPlusPlus17 &&
3200           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3201                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3202 }
3203 
3204 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3205   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3206     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3207     SmallVector<QualType, 16> Args(Proto->param_types());
3208     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3209       Args[i] = removePtrSizeAddrSpace(Args[i]);
3210     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3211   }
3212 
3213   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3214     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3215     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3216   }
3217 
3218   return T;
3219 }
3220 
3221 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3222   return hasSameType(T, U) ||
3223          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3224                      getFunctionTypeWithoutPtrSizes(U));
3225 }
3226 
3227 void ASTContext::adjustExceptionSpec(
3228     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3229     bool AsWritten) {
3230   // Update the type.
3231   QualType Updated =
3232       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3233   FD->setType(Updated);
3234 
3235   if (!AsWritten)
3236     return;
3237 
3238   // Update the type in the type source information too.
3239   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3240     // If the type and the type-as-written differ, we may need to update
3241     // the type-as-written too.
3242     if (TSInfo->getType() != FD->getType())
3243       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3244 
3245     // FIXME: When we get proper type location information for exceptions,
3246     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3247     // up the TypeSourceInfo;
3248     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3249                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3250            "TypeLoc size mismatch from updating exception specification");
3251     TSInfo->overrideType(Updated);
3252   }
3253 }
3254 
3255 /// getComplexType - Return the uniqued reference to the type for a complex
3256 /// number with the specified element type.
3257 QualType ASTContext::getComplexType(QualType T) const {
3258   // Unique pointers, to guarantee there is only one pointer of a particular
3259   // structure.
3260   llvm::FoldingSetNodeID ID;
3261   ComplexType::Profile(ID, T);
3262 
3263   void *InsertPos = nullptr;
3264   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3265     return QualType(CT, 0);
3266 
3267   // If the pointee type isn't canonical, this won't be a canonical type either,
3268   // so fill in the canonical type field.
3269   QualType Canonical;
3270   if (!T.isCanonical()) {
3271     Canonical = getComplexType(getCanonicalType(T));
3272 
3273     // Get the new insert position for the node we care about.
3274     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3275     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3276   }
3277   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3278   Types.push_back(New);
3279   ComplexTypes.InsertNode(New, InsertPos);
3280   return QualType(New, 0);
3281 }
3282 
3283 /// getPointerType - Return the uniqued reference to the type for a pointer to
3284 /// the specified type.
3285 QualType ASTContext::getPointerType(QualType T) const {
3286   // Unique pointers, to guarantee there is only one pointer of a particular
3287   // structure.
3288   llvm::FoldingSetNodeID ID;
3289   PointerType::Profile(ID, T);
3290 
3291   void *InsertPos = nullptr;
3292   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3293     return QualType(PT, 0);
3294 
3295   // If the pointee type isn't canonical, this won't be a canonical type either,
3296   // so fill in the canonical type field.
3297   QualType Canonical;
3298   if (!T.isCanonical()) {
3299     Canonical = getPointerType(getCanonicalType(T));
3300 
3301     // Get the new insert position for the node we care about.
3302     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3303     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3304   }
3305   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3306   Types.push_back(New);
3307   PointerTypes.InsertNode(New, InsertPos);
3308   return QualType(New, 0);
3309 }
3310 
3311 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3312   llvm::FoldingSetNodeID ID;
3313   AdjustedType::Profile(ID, Orig, New);
3314   void *InsertPos = nullptr;
3315   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3316   if (AT)
3317     return QualType(AT, 0);
3318 
3319   QualType Canonical = getCanonicalType(New);
3320 
3321   // Get the new insert position for the node we care about.
3322   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3323   assert(!AT && "Shouldn't be in the map!");
3324 
3325   AT = new (*this, TypeAlignment)
3326       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3327   Types.push_back(AT);
3328   AdjustedTypes.InsertNode(AT, InsertPos);
3329   return QualType(AT, 0);
3330 }
3331 
3332 QualType ASTContext::getDecayedType(QualType T) const {
3333   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3334 
3335   QualType Decayed;
3336 
3337   // C99 6.7.5.3p7:
3338   //   A declaration of a parameter as "array of type" shall be
3339   //   adjusted to "qualified pointer to type", where the type
3340   //   qualifiers (if any) are those specified within the [ and ] of
3341   //   the array type derivation.
3342   if (T->isArrayType())
3343     Decayed = getArrayDecayedType(T);
3344 
3345   // C99 6.7.5.3p8:
3346   //   A declaration of a parameter as "function returning type"
3347   //   shall be adjusted to "pointer to function returning type", as
3348   //   in 6.3.2.1.
3349   if (T->isFunctionType())
3350     Decayed = getPointerType(T);
3351 
3352   llvm::FoldingSetNodeID ID;
3353   AdjustedType::Profile(ID, T, Decayed);
3354   void *InsertPos = nullptr;
3355   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3356   if (AT)
3357     return QualType(AT, 0);
3358 
3359   QualType Canonical = getCanonicalType(Decayed);
3360 
3361   // Get the new insert position for the node we care about.
3362   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3363   assert(!AT && "Shouldn't be in the map!");
3364 
3365   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3366   Types.push_back(AT);
3367   AdjustedTypes.InsertNode(AT, InsertPos);
3368   return QualType(AT, 0);
3369 }
3370 
3371 /// getBlockPointerType - Return the uniqued reference to the type for
3372 /// a pointer to the specified block.
3373 QualType ASTContext::getBlockPointerType(QualType T) const {
3374   assert(T->isFunctionType() && "block of function types only");
3375   // Unique pointers, to guarantee there is only one block of a particular
3376   // structure.
3377   llvm::FoldingSetNodeID ID;
3378   BlockPointerType::Profile(ID, T);
3379 
3380   void *InsertPos = nullptr;
3381   if (BlockPointerType *PT =
3382         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3383     return QualType(PT, 0);
3384 
3385   // If the block pointee type isn't canonical, this won't be a canonical
3386   // type either so fill in the canonical type field.
3387   QualType Canonical;
3388   if (!T.isCanonical()) {
3389     Canonical = getBlockPointerType(getCanonicalType(T));
3390 
3391     // Get the new insert position for the node we care about.
3392     BlockPointerType *NewIP =
3393       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3394     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3395   }
3396   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3397   Types.push_back(New);
3398   BlockPointerTypes.InsertNode(New, InsertPos);
3399   return QualType(New, 0);
3400 }
3401 
3402 /// getLValueReferenceType - Return the uniqued reference to the type for an
3403 /// lvalue reference to the specified type.
3404 QualType
3405 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3406   assert((!T->isPlaceholderType() ||
3407           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3408          "Unresolved placeholder type");
3409 
3410   // Unique pointers, to guarantee there is only one pointer of a particular
3411   // structure.
3412   llvm::FoldingSetNodeID ID;
3413   ReferenceType::Profile(ID, T, SpelledAsLValue);
3414 
3415   void *InsertPos = nullptr;
3416   if (LValueReferenceType *RT =
3417         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3418     return QualType(RT, 0);
3419 
3420   const auto *InnerRef = T->getAs<ReferenceType>();
3421 
3422   // If the referencee type isn't canonical, this won't be a canonical type
3423   // either, so fill in the canonical type field.
3424   QualType Canonical;
3425   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3426     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3427     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3428 
3429     // Get the new insert position for the node we care about.
3430     LValueReferenceType *NewIP =
3431       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3432     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3433   }
3434 
3435   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3436                                                              SpelledAsLValue);
3437   Types.push_back(New);
3438   LValueReferenceTypes.InsertNode(New, InsertPos);
3439 
3440   return QualType(New, 0);
3441 }
3442 
3443 /// getRValueReferenceType - Return the uniqued reference to the type for an
3444 /// rvalue reference to the specified type.
3445 QualType ASTContext::getRValueReferenceType(QualType T) const {
3446   assert((!T->isPlaceholderType() ||
3447           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3448          "Unresolved placeholder type");
3449 
3450   // Unique pointers, to guarantee there is only one pointer of a particular
3451   // structure.
3452   llvm::FoldingSetNodeID ID;
3453   ReferenceType::Profile(ID, T, false);
3454 
3455   void *InsertPos = nullptr;
3456   if (RValueReferenceType *RT =
3457         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3458     return QualType(RT, 0);
3459 
3460   const auto *InnerRef = T->getAs<ReferenceType>();
3461 
3462   // If the referencee type isn't canonical, this won't be a canonical type
3463   // either, so fill in the canonical type field.
3464   QualType Canonical;
3465   if (InnerRef || !T.isCanonical()) {
3466     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3467     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3468 
3469     // Get the new insert position for the node we care about.
3470     RValueReferenceType *NewIP =
3471       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3472     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3473   }
3474 
3475   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3476   Types.push_back(New);
3477   RValueReferenceTypes.InsertNode(New, InsertPos);
3478   return QualType(New, 0);
3479 }
3480 
3481 /// getMemberPointerType - Return the uniqued reference to the type for a
3482 /// member pointer to the specified type, in the specified class.
3483 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3484   // Unique pointers, to guarantee there is only one pointer of a particular
3485   // structure.
3486   llvm::FoldingSetNodeID ID;
3487   MemberPointerType::Profile(ID, T, Cls);
3488 
3489   void *InsertPos = nullptr;
3490   if (MemberPointerType *PT =
3491       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3492     return QualType(PT, 0);
3493 
3494   // If the pointee or class type isn't canonical, this won't be a canonical
3495   // type either, so fill in the canonical type field.
3496   QualType Canonical;
3497   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3498     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3499 
3500     // Get the new insert position for the node we care about.
3501     MemberPointerType *NewIP =
3502       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3503     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3504   }
3505   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3506   Types.push_back(New);
3507   MemberPointerTypes.InsertNode(New, InsertPos);
3508   return QualType(New, 0);
3509 }
3510 
3511 /// getConstantArrayType - Return the unique reference to the type for an
3512 /// array of the specified element type.
3513 QualType ASTContext::getConstantArrayType(QualType EltTy,
3514                                           const llvm::APInt &ArySizeIn,
3515                                           const Expr *SizeExpr,
3516                                           ArrayType::ArraySizeModifier ASM,
3517                                           unsigned IndexTypeQuals) const {
3518   assert((EltTy->isDependentType() ||
3519           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3520          "Constant array of VLAs is illegal!");
3521 
3522   // We only need the size as part of the type if it's instantiation-dependent.
3523   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3524     SizeExpr = nullptr;
3525 
3526   // Convert the array size into a canonical width matching the pointer size for
3527   // the target.
3528   llvm::APInt ArySize(ArySizeIn);
3529   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3530 
3531   llvm::FoldingSetNodeID ID;
3532   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3533                              IndexTypeQuals);
3534 
3535   void *InsertPos = nullptr;
3536   if (ConstantArrayType *ATP =
3537       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3538     return QualType(ATP, 0);
3539 
3540   // If the element type isn't canonical or has qualifiers, or the array bound
3541   // is instantiation-dependent, this won't be a canonical type either, so fill
3542   // in the canonical type field.
3543   QualType Canon;
3544   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3545     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3546     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3547                                  ASM, IndexTypeQuals);
3548     Canon = getQualifiedType(Canon, canonSplit.Quals);
3549 
3550     // Get the new insert position for the node we care about.
3551     ConstantArrayType *NewIP =
3552       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3553     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3554   }
3555 
3556   void *Mem = Allocate(
3557       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3558       TypeAlignment);
3559   auto *New = new (Mem)
3560     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3561   ConstantArrayTypes.InsertNode(New, InsertPos);
3562   Types.push_back(New);
3563   return QualType(New, 0);
3564 }
3565 
3566 /// getVariableArrayDecayedType - Turns the given type, which may be
3567 /// variably-modified, into the corresponding type with all the known
3568 /// sizes replaced with [*].
3569 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3570   // Vastly most common case.
3571   if (!type->isVariablyModifiedType()) return type;
3572 
3573   QualType result;
3574 
3575   SplitQualType split = type.getSplitDesugaredType();
3576   const Type *ty = split.Ty;
3577   switch (ty->getTypeClass()) {
3578 #define TYPE(Class, Base)
3579 #define ABSTRACT_TYPE(Class, Base)
3580 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3581 #include "clang/AST/TypeNodes.inc"
3582     llvm_unreachable("didn't desugar past all non-canonical types?");
3583 
3584   // These types should never be variably-modified.
3585   case Type::Builtin:
3586   case Type::Complex:
3587   case Type::Vector:
3588   case Type::DependentVector:
3589   case Type::ExtVector:
3590   case Type::DependentSizedExtVector:
3591   case Type::ConstantMatrix:
3592   case Type::DependentSizedMatrix:
3593   case Type::DependentAddressSpace:
3594   case Type::ObjCObject:
3595   case Type::ObjCInterface:
3596   case Type::ObjCObjectPointer:
3597   case Type::Record:
3598   case Type::Enum:
3599   case Type::UnresolvedUsing:
3600   case Type::TypeOfExpr:
3601   case Type::TypeOf:
3602   case Type::Decltype:
3603   case Type::UnaryTransform:
3604   case Type::DependentName:
3605   case Type::InjectedClassName:
3606   case Type::TemplateSpecialization:
3607   case Type::DependentTemplateSpecialization:
3608   case Type::TemplateTypeParm:
3609   case Type::SubstTemplateTypeParmPack:
3610   case Type::Auto:
3611   case Type::DeducedTemplateSpecialization:
3612   case Type::PackExpansion:
3613   case Type::BitInt:
3614   case Type::DependentBitInt:
3615     llvm_unreachable("type should never be variably-modified");
3616 
3617   // These types can be variably-modified but should never need to
3618   // further decay.
3619   case Type::FunctionNoProto:
3620   case Type::FunctionProto:
3621   case Type::BlockPointer:
3622   case Type::MemberPointer:
3623   case Type::Pipe:
3624     return type;
3625 
3626   // These types can be variably-modified.  All these modifications
3627   // preserve structure except as noted by comments.
3628   // TODO: if we ever care about optimizing VLAs, there are no-op
3629   // optimizations available here.
3630   case Type::Pointer:
3631     result = getPointerType(getVariableArrayDecayedType(
3632                               cast<PointerType>(ty)->getPointeeType()));
3633     break;
3634 
3635   case Type::LValueReference: {
3636     const auto *lv = cast<LValueReferenceType>(ty);
3637     result = getLValueReferenceType(
3638                  getVariableArrayDecayedType(lv->getPointeeType()),
3639                                     lv->isSpelledAsLValue());
3640     break;
3641   }
3642 
3643   case Type::RValueReference: {
3644     const auto *lv = cast<RValueReferenceType>(ty);
3645     result = getRValueReferenceType(
3646                  getVariableArrayDecayedType(lv->getPointeeType()));
3647     break;
3648   }
3649 
3650   case Type::Atomic: {
3651     const auto *at = cast<AtomicType>(ty);
3652     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3653     break;
3654   }
3655 
3656   case Type::ConstantArray: {
3657     const auto *cat = cast<ConstantArrayType>(ty);
3658     result = getConstantArrayType(
3659                  getVariableArrayDecayedType(cat->getElementType()),
3660                                   cat->getSize(),
3661                                   cat->getSizeExpr(),
3662                                   cat->getSizeModifier(),
3663                                   cat->getIndexTypeCVRQualifiers());
3664     break;
3665   }
3666 
3667   case Type::DependentSizedArray: {
3668     const auto *dat = cast<DependentSizedArrayType>(ty);
3669     result = getDependentSizedArrayType(
3670                  getVariableArrayDecayedType(dat->getElementType()),
3671                                         dat->getSizeExpr(),
3672                                         dat->getSizeModifier(),
3673                                         dat->getIndexTypeCVRQualifiers(),
3674                                         dat->getBracketsRange());
3675     break;
3676   }
3677 
3678   // Turn incomplete types into [*] types.
3679   case Type::IncompleteArray: {
3680     const auto *iat = cast<IncompleteArrayType>(ty);
3681     result = getVariableArrayType(
3682                  getVariableArrayDecayedType(iat->getElementType()),
3683                                   /*size*/ nullptr,
3684                                   ArrayType::Normal,
3685                                   iat->getIndexTypeCVRQualifiers(),
3686                                   SourceRange());
3687     break;
3688   }
3689 
3690   // Turn VLA types into [*] types.
3691   case Type::VariableArray: {
3692     const auto *vat = cast<VariableArrayType>(ty);
3693     result = getVariableArrayType(
3694                  getVariableArrayDecayedType(vat->getElementType()),
3695                                   /*size*/ nullptr,
3696                                   ArrayType::Star,
3697                                   vat->getIndexTypeCVRQualifiers(),
3698                                   vat->getBracketsRange());
3699     break;
3700   }
3701   }
3702 
3703   // Apply the top-level qualifiers from the original.
3704   return getQualifiedType(result, split.Quals);
3705 }
3706 
3707 /// getVariableArrayType - Returns a non-unique reference to the type for a
3708 /// variable array of the specified element type.
3709 QualType ASTContext::getVariableArrayType(QualType EltTy,
3710                                           Expr *NumElts,
3711                                           ArrayType::ArraySizeModifier ASM,
3712                                           unsigned IndexTypeQuals,
3713                                           SourceRange Brackets) const {
3714   // Since we don't unique expressions, it isn't possible to unique VLA's
3715   // that have an expression provided for their size.
3716   QualType Canon;
3717 
3718   // Be sure to pull qualifiers off the element type.
3719   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3720     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3721     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3722                                  IndexTypeQuals, Brackets);
3723     Canon = getQualifiedType(Canon, canonSplit.Quals);
3724   }
3725 
3726   auto *New = new (*this, TypeAlignment)
3727     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3728 
3729   VariableArrayTypes.push_back(New);
3730   Types.push_back(New);
3731   return QualType(New, 0);
3732 }
3733 
3734 /// getDependentSizedArrayType - Returns a non-unique reference to
3735 /// the type for a dependently-sized array of the specified element
3736 /// type.
3737 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3738                                                 Expr *numElements,
3739                                                 ArrayType::ArraySizeModifier ASM,
3740                                                 unsigned elementTypeQuals,
3741                                                 SourceRange brackets) const {
3742   assert((!numElements || numElements->isTypeDependent() ||
3743           numElements->isValueDependent()) &&
3744          "Size must be type- or value-dependent!");
3745 
3746   // Dependently-sized array types that do not have a specified number
3747   // of elements will have their sizes deduced from a dependent
3748   // initializer.  We do no canonicalization here at all, which is okay
3749   // because they can't be used in most locations.
3750   if (!numElements) {
3751     auto *newType
3752       = new (*this, TypeAlignment)
3753           DependentSizedArrayType(*this, elementType, QualType(),
3754                                   numElements, ASM, elementTypeQuals,
3755                                   brackets);
3756     Types.push_back(newType);
3757     return QualType(newType, 0);
3758   }
3759 
3760   // Otherwise, we actually build a new type every time, but we
3761   // also build a canonical type.
3762 
3763   SplitQualType canonElementType = getCanonicalType(elementType).split();
3764 
3765   void *insertPos = nullptr;
3766   llvm::FoldingSetNodeID ID;
3767   DependentSizedArrayType::Profile(ID, *this,
3768                                    QualType(canonElementType.Ty, 0),
3769                                    ASM, elementTypeQuals, numElements);
3770 
3771   // Look for an existing type with these properties.
3772   DependentSizedArrayType *canonTy =
3773     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3774 
3775   // If we don't have one, build one.
3776   if (!canonTy) {
3777     canonTy = new (*this, TypeAlignment)
3778       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3779                               QualType(), numElements, ASM, elementTypeQuals,
3780                               brackets);
3781     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3782     Types.push_back(canonTy);
3783   }
3784 
3785   // Apply qualifiers from the element type to the array.
3786   QualType canon = getQualifiedType(QualType(canonTy,0),
3787                                     canonElementType.Quals);
3788 
3789   // If we didn't need extra canonicalization for the element type or the size
3790   // expression, then just use that as our result.
3791   if (QualType(canonElementType.Ty, 0) == elementType &&
3792       canonTy->getSizeExpr() == numElements)
3793     return canon;
3794 
3795   // Otherwise, we need to build a type which follows the spelling
3796   // of the element type.
3797   auto *sugaredType
3798     = new (*this, TypeAlignment)
3799         DependentSizedArrayType(*this, elementType, canon, numElements,
3800                                 ASM, elementTypeQuals, brackets);
3801   Types.push_back(sugaredType);
3802   return QualType(sugaredType, 0);
3803 }
3804 
3805 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3806                                             ArrayType::ArraySizeModifier ASM,
3807                                             unsigned elementTypeQuals) const {
3808   llvm::FoldingSetNodeID ID;
3809   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3810 
3811   void *insertPos = nullptr;
3812   if (IncompleteArrayType *iat =
3813        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3814     return QualType(iat, 0);
3815 
3816   // If the element type isn't canonical, this won't be a canonical type
3817   // either, so fill in the canonical type field.  We also have to pull
3818   // qualifiers off the element type.
3819   QualType canon;
3820 
3821   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3822     SplitQualType canonSplit = getCanonicalType(elementType).split();
3823     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3824                                    ASM, elementTypeQuals);
3825     canon = getQualifiedType(canon, canonSplit.Quals);
3826 
3827     // Get the new insert position for the node we care about.
3828     IncompleteArrayType *existing =
3829       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3830     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3831   }
3832 
3833   auto *newType = new (*this, TypeAlignment)
3834     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3835 
3836   IncompleteArrayTypes.InsertNode(newType, insertPos);
3837   Types.push_back(newType);
3838   return QualType(newType, 0);
3839 }
3840 
3841 ASTContext::BuiltinVectorTypeInfo
3842 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3843 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3844   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3845    NUMVECTORS};
3846 
3847 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3848   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3849 
3850   switch (Ty->getKind()) {
3851   default:
3852     llvm_unreachable("Unsupported builtin vector type");
3853   case BuiltinType::SveInt8:
3854     return SVE_INT_ELTTY(8, 16, true, 1);
3855   case BuiltinType::SveUint8:
3856     return SVE_INT_ELTTY(8, 16, false, 1);
3857   case BuiltinType::SveInt8x2:
3858     return SVE_INT_ELTTY(8, 16, true, 2);
3859   case BuiltinType::SveUint8x2:
3860     return SVE_INT_ELTTY(8, 16, false, 2);
3861   case BuiltinType::SveInt8x3:
3862     return SVE_INT_ELTTY(8, 16, true, 3);
3863   case BuiltinType::SveUint8x3:
3864     return SVE_INT_ELTTY(8, 16, false, 3);
3865   case BuiltinType::SveInt8x4:
3866     return SVE_INT_ELTTY(8, 16, true, 4);
3867   case BuiltinType::SveUint8x4:
3868     return SVE_INT_ELTTY(8, 16, false, 4);
3869   case BuiltinType::SveInt16:
3870     return SVE_INT_ELTTY(16, 8, true, 1);
3871   case BuiltinType::SveUint16:
3872     return SVE_INT_ELTTY(16, 8, false, 1);
3873   case BuiltinType::SveInt16x2:
3874     return SVE_INT_ELTTY(16, 8, true, 2);
3875   case BuiltinType::SveUint16x2:
3876     return SVE_INT_ELTTY(16, 8, false, 2);
3877   case BuiltinType::SveInt16x3:
3878     return SVE_INT_ELTTY(16, 8, true, 3);
3879   case BuiltinType::SveUint16x3:
3880     return SVE_INT_ELTTY(16, 8, false, 3);
3881   case BuiltinType::SveInt16x4:
3882     return SVE_INT_ELTTY(16, 8, true, 4);
3883   case BuiltinType::SveUint16x4:
3884     return SVE_INT_ELTTY(16, 8, false, 4);
3885   case BuiltinType::SveInt32:
3886     return SVE_INT_ELTTY(32, 4, true, 1);
3887   case BuiltinType::SveUint32:
3888     return SVE_INT_ELTTY(32, 4, false, 1);
3889   case BuiltinType::SveInt32x2:
3890     return SVE_INT_ELTTY(32, 4, true, 2);
3891   case BuiltinType::SveUint32x2:
3892     return SVE_INT_ELTTY(32, 4, false, 2);
3893   case BuiltinType::SveInt32x3:
3894     return SVE_INT_ELTTY(32, 4, true, 3);
3895   case BuiltinType::SveUint32x3:
3896     return SVE_INT_ELTTY(32, 4, false, 3);
3897   case BuiltinType::SveInt32x4:
3898     return SVE_INT_ELTTY(32, 4, true, 4);
3899   case BuiltinType::SveUint32x4:
3900     return SVE_INT_ELTTY(32, 4, false, 4);
3901   case BuiltinType::SveInt64:
3902     return SVE_INT_ELTTY(64, 2, true, 1);
3903   case BuiltinType::SveUint64:
3904     return SVE_INT_ELTTY(64, 2, false, 1);
3905   case BuiltinType::SveInt64x2:
3906     return SVE_INT_ELTTY(64, 2, true, 2);
3907   case BuiltinType::SveUint64x2:
3908     return SVE_INT_ELTTY(64, 2, false, 2);
3909   case BuiltinType::SveInt64x3:
3910     return SVE_INT_ELTTY(64, 2, true, 3);
3911   case BuiltinType::SveUint64x3:
3912     return SVE_INT_ELTTY(64, 2, false, 3);
3913   case BuiltinType::SveInt64x4:
3914     return SVE_INT_ELTTY(64, 2, true, 4);
3915   case BuiltinType::SveUint64x4:
3916     return SVE_INT_ELTTY(64, 2, false, 4);
3917   case BuiltinType::SveBool:
3918     return SVE_ELTTY(BoolTy, 16, 1);
3919   case BuiltinType::SveFloat16:
3920     return SVE_ELTTY(HalfTy, 8, 1);
3921   case BuiltinType::SveFloat16x2:
3922     return SVE_ELTTY(HalfTy, 8, 2);
3923   case BuiltinType::SveFloat16x3:
3924     return SVE_ELTTY(HalfTy, 8, 3);
3925   case BuiltinType::SveFloat16x4:
3926     return SVE_ELTTY(HalfTy, 8, 4);
3927   case BuiltinType::SveFloat32:
3928     return SVE_ELTTY(FloatTy, 4, 1);
3929   case BuiltinType::SveFloat32x2:
3930     return SVE_ELTTY(FloatTy, 4, 2);
3931   case BuiltinType::SveFloat32x3:
3932     return SVE_ELTTY(FloatTy, 4, 3);
3933   case BuiltinType::SveFloat32x4:
3934     return SVE_ELTTY(FloatTy, 4, 4);
3935   case BuiltinType::SveFloat64:
3936     return SVE_ELTTY(DoubleTy, 2, 1);
3937   case BuiltinType::SveFloat64x2:
3938     return SVE_ELTTY(DoubleTy, 2, 2);
3939   case BuiltinType::SveFloat64x3:
3940     return SVE_ELTTY(DoubleTy, 2, 3);
3941   case BuiltinType::SveFloat64x4:
3942     return SVE_ELTTY(DoubleTy, 2, 4);
3943   case BuiltinType::SveBFloat16:
3944     return SVE_ELTTY(BFloat16Ty, 8, 1);
3945   case BuiltinType::SveBFloat16x2:
3946     return SVE_ELTTY(BFloat16Ty, 8, 2);
3947   case BuiltinType::SveBFloat16x3:
3948     return SVE_ELTTY(BFloat16Ty, 8, 3);
3949   case BuiltinType::SveBFloat16x4:
3950     return SVE_ELTTY(BFloat16Ty, 8, 4);
3951 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3952                             IsSigned)                                          \
3953   case BuiltinType::Id:                                                        \
3954     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3955             llvm::ElementCount::getScalable(NumEls), NF};
3956 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3957   case BuiltinType::Id:                                                        \
3958     return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy),    \
3959             llvm::ElementCount::getScalable(NumEls), NF};
3960 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3961   case BuiltinType::Id:                                                        \
3962     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3963 #include "clang/Basic/RISCVVTypes.def"
3964   }
3965 }
3966 
3967 /// getScalableVectorType - Return the unique reference to a scalable vector
3968 /// type of the specified element type and size. VectorType must be a built-in
3969 /// type.
3970 QualType ASTContext::getScalableVectorType(QualType EltTy,
3971                                            unsigned NumElts) const {
3972   if (Target->hasAArch64SVETypes()) {
3973     uint64_t EltTySize = getTypeSize(EltTy);
3974 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3975                         IsSigned, IsFP, IsBF)                                  \
3976   if (!EltTy->isBooleanType() &&                                               \
3977       ((EltTy->hasIntegerRepresentation() &&                                   \
3978         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3979        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3980         IsFP && !IsBF) ||                                                      \
3981        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3982         IsBF && !IsFP)) &&                                                     \
3983       EltTySize == ElBits && NumElts == NumEls) {                              \
3984     return SingletonId;                                                        \
3985   }
3986 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3987   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3988     return SingletonId;
3989 #include "clang/Basic/AArch64SVEACLETypes.def"
3990   } else if (Target->hasRISCVVTypes()) {
3991     uint64_t EltTySize = getTypeSize(EltTy);
3992 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3993                         IsFP)                                                  \
3994     if (!EltTy->isBooleanType() &&                                             \
3995         ((EltTy->hasIntegerRepresentation() &&                                 \
3996           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3997          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3998         EltTySize == ElBits && NumElts == NumEls)                              \
3999       return SingletonId;
4000 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
4001     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
4002       return SingletonId;
4003 #include "clang/Basic/RISCVVTypes.def"
4004   }
4005   return QualType();
4006 }
4007 
4008 /// getVectorType - Return the unique reference to a vector type of
4009 /// the specified element type and size. VectorType must be a built-in type.
4010 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4011                                    VectorType::VectorKind VecKind) const {
4012   assert(vecType->isBuiltinType());
4013 
4014   // Check if we've already instantiated a vector of this type.
4015   llvm::FoldingSetNodeID ID;
4016   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4017 
4018   void *InsertPos = nullptr;
4019   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4020     return QualType(VTP, 0);
4021 
4022   // If the element type isn't canonical, this won't be a canonical type either,
4023   // so fill in the canonical type field.
4024   QualType Canonical;
4025   if (!vecType.isCanonical()) {
4026     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4027 
4028     // Get the new insert position for the node we care about.
4029     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4030     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4031   }
4032   auto *New = new (*this, TypeAlignment)
4033     VectorType(vecType, NumElts, Canonical, VecKind);
4034   VectorTypes.InsertNode(New, InsertPos);
4035   Types.push_back(New);
4036   return QualType(New, 0);
4037 }
4038 
4039 QualType
4040 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4041                                    SourceLocation AttrLoc,
4042                                    VectorType::VectorKind VecKind) const {
4043   llvm::FoldingSetNodeID ID;
4044   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4045                                VecKind);
4046   void *InsertPos = nullptr;
4047   DependentVectorType *Canon =
4048       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4049   DependentVectorType *New;
4050 
4051   if (Canon) {
4052     New = new (*this, TypeAlignment) DependentVectorType(
4053         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4054   } else {
4055     QualType CanonVecTy = getCanonicalType(VecType);
4056     if (CanonVecTy == VecType) {
4057       New = new (*this, TypeAlignment) DependentVectorType(
4058           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4059 
4060       DependentVectorType *CanonCheck =
4061           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4062       assert(!CanonCheck &&
4063              "Dependent-sized vector_size canonical type broken");
4064       (void)CanonCheck;
4065       DependentVectorTypes.InsertNode(New, InsertPos);
4066     } else {
4067       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4068                                                 SourceLocation(), VecKind);
4069       New = new (*this, TypeAlignment) DependentVectorType(
4070           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4071     }
4072   }
4073 
4074   Types.push_back(New);
4075   return QualType(New, 0);
4076 }
4077 
4078 /// getExtVectorType - Return the unique reference to an extended vector type of
4079 /// the specified element type and size. VectorType must be a built-in type.
4080 QualType
4081 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
4082   assert(vecType->isBuiltinType() || vecType->isDependentType());
4083 
4084   // Check if we've already instantiated a vector of this type.
4085   llvm::FoldingSetNodeID ID;
4086   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4087                       VectorType::GenericVector);
4088   void *InsertPos = nullptr;
4089   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4090     return QualType(VTP, 0);
4091 
4092   // If the element type isn't canonical, this won't be a canonical type either,
4093   // so fill in the canonical type field.
4094   QualType Canonical;
4095   if (!vecType.isCanonical()) {
4096     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4097 
4098     // Get the new insert position for the node we care about.
4099     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4100     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4101   }
4102   auto *New = new (*this, TypeAlignment)
4103     ExtVectorType(vecType, NumElts, Canonical);
4104   VectorTypes.InsertNode(New, InsertPos);
4105   Types.push_back(New);
4106   return QualType(New, 0);
4107 }
4108 
4109 QualType
4110 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4111                                            Expr *SizeExpr,
4112                                            SourceLocation AttrLoc) const {
4113   llvm::FoldingSetNodeID ID;
4114   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4115                                        SizeExpr);
4116 
4117   void *InsertPos = nullptr;
4118   DependentSizedExtVectorType *Canon
4119     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4120   DependentSizedExtVectorType *New;
4121   if (Canon) {
4122     // We already have a canonical version of this array type; use it as
4123     // the canonical type for a newly-built type.
4124     New = new (*this, TypeAlignment)
4125       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4126                                   SizeExpr, AttrLoc);
4127   } else {
4128     QualType CanonVecTy = getCanonicalType(vecType);
4129     if (CanonVecTy == vecType) {
4130       New = new (*this, TypeAlignment)
4131         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4132                                     AttrLoc);
4133 
4134       DependentSizedExtVectorType *CanonCheck
4135         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4136       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4137       (void)CanonCheck;
4138       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4139     } else {
4140       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4141                                                            SourceLocation());
4142       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4143           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4144     }
4145   }
4146 
4147   Types.push_back(New);
4148   return QualType(New, 0);
4149 }
4150 
4151 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4152                                            unsigned NumColumns) const {
4153   llvm::FoldingSetNodeID ID;
4154   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4155                               Type::ConstantMatrix);
4156 
4157   assert(MatrixType::isValidElementType(ElementTy) &&
4158          "need a valid element type");
4159   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4160          ConstantMatrixType::isDimensionValid(NumColumns) &&
4161          "need valid matrix dimensions");
4162   void *InsertPos = nullptr;
4163   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4164     return QualType(MTP, 0);
4165 
4166   QualType Canonical;
4167   if (!ElementTy.isCanonical()) {
4168     Canonical =
4169         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4170 
4171     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4172     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4173     (void)NewIP;
4174   }
4175 
4176   auto *New = new (*this, TypeAlignment)
4177       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4178   MatrixTypes.InsertNode(New, InsertPos);
4179   Types.push_back(New);
4180   return QualType(New, 0);
4181 }
4182 
4183 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4184                                                  Expr *RowExpr,
4185                                                  Expr *ColumnExpr,
4186                                                  SourceLocation AttrLoc) const {
4187   QualType CanonElementTy = getCanonicalType(ElementTy);
4188   llvm::FoldingSetNodeID ID;
4189   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4190                                     ColumnExpr);
4191 
4192   void *InsertPos = nullptr;
4193   DependentSizedMatrixType *Canon =
4194       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4195 
4196   if (!Canon) {
4197     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4198         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4199 #ifndef NDEBUG
4200     DependentSizedMatrixType *CanonCheck =
4201         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4202     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4203 #endif
4204     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4205     Types.push_back(Canon);
4206   }
4207 
4208   // Already have a canonical version of the matrix type
4209   //
4210   // If it exactly matches the requested type, use it directly.
4211   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4212       Canon->getRowExpr() == ColumnExpr)
4213     return QualType(Canon, 0);
4214 
4215   // Use Canon as the canonical type for newly-built type.
4216   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4217       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4218                                ColumnExpr, AttrLoc);
4219   Types.push_back(New);
4220   return QualType(New, 0);
4221 }
4222 
4223 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4224                                                   Expr *AddrSpaceExpr,
4225                                                   SourceLocation AttrLoc) const {
4226   assert(AddrSpaceExpr->isInstantiationDependent());
4227 
4228   QualType canonPointeeType = getCanonicalType(PointeeType);
4229 
4230   void *insertPos = nullptr;
4231   llvm::FoldingSetNodeID ID;
4232   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4233                                      AddrSpaceExpr);
4234 
4235   DependentAddressSpaceType *canonTy =
4236     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4237 
4238   if (!canonTy) {
4239     canonTy = new (*this, TypeAlignment)
4240       DependentAddressSpaceType(*this, canonPointeeType,
4241                                 QualType(), AddrSpaceExpr, AttrLoc);
4242     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4243     Types.push_back(canonTy);
4244   }
4245 
4246   if (canonPointeeType == PointeeType &&
4247       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4248     return QualType(canonTy, 0);
4249 
4250   auto *sugaredType
4251     = new (*this, TypeAlignment)
4252         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4253                                   AddrSpaceExpr, AttrLoc);
4254   Types.push_back(sugaredType);
4255   return QualType(sugaredType, 0);
4256 }
4257 
4258 /// Determine whether \p T is canonical as the result type of a function.
4259 static bool isCanonicalResultType(QualType T) {
4260   return T.isCanonical() &&
4261          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4262           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4263 }
4264 
4265 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4266 QualType
4267 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4268                                    const FunctionType::ExtInfo &Info) const {
4269   // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4270   // functionality creates a function without a prototype regardless of
4271   // language mode (so it makes them even in C++). Once the rewriter has been
4272   // fixed, this assertion can be enabled again.
4273   //assert(!LangOpts.requiresStrictPrototypes() &&
4274   //       "strict prototypes are disabled");
4275 
4276   // Unique functions, to guarantee there is only one function of a particular
4277   // structure.
4278   llvm::FoldingSetNodeID ID;
4279   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4280 
4281   void *InsertPos = nullptr;
4282   if (FunctionNoProtoType *FT =
4283         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4284     return QualType(FT, 0);
4285 
4286   QualType Canonical;
4287   if (!isCanonicalResultType(ResultTy)) {
4288     Canonical =
4289       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4290 
4291     // Get the new insert position for the node we care about.
4292     FunctionNoProtoType *NewIP =
4293       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4294     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4295   }
4296 
4297   auto *New = new (*this, TypeAlignment)
4298     FunctionNoProtoType(ResultTy, Canonical, Info);
4299   Types.push_back(New);
4300   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4301   return QualType(New, 0);
4302 }
4303 
4304 CanQualType
4305 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4306   CanQualType CanResultType = getCanonicalType(ResultType);
4307 
4308   // Canonical result types do not have ARC lifetime qualifiers.
4309   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4310     Qualifiers Qs = CanResultType.getQualifiers();
4311     Qs.removeObjCLifetime();
4312     return CanQualType::CreateUnsafe(
4313              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4314   }
4315 
4316   return CanResultType;
4317 }
4318 
4319 static bool isCanonicalExceptionSpecification(
4320     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4321   if (ESI.Type == EST_None)
4322     return true;
4323   if (!NoexceptInType)
4324     return false;
4325 
4326   // C++17 onwards: exception specification is part of the type, as a simple
4327   // boolean "can this function type throw".
4328   if (ESI.Type == EST_BasicNoexcept)
4329     return true;
4330 
4331   // A noexcept(expr) specification is (possibly) canonical if expr is
4332   // value-dependent.
4333   if (ESI.Type == EST_DependentNoexcept)
4334     return true;
4335 
4336   // A dynamic exception specification is canonical if it only contains pack
4337   // expansions (so we can't tell whether it's non-throwing) and all its
4338   // contained types are canonical.
4339   if (ESI.Type == EST_Dynamic) {
4340     bool AnyPackExpansions = false;
4341     for (QualType ET : ESI.Exceptions) {
4342       if (!ET.isCanonical())
4343         return false;
4344       if (ET->getAs<PackExpansionType>())
4345         AnyPackExpansions = true;
4346     }
4347     return AnyPackExpansions;
4348   }
4349 
4350   return false;
4351 }
4352 
4353 QualType ASTContext::getFunctionTypeInternal(
4354     QualType ResultTy, ArrayRef<QualType> ArgArray,
4355     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4356   size_t NumArgs = ArgArray.size();
4357 
4358   // Unique functions, to guarantee there is only one function of a particular
4359   // structure.
4360   llvm::FoldingSetNodeID ID;
4361   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4362                              *this, true);
4363 
4364   QualType Canonical;
4365   bool Unique = false;
4366 
4367   void *InsertPos = nullptr;
4368   if (FunctionProtoType *FPT =
4369         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4370     QualType Existing = QualType(FPT, 0);
4371 
4372     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4373     // it so long as our exception specification doesn't contain a dependent
4374     // noexcept expression, or we're just looking for a canonical type.
4375     // Otherwise, we're going to need to create a type
4376     // sugar node to hold the concrete expression.
4377     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4378         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4379       return Existing;
4380 
4381     // We need a new type sugar node for this one, to hold the new noexcept
4382     // expression. We do no canonicalization here, but that's OK since we don't
4383     // expect to see the same noexcept expression much more than once.
4384     Canonical = getCanonicalType(Existing);
4385     Unique = true;
4386   }
4387 
4388   bool NoexceptInType = getLangOpts().CPlusPlus17;
4389   bool IsCanonicalExceptionSpec =
4390       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4391 
4392   // Determine whether the type being created is already canonical or not.
4393   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4394                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4395   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4396     if (!ArgArray[i].isCanonicalAsParam())
4397       isCanonical = false;
4398 
4399   if (OnlyWantCanonical)
4400     assert(isCanonical &&
4401            "given non-canonical parameters constructing canonical type");
4402 
4403   // If this type isn't canonical, get the canonical version of it if we don't
4404   // already have it. The exception spec is only partially part of the
4405   // canonical type, and only in C++17 onwards.
4406   if (!isCanonical && Canonical.isNull()) {
4407     SmallVector<QualType, 16> CanonicalArgs;
4408     CanonicalArgs.reserve(NumArgs);
4409     for (unsigned i = 0; i != NumArgs; ++i)
4410       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4411 
4412     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4413     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4414     CanonicalEPI.HasTrailingReturn = false;
4415 
4416     if (IsCanonicalExceptionSpec) {
4417       // Exception spec is already OK.
4418     } else if (NoexceptInType) {
4419       switch (EPI.ExceptionSpec.Type) {
4420       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4421         // We don't know yet. It shouldn't matter what we pick here; no-one
4422         // should ever look at this.
4423         LLVM_FALLTHROUGH;
4424       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4425         CanonicalEPI.ExceptionSpec.Type = EST_None;
4426         break;
4427 
4428         // A dynamic exception specification is almost always "not noexcept",
4429         // with the exception that a pack expansion might expand to no types.
4430       case EST_Dynamic: {
4431         bool AnyPacks = false;
4432         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4433           if (ET->getAs<PackExpansionType>())
4434             AnyPacks = true;
4435           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4436         }
4437         if (!AnyPacks)
4438           CanonicalEPI.ExceptionSpec.Type = EST_None;
4439         else {
4440           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4441           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4442         }
4443         break;
4444       }
4445 
4446       case EST_DynamicNone:
4447       case EST_BasicNoexcept:
4448       case EST_NoexceptTrue:
4449       case EST_NoThrow:
4450         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4451         break;
4452 
4453       case EST_DependentNoexcept:
4454         llvm_unreachable("dependent noexcept is already canonical");
4455       }
4456     } else {
4457       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4458     }
4459 
4460     // Adjust the canonical function result type.
4461     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4462     Canonical =
4463         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4464 
4465     // Get the new insert position for the node we care about.
4466     FunctionProtoType *NewIP =
4467       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4468     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4469   }
4470 
4471   // Compute the needed size to hold this FunctionProtoType and the
4472   // various trailing objects.
4473   auto ESH = FunctionProtoType::getExceptionSpecSize(
4474       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4475   size_t Size = FunctionProtoType::totalSizeToAlloc<
4476       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4477       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4478       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4479       NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
4480       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4481       EPI.ExtParameterInfos ? NumArgs : 0,
4482       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4483 
4484   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4485   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4486   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4487   Types.push_back(FTP);
4488   if (!Unique)
4489     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4490   return QualType(FTP, 0);
4491 }
4492 
4493 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4494   llvm::FoldingSetNodeID ID;
4495   PipeType::Profile(ID, T, ReadOnly);
4496 
4497   void *InsertPos = nullptr;
4498   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4499     return QualType(PT, 0);
4500 
4501   // If the pipe element type isn't canonical, this won't be a canonical type
4502   // either, so fill in the canonical type field.
4503   QualType Canonical;
4504   if (!T.isCanonical()) {
4505     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4506 
4507     // Get the new insert position for the node we care about.
4508     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4509     assert(!NewIP && "Shouldn't be in the map!");
4510     (void)NewIP;
4511   }
4512   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4513   Types.push_back(New);
4514   PipeTypes.InsertNode(New, InsertPos);
4515   return QualType(New, 0);
4516 }
4517 
4518 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4519   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4520   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4521                          : Ty;
4522 }
4523 
4524 QualType ASTContext::getReadPipeType(QualType T) const {
4525   return getPipeType(T, true);
4526 }
4527 
4528 QualType ASTContext::getWritePipeType(QualType T) const {
4529   return getPipeType(T, false);
4530 }
4531 
4532 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4533   llvm::FoldingSetNodeID ID;
4534   BitIntType::Profile(ID, IsUnsigned, NumBits);
4535 
4536   void *InsertPos = nullptr;
4537   if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4538     return QualType(EIT, 0);
4539 
4540   auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
4541   BitIntTypes.InsertNode(New, InsertPos);
4542   Types.push_back(New);
4543   return QualType(New, 0);
4544 }
4545 
4546 QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4547                                             Expr *NumBitsExpr) const {
4548   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4549   llvm::FoldingSetNodeID ID;
4550   DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4551 
4552   void *InsertPos = nullptr;
4553   if (DependentBitIntType *Existing =
4554           DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4555     return QualType(Existing, 0);
4556 
4557   auto *New = new (*this, TypeAlignment)
4558       DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
4559   DependentBitIntTypes.InsertNode(New, InsertPos);
4560 
4561   Types.push_back(New);
4562   return QualType(New, 0);
4563 }
4564 
4565 #ifndef NDEBUG
4566 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4567   if (!isa<CXXRecordDecl>(D)) return false;
4568   const auto *RD = cast<CXXRecordDecl>(D);
4569   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4570     return true;
4571   if (RD->getDescribedClassTemplate() &&
4572       !isa<ClassTemplateSpecializationDecl>(RD))
4573     return true;
4574   return false;
4575 }
4576 #endif
4577 
4578 /// getInjectedClassNameType - Return the unique reference to the
4579 /// injected class name type for the specified templated declaration.
4580 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4581                                               QualType TST) const {
4582   assert(NeedsInjectedClassNameType(Decl));
4583   if (Decl->TypeForDecl) {
4584     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4585   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4586     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4587     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4588     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4589   } else {
4590     Type *newType =
4591       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4592     Decl->TypeForDecl = newType;
4593     Types.push_back(newType);
4594   }
4595   return QualType(Decl->TypeForDecl, 0);
4596 }
4597 
4598 /// getTypeDeclType - Return the unique reference to the type for the
4599 /// specified type declaration.
4600 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4601   assert(Decl && "Passed null for Decl param");
4602   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4603 
4604   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4605     return getTypedefType(Typedef);
4606 
4607   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4608          "Template type parameter types are always available.");
4609 
4610   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4611     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4612     assert(!NeedsInjectedClassNameType(Record));
4613     return getRecordType(Record);
4614   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4615     assert(Enum->isFirstDecl() && "enum has previous declaration");
4616     return getEnumType(Enum);
4617   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4618     return getUnresolvedUsingType(Using);
4619   } else
4620     llvm_unreachable("TypeDecl without a type?");
4621 
4622   return QualType(Decl->TypeForDecl, 0);
4623 }
4624 
4625 /// getTypedefType - Return the unique reference to the type for the
4626 /// specified typedef name decl.
4627 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4628                                     QualType Underlying) const {
4629   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4630 
4631   if (Underlying.isNull())
4632     Underlying = Decl->getUnderlyingType();
4633   QualType Canonical = getCanonicalType(Underlying);
4634   auto *newType = new (*this, TypeAlignment)
4635       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4636   Decl->TypeForDecl = newType;
4637   Types.push_back(newType);
4638   return QualType(newType, 0);
4639 }
4640 
4641 QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4642                                   QualType Underlying) const {
4643   llvm::FoldingSetNodeID ID;
4644   UsingType::Profile(ID, Found);
4645 
4646   void *InsertPos = nullptr;
4647   UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos);
4648   if (T)
4649     return QualType(T, 0);
4650 
4651   assert(!Underlying.hasLocalQualifiers());
4652   assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl())));
4653   QualType Canon = Underlying.getCanonicalType();
4654 
4655   UsingType *NewType =
4656       new (*this, TypeAlignment) UsingType(Found, Underlying, Canon);
4657   Types.push_back(NewType);
4658   UsingTypes.InsertNode(NewType, InsertPos);
4659   return QualType(NewType, 0);
4660 }
4661 
4662 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4663   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4664 
4665   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4666     if (PrevDecl->TypeForDecl)
4667       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4668 
4669   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4670   Decl->TypeForDecl = newType;
4671   Types.push_back(newType);
4672   return QualType(newType, 0);
4673 }
4674 
4675 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4676   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4677 
4678   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4679     if (PrevDecl->TypeForDecl)
4680       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4681 
4682   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4683   Decl->TypeForDecl = newType;
4684   Types.push_back(newType);
4685   return QualType(newType, 0);
4686 }
4687 
4688 QualType ASTContext::getUnresolvedUsingType(
4689     const UnresolvedUsingTypenameDecl *Decl) const {
4690   if (Decl->TypeForDecl)
4691     return QualType(Decl->TypeForDecl, 0);
4692 
4693   if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4694           Decl->getCanonicalDecl())
4695     if (CanonicalDecl->TypeForDecl)
4696       return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4697 
4698   Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
4699   Decl->TypeForDecl = newType;
4700   Types.push_back(newType);
4701   return QualType(newType, 0);
4702 }
4703 
4704 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4705                                        QualType modifiedType,
4706                                        QualType equivalentType) const {
4707   llvm::FoldingSetNodeID id;
4708   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4709 
4710   void *insertPos = nullptr;
4711   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4712   if (type) return QualType(type, 0);
4713 
4714   QualType canon = getCanonicalType(equivalentType);
4715   type = new (*this, TypeAlignment)
4716       AttributedType(canon, attrKind, modifiedType, equivalentType);
4717 
4718   Types.push_back(type);
4719   AttributedTypes.InsertNode(type, insertPos);
4720 
4721   return QualType(type, 0);
4722 }
4723 
4724 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4725                                              QualType Wrapped) {
4726   llvm::FoldingSetNodeID ID;
4727   BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4728 
4729   void *InsertPos = nullptr;
4730   BTFTagAttributedType *Ty =
4731       BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4732   if (Ty)
4733     return QualType(Ty, 0);
4734 
4735   QualType Canon = getCanonicalType(Wrapped);
4736   Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4737 
4738   Types.push_back(Ty);
4739   BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4740 
4741   return QualType(Ty, 0);
4742 }
4743 
4744 /// Retrieve a substitution-result type.
4745 QualType
4746 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4747                                          QualType Replacement) const {
4748   assert(Replacement.isCanonical()
4749          && "replacement types must always be canonical");
4750 
4751   llvm::FoldingSetNodeID ID;
4752   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4753   void *InsertPos = nullptr;
4754   SubstTemplateTypeParmType *SubstParm
4755     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4756 
4757   if (!SubstParm) {
4758     SubstParm = new (*this, TypeAlignment)
4759       SubstTemplateTypeParmType(Parm, Replacement);
4760     Types.push_back(SubstParm);
4761     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4762   }
4763 
4764   return QualType(SubstParm, 0);
4765 }
4766 
4767 /// Retrieve a
4768 QualType ASTContext::getSubstTemplateTypeParmPackType(
4769                                           const TemplateTypeParmType *Parm,
4770                                               const TemplateArgument &ArgPack) {
4771 #ifndef NDEBUG
4772   for (const auto &P : ArgPack.pack_elements()) {
4773     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4774     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4775   }
4776 #endif
4777 
4778   llvm::FoldingSetNodeID ID;
4779   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4780   void *InsertPos = nullptr;
4781   if (SubstTemplateTypeParmPackType *SubstParm
4782         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4783     return QualType(SubstParm, 0);
4784 
4785   QualType Canon;
4786   if (!Parm->isCanonicalUnqualified()) {
4787     Canon = getCanonicalType(QualType(Parm, 0));
4788     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4789                                              ArgPack);
4790     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4791   }
4792 
4793   auto *SubstParm
4794     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4795                                                                ArgPack);
4796   Types.push_back(SubstParm);
4797   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4798   return QualType(SubstParm, 0);
4799 }
4800 
4801 /// Retrieve the template type parameter type for a template
4802 /// parameter or parameter pack with the given depth, index, and (optionally)
4803 /// name.
4804 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4805                                              bool ParameterPack,
4806                                              TemplateTypeParmDecl *TTPDecl) const {
4807   llvm::FoldingSetNodeID ID;
4808   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4809   void *InsertPos = nullptr;
4810   TemplateTypeParmType *TypeParm
4811     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4812 
4813   if (TypeParm)
4814     return QualType(TypeParm, 0);
4815 
4816   if (TTPDecl) {
4817     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4818     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4819 
4820     TemplateTypeParmType *TypeCheck
4821       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4822     assert(!TypeCheck && "Template type parameter canonical type broken");
4823     (void)TypeCheck;
4824   } else
4825     TypeParm = new (*this, TypeAlignment)
4826       TemplateTypeParmType(Depth, Index, ParameterPack);
4827 
4828   Types.push_back(TypeParm);
4829   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4830 
4831   return QualType(TypeParm, 0);
4832 }
4833 
4834 TypeSourceInfo *
4835 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4836                                               SourceLocation NameLoc,
4837                                         const TemplateArgumentListInfo &Args,
4838                                               QualType Underlying) const {
4839   assert(!Name.getAsDependentTemplateName() &&
4840          "No dependent template names here!");
4841   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4842 
4843   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4844   TemplateSpecializationTypeLoc TL =
4845       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4846   TL.setTemplateKeywordLoc(SourceLocation());
4847   TL.setTemplateNameLoc(NameLoc);
4848   TL.setLAngleLoc(Args.getLAngleLoc());
4849   TL.setRAngleLoc(Args.getRAngleLoc());
4850   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4851     TL.setArgLocInfo(i, Args[i].getLocInfo());
4852   return DI;
4853 }
4854 
4855 QualType
4856 ASTContext::getTemplateSpecializationType(TemplateName Template,
4857                                           const TemplateArgumentListInfo &Args,
4858                                           QualType Underlying) const {
4859   assert(!Template.getAsDependentTemplateName() &&
4860          "No dependent template names here!");
4861 
4862   SmallVector<TemplateArgument, 4> ArgVec;
4863   ArgVec.reserve(Args.size());
4864   for (const TemplateArgumentLoc &Arg : Args.arguments())
4865     ArgVec.push_back(Arg.getArgument());
4866 
4867   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4868 }
4869 
4870 #ifndef NDEBUG
4871 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4872   for (const TemplateArgument &Arg : Args)
4873     if (Arg.isPackExpansion())
4874       return true;
4875 
4876   return true;
4877 }
4878 #endif
4879 
4880 QualType
4881 ASTContext::getTemplateSpecializationType(TemplateName Template,
4882                                           ArrayRef<TemplateArgument> Args,
4883                                           QualType Underlying) const {
4884   assert(!Template.getAsDependentTemplateName() &&
4885          "No dependent template names here!");
4886   // Look through qualified template names.
4887   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4888     Template = QTN->getUnderlyingTemplate();
4889 
4890   bool IsTypeAlias =
4891       isa_and_nonnull<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4892   QualType CanonType;
4893   if (!Underlying.isNull())
4894     CanonType = getCanonicalType(Underlying);
4895   else {
4896     // We can get here with an alias template when the specialization contains
4897     // a pack expansion that does not match up with a parameter pack.
4898     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4899            "Caller must compute aliased type");
4900     IsTypeAlias = false;
4901     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4902   }
4903 
4904   // Allocate the (non-canonical) template specialization type, but don't
4905   // try to unique it: these types typically have location information that
4906   // we don't unique and don't want to lose.
4907   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4908                        sizeof(TemplateArgument) * Args.size() +
4909                        (IsTypeAlias? sizeof(QualType) : 0),
4910                        TypeAlignment);
4911   auto *Spec
4912     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4913                                          IsTypeAlias ? Underlying : QualType());
4914 
4915   Types.push_back(Spec);
4916   return QualType(Spec, 0);
4917 }
4918 
4919 static bool
4920 getCanonicalTemplateArguments(const ASTContext &C,
4921                               ArrayRef<TemplateArgument> OrigArgs,
4922                               SmallVectorImpl<TemplateArgument> &CanonArgs) {
4923   bool AnyNonCanonArgs = false;
4924   unsigned NumArgs = OrigArgs.size();
4925   CanonArgs.resize(NumArgs);
4926   for (unsigned I = 0; I != NumArgs; ++I) {
4927     const TemplateArgument &OrigArg = OrigArgs[I];
4928     TemplateArgument &CanonArg = CanonArgs[I];
4929     CanonArg = C.getCanonicalTemplateArgument(OrigArg);
4930     if (!CanonArg.structurallyEquals(OrigArg))
4931       AnyNonCanonArgs = true;
4932   }
4933   return AnyNonCanonArgs;
4934 }
4935 
4936 QualType ASTContext::getCanonicalTemplateSpecializationType(
4937     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4938   assert(!Template.getAsDependentTemplateName() &&
4939          "No dependent template names here!");
4940 
4941   // Look through qualified template names.
4942   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4943     Template = TemplateName(QTN->getUnderlyingTemplate());
4944 
4945   // Build the canonical template specialization type.
4946   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4947   SmallVector<TemplateArgument, 4> CanonArgs;
4948   ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
4949 
4950   // Determine whether this canonical template specialization type already
4951   // exists.
4952   llvm::FoldingSetNodeID ID;
4953   TemplateSpecializationType::Profile(ID, CanonTemplate,
4954                                       CanonArgs, *this);
4955 
4956   void *InsertPos = nullptr;
4957   TemplateSpecializationType *Spec
4958     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4959 
4960   if (!Spec) {
4961     // Allocate a new canonical template specialization type.
4962     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4963                           sizeof(TemplateArgument) * CanonArgs.size()),
4964                          TypeAlignment);
4965     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4966                                                 CanonArgs,
4967                                                 QualType(), QualType());
4968     Types.push_back(Spec);
4969     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4970   }
4971 
4972   assert(Spec->isDependentType() &&
4973          "Non-dependent template-id type must have a canonical type");
4974   return QualType(Spec, 0);
4975 }
4976 
4977 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4978                                        NestedNameSpecifier *NNS,
4979                                        QualType NamedType,
4980                                        TagDecl *OwnedTagDecl) const {
4981   llvm::FoldingSetNodeID ID;
4982   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4983 
4984   void *InsertPos = nullptr;
4985   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4986   if (T)
4987     return QualType(T, 0);
4988 
4989   QualType Canon = NamedType;
4990   if (!Canon.isCanonical()) {
4991     Canon = getCanonicalType(NamedType);
4992     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4993     assert(!CheckT && "Elaborated canonical type broken");
4994     (void)CheckT;
4995   }
4996 
4997   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4998                        TypeAlignment);
4999   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5000 
5001   Types.push_back(T);
5002   ElaboratedTypes.InsertNode(T, InsertPos);
5003   return QualType(T, 0);
5004 }
5005 
5006 QualType
5007 ASTContext::getParenType(QualType InnerType) const {
5008   llvm::FoldingSetNodeID ID;
5009   ParenType::Profile(ID, InnerType);
5010 
5011   void *InsertPos = nullptr;
5012   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5013   if (T)
5014     return QualType(T, 0);
5015 
5016   QualType Canon = InnerType;
5017   if (!Canon.isCanonical()) {
5018     Canon = getCanonicalType(InnerType);
5019     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5020     assert(!CheckT && "Paren canonical type broken");
5021     (void)CheckT;
5022   }
5023 
5024   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
5025   Types.push_back(T);
5026   ParenTypes.InsertNode(T, InsertPos);
5027   return QualType(T, 0);
5028 }
5029 
5030 QualType
5031 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5032                                   const IdentifierInfo *MacroII) const {
5033   QualType Canon = UnderlyingTy;
5034   if (!Canon.isCanonical())
5035     Canon = getCanonicalType(UnderlyingTy);
5036 
5037   auto *newType = new (*this, TypeAlignment)
5038       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5039   Types.push_back(newType);
5040   return QualType(newType, 0);
5041 }
5042 
5043 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5044                                           NestedNameSpecifier *NNS,
5045                                           const IdentifierInfo *Name,
5046                                           QualType Canon) const {
5047   if (Canon.isNull()) {
5048     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5049     if (CanonNNS != NNS)
5050       Canon = getDependentNameType(Keyword, CanonNNS, Name);
5051   }
5052 
5053   llvm::FoldingSetNodeID ID;
5054   DependentNameType::Profile(ID, Keyword, NNS, Name);
5055 
5056   void *InsertPos = nullptr;
5057   DependentNameType *T
5058     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5059   if (T)
5060     return QualType(T, 0);
5061 
5062   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
5063   Types.push_back(T);
5064   DependentNameTypes.InsertNode(T, InsertPos);
5065   return QualType(T, 0);
5066 }
5067 
5068 QualType
5069 ASTContext::getDependentTemplateSpecializationType(
5070                                  ElaboratedTypeKeyword Keyword,
5071                                  NestedNameSpecifier *NNS,
5072                                  const IdentifierInfo *Name,
5073                                  const TemplateArgumentListInfo &Args) const {
5074   // TODO: avoid this copy
5075   SmallVector<TemplateArgument, 16> ArgCopy;
5076   for (unsigned I = 0, E = Args.size(); I != E; ++I)
5077     ArgCopy.push_back(Args[I].getArgument());
5078   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5079 }
5080 
5081 QualType
5082 ASTContext::getDependentTemplateSpecializationType(
5083                                  ElaboratedTypeKeyword Keyword,
5084                                  NestedNameSpecifier *NNS,
5085                                  const IdentifierInfo *Name,
5086                                  ArrayRef<TemplateArgument> Args) const {
5087   assert((!NNS || NNS->isDependent()) &&
5088          "nested-name-specifier must be dependent");
5089 
5090   llvm::FoldingSetNodeID ID;
5091   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5092                                                Name, Args);
5093 
5094   void *InsertPos = nullptr;
5095   DependentTemplateSpecializationType *T
5096     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5097   if (T)
5098     return QualType(T, 0);
5099 
5100   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5101 
5102   ElaboratedTypeKeyword CanonKeyword = Keyword;
5103   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
5104 
5105   SmallVector<TemplateArgument, 16> CanonArgs;
5106   bool AnyNonCanonArgs =
5107       ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
5108 
5109   QualType Canon;
5110   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5111     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5112                                                    Name,
5113                                                    CanonArgs);
5114 
5115     // Find the insert position again.
5116     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5117   }
5118 
5119   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5120                         sizeof(TemplateArgument) * Args.size()),
5121                        TypeAlignment);
5122   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5123                                                     Name, Args, Canon);
5124   Types.push_back(T);
5125   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5126   return QualType(T, 0);
5127 }
5128 
5129 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5130   TemplateArgument Arg;
5131   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5132     QualType ArgType = getTypeDeclType(TTP);
5133     if (TTP->isParameterPack())
5134       ArgType = getPackExpansionType(ArgType, None);
5135 
5136     Arg = TemplateArgument(ArgType);
5137   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5138     QualType T =
5139         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5140     // For class NTTPs, ensure we include the 'const' so the type matches that
5141     // of a real template argument.
5142     // FIXME: It would be more faithful to model this as something like an
5143     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5144     if (T->isRecordType())
5145       T.addConst();
5146     Expr *E = new (*this) DeclRefExpr(
5147         *this, NTTP, /*enclosing*/ false, T,
5148         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5149 
5150     if (NTTP->isParameterPack())
5151       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
5152                                         None);
5153     Arg = TemplateArgument(E);
5154   } else {
5155     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5156     if (TTP->isParameterPack())
5157       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
5158     else
5159       Arg = TemplateArgument(TemplateName(TTP));
5160   }
5161 
5162   if (Param->isTemplateParameterPack())
5163     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5164 
5165   return Arg;
5166 }
5167 
5168 void
5169 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
5170                                     SmallVectorImpl<TemplateArgument> &Args) {
5171   Args.reserve(Args.size() + Params->size());
5172 
5173   for (NamedDecl *Param : *Params)
5174     Args.push_back(getInjectedTemplateArg(Param));
5175 }
5176 
5177 QualType ASTContext::getPackExpansionType(QualType Pattern,
5178                                           Optional<unsigned> NumExpansions,
5179                                           bool ExpectPackInType) {
5180   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5181          "Pack expansions must expand one or more parameter packs");
5182 
5183   llvm::FoldingSetNodeID ID;
5184   PackExpansionType::Profile(ID, Pattern, NumExpansions);
5185 
5186   void *InsertPos = nullptr;
5187   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5188   if (T)
5189     return QualType(T, 0);
5190 
5191   QualType Canon;
5192   if (!Pattern.isCanonical()) {
5193     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5194                                  /*ExpectPackInType=*/false);
5195 
5196     // Find the insert position again, in case we inserted an element into
5197     // PackExpansionTypes and invalidated our insert position.
5198     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5199   }
5200 
5201   T = new (*this, TypeAlignment)
5202       PackExpansionType(Pattern, Canon, NumExpansions);
5203   Types.push_back(T);
5204   PackExpansionTypes.InsertNode(T, InsertPos);
5205   return QualType(T, 0);
5206 }
5207 
5208 /// CmpProtocolNames - Comparison predicate for sorting protocols
5209 /// alphabetically.
5210 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5211                             ObjCProtocolDecl *const *RHS) {
5212   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5213 }
5214 
5215 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5216   if (Protocols.empty()) return true;
5217 
5218   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5219     return false;
5220 
5221   for (unsigned i = 1; i != Protocols.size(); ++i)
5222     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5223         Protocols[i]->getCanonicalDecl() != Protocols[i])
5224       return false;
5225   return true;
5226 }
5227 
5228 static void
5229 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5230   // Sort protocols, keyed by name.
5231   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5232 
5233   // Canonicalize.
5234   for (ObjCProtocolDecl *&P : Protocols)
5235     P = P->getCanonicalDecl();
5236 
5237   // Remove duplicates.
5238   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5239   Protocols.erase(ProtocolsEnd, Protocols.end());
5240 }
5241 
5242 QualType ASTContext::getObjCObjectType(QualType BaseType,
5243                                        ObjCProtocolDecl * const *Protocols,
5244                                        unsigned NumProtocols) const {
5245   return getObjCObjectType(BaseType, {},
5246                            llvm::makeArrayRef(Protocols, NumProtocols),
5247                            /*isKindOf=*/false);
5248 }
5249 
5250 QualType ASTContext::getObjCObjectType(
5251            QualType baseType,
5252            ArrayRef<QualType> typeArgs,
5253            ArrayRef<ObjCProtocolDecl *> protocols,
5254            bool isKindOf) const {
5255   // If the base type is an interface and there aren't any protocols or
5256   // type arguments to add, then the interface type will do just fine.
5257   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5258       isa<ObjCInterfaceType>(baseType))
5259     return baseType;
5260 
5261   // Look in the folding set for an existing type.
5262   llvm::FoldingSetNodeID ID;
5263   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5264   void *InsertPos = nullptr;
5265   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5266     return QualType(QT, 0);
5267 
5268   // Determine the type arguments to be used for canonicalization,
5269   // which may be explicitly specified here or written on the base
5270   // type.
5271   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5272   if (effectiveTypeArgs.empty()) {
5273     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5274       effectiveTypeArgs = baseObject->getTypeArgs();
5275   }
5276 
5277   // Build the canonical type, which has the canonical base type and a
5278   // sorted-and-uniqued list of protocols and the type arguments
5279   // canonicalized.
5280   QualType canonical;
5281   bool typeArgsAreCanonical = llvm::all_of(
5282       effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5283   bool protocolsSorted = areSortedAndUniqued(protocols);
5284   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5285     // Determine the canonical type arguments.
5286     ArrayRef<QualType> canonTypeArgs;
5287     SmallVector<QualType, 4> canonTypeArgsVec;
5288     if (!typeArgsAreCanonical) {
5289       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5290       for (auto typeArg : effectiveTypeArgs)
5291         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5292       canonTypeArgs = canonTypeArgsVec;
5293     } else {
5294       canonTypeArgs = effectiveTypeArgs;
5295     }
5296 
5297     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5298     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5299     if (!protocolsSorted) {
5300       canonProtocolsVec.append(protocols.begin(), protocols.end());
5301       SortAndUniqueProtocols(canonProtocolsVec);
5302       canonProtocols = canonProtocolsVec;
5303     } else {
5304       canonProtocols = protocols;
5305     }
5306 
5307     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5308                                   canonProtocols, isKindOf);
5309 
5310     // Regenerate InsertPos.
5311     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5312   }
5313 
5314   unsigned size = sizeof(ObjCObjectTypeImpl);
5315   size += typeArgs.size() * sizeof(QualType);
5316   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5317   void *mem = Allocate(size, TypeAlignment);
5318   auto *T =
5319     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5320                                  isKindOf);
5321 
5322   Types.push_back(T);
5323   ObjCObjectTypes.InsertNode(T, InsertPos);
5324   return QualType(T, 0);
5325 }
5326 
5327 /// Apply Objective-C protocol qualifiers to the given type.
5328 /// If this is for the canonical type of a type parameter, we can apply
5329 /// protocol qualifiers on the ObjCObjectPointerType.
5330 QualType
5331 ASTContext::applyObjCProtocolQualifiers(QualType type,
5332                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5333                   bool allowOnPointerType) const {
5334   hasError = false;
5335 
5336   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5337     return getObjCTypeParamType(objT->getDecl(), protocols);
5338   }
5339 
5340   // Apply protocol qualifiers to ObjCObjectPointerType.
5341   if (allowOnPointerType) {
5342     if (const auto *objPtr =
5343             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5344       const ObjCObjectType *objT = objPtr->getObjectType();
5345       // Merge protocol lists and construct ObjCObjectType.
5346       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5347       protocolsVec.append(objT->qual_begin(),
5348                           objT->qual_end());
5349       protocolsVec.append(protocols.begin(), protocols.end());
5350       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5351       type = getObjCObjectType(
5352              objT->getBaseType(),
5353              objT->getTypeArgsAsWritten(),
5354              protocols,
5355              objT->isKindOfTypeAsWritten());
5356       return getObjCObjectPointerType(type);
5357     }
5358   }
5359 
5360   // Apply protocol qualifiers to ObjCObjectType.
5361   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5362     // FIXME: Check for protocols to which the class type is already
5363     // known to conform.
5364 
5365     return getObjCObjectType(objT->getBaseType(),
5366                              objT->getTypeArgsAsWritten(),
5367                              protocols,
5368                              objT->isKindOfTypeAsWritten());
5369   }
5370 
5371   // If the canonical type is ObjCObjectType, ...
5372   if (type->isObjCObjectType()) {
5373     // Silently overwrite any existing protocol qualifiers.
5374     // TODO: determine whether that's the right thing to do.
5375 
5376     // FIXME: Check for protocols to which the class type is already
5377     // known to conform.
5378     return getObjCObjectType(type, {}, protocols, false);
5379   }
5380 
5381   // id<protocol-list>
5382   if (type->isObjCIdType()) {
5383     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5384     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5385                                  objPtr->isKindOfType());
5386     return getObjCObjectPointerType(type);
5387   }
5388 
5389   // Class<protocol-list>
5390   if (type->isObjCClassType()) {
5391     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5392     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5393                                  objPtr->isKindOfType());
5394     return getObjCObjectPointerType(type);
5395   }
5396 
5397   hasError = true;
5398   return type;
5399 }
5400 
5401 QualType
5402 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5403                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5404   // Look in the folding set for an existing type.
5405   llvm::FoldingSetNodeID ID;
5406   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5407   void *InsertPos = nullptr;
5408   if (ObjCTypeParamType *TypeParam =
5409       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5410     return QualType(TypeParam, 0);
5411 
5412   // We canonicalize to the underlying type.
5413   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5414   if (!protocols.empty()) {
5415     // Apply the protocol qualifers.
5416     bool hasError;
5417     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5418         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5419     assert(!hasError && "Error when apply protocol qualifier to bound type");
5420   }
5421 
5422   unsigned size = sizeof(ObjCTypeParamType);
5423   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5424   void *mem = Allocate(size, TypeAlignment);
5425   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5426 
5427   Types.push_back(newType);
5428   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5429   return QualType(newType, 0);
5430 }
5431 
5432 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5433                                               ObjCTypeParamDecl *New) const {
5434   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5435   // Update TypeForDecl after updating TypeSourceInfo.
5436   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5437   SmallVector<ObjCProtocolDecl *, 8> protocols;
5438   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5439   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5440   New->setTypeForDecl(UpdatedTy.getTypePtr());
5441 }
5442 
5443 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5444 /// protocol list adopt all protocols in QT's qualified-id protocol
5445 /// list.
5446 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5447                                                 ObjCInterfaceDecl *IC) {
5448   if (!QT->isObjCQualifiedIdType())
5449     return false;
5450 
5451   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5452     // If both the right and left sides have qualifiers.
5453     for (auto *Proto : OPT->quals()) {
5454       if (!IC->ClassImplementsProtocol(Proto, false))
5455         return false;
5456     }
5457     return true;
5458   }
5459   return false;
5460 }
5461 
5462 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5463 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5464 /// of protocols.
5465 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5466                                                 ObjCInterfaceDecl *IDecl) {
5467   if (!QT->isObjCQualifiedIdType())
5468     return false;
5469   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5470   if (!OPT)
5471     return false;
5472   if (!IDecl->hasDefinition())
5473     return false;
5474   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5475   CollectInheritedProtocols(IDecl, InheritedProtocols);
5476   if (InheritedProtocols.empty())
5477     return false;
5478   // Check that if every protocol in list of id<plist> conforms to a protocol
5479   // of IDecl's, then bridge casting is ok.
5480   bool Conforms = false;
5481   for (auto *Proto : OPT->quals()) {
5482     Conforms = false;
5483     for (auto *PI : InheritedProtocols) {
5484       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5485         Conforms = true;
5486         break;
5487       }
5488     }
5489     if (!Conforms)
5490       break;
5491   }
5492   if (Conforms)
5493     return true;
5494 
5495   for (auto *PI : InheritedProtocols) {
5496     // If both the right and left sides have qualifiers.
5497     bool Adopts = false;
5498     for (auto *Proto : OPT->quals()) {
5499       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5500       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5501         break;
5502     }
5503     if (!Adopts)
5504       return false;
5505   }
5506   return true;
5507 }
5508 
5509 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5510 /// the given object type.
5511 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5512   llvm::FoldingSetNodeID ID;
5513   ObjCObjectPointerType::Profile(ID, ObjectT);
5514 
5515   void *InsertPos = nullptr;
5516   if (ObjCObjectPointerType *QT =
5517               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5518     return QualType(QT, 0);
5519 
5520   // Find the canonical object type.
5521   QualType Canonical;
5522   if (!ObjectT.isCanonical()) {
5523     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5524 
5525     // Regenerate InsertPos.
5526     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5527   }
5528 
5529   // No match.
5530   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5531   auto *QType =
5532     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5533 
5534   Types.push_back(QType);
5535   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5536   return QualType(QType, 0);
5537 }
5538 
5539 /// getObjCInterfaceType - Return the unique reference to the type for the
5540 /// specified ObjC interface decl. The list of protocols is optional.
5541 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5542                                           ObjCInterfaceDecl *PrevDecl) const {
5543   if (Decl->TypeForDecl)
5544     return QualType(Decl->TypeForDecl, 0);
5545 
5546   if (PrevDecl) {
5547     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5548     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5549     return QualType(PrevDecl->TypeForDecl, 0);
5550   }
5551 
5552   // Prefer the definition, if there is one.
5553   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5554     Decl = Def;
5555 
5556   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5557   auto *T = new (Mem) ObjCInterfaceType(Decl);
5558   Decl->TypeForDecl = T;
5559   Types.push_back(T);
5560   return QualType(T, 0);
5561 }
5562 
5563 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5564 /// TypeOfExprType AST's (since expression's are never shared). For example,
5565 /// multiple declarations that refer to "typeof(x)" all contain different
5566 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5567 /// on canonical type's (which are always unique).
5568 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5569   TypeOfExprType *toe;
5570   if (tofExpr->isTypeDependent()) {
5571     llvm::FoldingSetNodeID ID;
5572     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5573 
5574     void *InsertPos = nullptr;
5575     DependentTypeOfExprType *Canon
5576       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5577     if (Canon) {
5578       // We already have a "canonical" version of an identical, dependent
5579       // typeof(expr) type. Use that as our canonical type.
5580       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5581                                           QualType((TypeOfExprType*)Canon, 0));
5582     } else {
5583       // Build a new, canonical typeof(expr) type.
5584       Canon
5585         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5586       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5587       toe = Canon;
5588     }
5589   } else {
5590     QualType Canonical = getCanonicalType(tofExpr->getType());
5591     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5592   }
5593   Types.push_back(toe);
5594   return QualType(toe, 0);
5595 }
5596 
5597 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5598 /// TypeOfType nodes. The only motivation to unique these nodes would be
5599 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5600 /// an issue. This doesn't affect the type checker, since it operates
5601 /// on canonical types (which are always unique).
5602 QualType ASTContext::getTypeOfType(QualType tofType) const {
5603   QualType Canonical = getCanonicalType(tofType);
5604   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5605   Types.push_back(tot);
5606   return QualType(tot, 0);
5607 }
5608 
5609 /// getReferenceQualifiedType - Given an expr, will return the type for
5610 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5611 /// and class member access into account.
5612 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
5613   // C++11 [dcl.type.simple]p4:
5614   //   [...]
5615   QualType T = E->getType();
5616   switch (E->getValueKind()) {
5617   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5618   //       type of e;
5619   case VK_XValue:
5620     return getRValueReferenceType(T);
5621   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5622   //       type of e;
5623   case VK_LValue:
5624     return getLValueReferenceType(T);
5625   //  - otherwise, decltype(e) is the type of e.
5626   case VK_PRValue:
5627     return T;
5628   }
5629   llvm_unreachable("Unknown value kind");
5630 }
5631 
5632 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5633 /// nodes. This would never be helpful, since each such type has its own
5634 /// expression, and would not give a significant memory saving, since there
5635 /// is an Expr tree under each such type.
5636 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5637   DecltypeType *dt;
5638 
5639   // C++11 [temp.type]p2:
5640   //   If an expression e involves a template parameter, decltype(e) denotes a
5641   //   unique dependent type. Two such decltype-specifiers refer to the same
5642   //   type only if their expressions are equivalent (14.5.6.1).
5643   if (e->isInstantiationDependent()) {
5644     llvm::FoldingSetNodeID ID;
5645     DependentDecltypeType::Profile(ID, *this, e);
5646 
5647     void *InsertPos = nullptr;
5648     DependentDecltypeType *Canon
5649       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5650     if (!Canon) {
5651       // Build a new, canonical decltype(expr) type.
5652       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5653       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5654     }
5655     dt = new (*this, TypeAlignment)
5656         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5657   } else {
5658     dt = new (*this, TypeAlignment)
5659         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5660   }
5661   Types.push_back(dt);
5662   return QualType(dt, 0);
5663 }
5664 
5665 /// getUnaryTransformationType - We don't unique these, since the memory
5666 /// savings are minimal and these are rare.
5667 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5668                                            QualType UnderlyingType,
5669                                            UnaryTransformType::UTTKind Kind)
5670     const {
5671   UnaryTransformType *ut = nullptr;
5672 
5673   if (BaseType->isDependentType()) {
5674     // Look in the folding set for an existing type.
5675     llvm::FoldingSetNodeID ID;
5676     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5677 
5678     void *InsertPos = nullptr;
5679     DependentUnaryTransformType *Canon
5680       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5681 
5682     if (!Canon) {
5683       // Build a new, canonical __underlying_type(type) type.
5684       Canon = new (*this, TypeAlignment)
5685              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5686                                          Kind);
5687       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5688     }
5689     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5690                                                         QualType(), Kind,
5691                                                         QualType(Canon, 0));
5692   } else {
5693     QualType CanonType = getCanonicalType(UnderlyingType);
5694     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5695                                                         UnderlyingType, Kind,
5696                                                         CanonType);
5697   }
5698   Types.push_back(ut);
5699   return QualType(ut, 0);
5700 }
5701 
5702 QualType ASTContext::getAutoTypeInternal(
5703     QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5704     bool IsPack, ConceptDecl *TypeConstraintConcept,
5705     ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5706   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5707       !TypeConstraintConcept && !IsDependent)
5708     return getAutoDeductType();
5709 
5710   if (TypeConstraintConcept)
5711     TypeConstraintConcept = TypeConstraintConcept->getCanonicalDecl();
5712 
5713   // Look in the folding set for an existing type.
5714   void *InsertPos = nullptr;
5715   llvm::FoldingSetNodeID ID;
5716   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5717                     TypeConstraintConcept, TypeConstraintArgs);
5718   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5719     return QualType(AT, 0);
5720 
5721   QualType Canon;
5722   if (!IsCanon) {
5723     if (DeducedType.isNull()) {
5724       SmallVector<TemplateArgument, 4> CanonArgs;
5725       bool AnyNonCanonArgs =
5726           ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs);
5727       if (AnyNonCanonArgs) {
5728         Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5729                                     TypeConstraintConcept, CanonArgs, true);
5730         // Find the insert position again.
5731         AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5732       }
5733     } else {
5734       Canon = DeducedType.getCanonicalType();
5735     }
5736   }
5737 
5738   void *Mem = Allocate(sizeof(AutoType) +
5739                            sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5740                        TypeAlignment);
5741   auto *AT = new (Mem) AutoType(
5742       DeducedType, Keyword,
5743       (IsDependent ? TypeDependence::DependentInstantiation
5744                    : TypeDependence::None) |
5745           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5746       Canon, TypeConstraintConcept, TypeConstraintArgs);
5747   Types.push_back(AT);
5748   AutoTypes.InsertNode(AT, InsertPos);
5749   return QualType(AT, 0);
5750 }
5751 
5752 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5753 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5754 /// canonical deduced-but-dependent 'auto' type.
5755 QualType
5756 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5757                         bool IsDependent, bool IsPack,
5758                         ConceptDecl *TypeConstraintConcept,
5759                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5760   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5761   assert((!IsDependent || DeducedType.isNull()) &&
5762          "A dependent auto should be undeduced");
5763   return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5764                              TypeConstraintConcept, TypeConstraintArgs);
5765 }
5766 
5767 /// Return the uniqued reference to the deduced template specialization type
5768 /// which has been deduced to the given type, or to the canonical undeduced
5769 /// such type, or the canonical deduced-but-dependent such type.
5770 QualType ASTContext::getDeducedTemplateSpecializationType(
5771     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5772   // Look in the folding set for an existing type.
5773   void *InsertPos = nullptr;
5774   llvm::FoldingSetNodeID ID;
5775   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5776                                              IsDependent);
5777   if (DeducedTemplateSpecializationType *DTST =
5778           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5779     return QualType(DTST, 0);
5780 
5781   auto *DTST = new (*this, TypeAlignment)
5782       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5783   llvm::FoldingSetNodeID TempID;
5784   DTST->Profile(TempID);
5785   assert(ID == TempID && "ID does not match");
5786   Types.push_back(DTST);
5787   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5788   return QualType(DTST, 0);
5789 }
5790 
5791 /// getAtomicType - Return the uniqued reference to the atomic type for
5792 /// the given value type.
5793 QualType ASTContext::getAtomicType(QualType T) const {
5794   // Unique pointers, to guarantee there is only one pointer of a particular
5795   // structure.
5796   llvm::FoldingSetNodeID ID;
5797   AtomicType::Profile(ID, T);
5798 
5799   void *InsertPos = nullptr;
5800   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5801     return QualType(AT, 0);
5802 
5803   // If the atomic value type isn't canonical, this won't be a canonical type
5804   // either, so fill in the canonical type field.
5805   QualType Canonical;
5806   if (!T.isCanonical()) {
5807     Canonical = getAtomicType(getCanonicalType(T));
5808 
5809     // Get the new insert position for the node we care about.
5810     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5811     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5812   }
5813   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5814   Types.push_back(New);
5815   AtomicTypes.InsertNode(New, InsertPos);
5816   return QualType(New, 0);
5817 }
5818 
5819 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5820 QualType ASTContext::getAutoDeductType() const {
5821   if (AutoDeductTy.isNull())
5822     AutoDeductTy = QualType(new (*this, TypeAlignment)
5823                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5824                                          TypeDependence::None, QualType(),
5825                                          /*concept*/ nullptr, /*args*/ {}),
5826                             0);
5827   return AutoDeductTy;
5828 }
5829 
5830 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5831 QualType ASTContext::getAutoRRefDeductType() const {
5832   if (AutoRRefDeductTy.isNull())
5833     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5834   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5835   return AutoRRefDeductTy;
5836 }
5837 
5838 /// getTagDeclType - Return the unique reference to the type for the
5839 /// specified TagDecl (struct/union/class/enum) decl.
5840 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5841   assert(Decl);
5842   // FIXME: What is the design on getTagDeclType when it requires casting
5843   // away const?  mutable?
5844   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5845 }
5846 
5847 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5848 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5849 /// needs to agree with the definition in <stddef.h>.
5850 CanQualType ASTContext::getSizeType() const {
5851   return getFromTargetType(Target->getSizeType());
5852 }
5853 
5854 /// Return the unique signed counterpart of the integer type
5855 /// corresponding to size_t.
5856 CanQualType ASTContext::getSignedSizeType() const {
5857   return getFromTargetType(Target->getSignedSizeType());
5858 }
5859 
5860 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5861 CanQualType ASTContext::getIntMaxType() const {
5862   return getFromTargetType(Target->getIntMaxType());
5863 }
5864 
5865 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5866 CanQualType ASTContext::getUIntMaxType() const {
5867   return getFromTargetType(Target->getUIntMaxType());
5868 }
5869 
5870 /// getSignedWCharType - Return the type of "signed wchar_t".
5871 /// Used when in C++, as a GCC extension.
5872 QualType ASTContext::getSignedWCharType() const {
5873   // FIXME: derive from "Target" ?
5874   return WCharTy;
5875 }
5876 
5877 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5878 /// Used when in C++, as a GCC extension.
5879 QualType ASTContext::getUnsignedWCharType() const {
5880   // FIXME: derive from "Target" ?
5881   return UnsignedIntTy;
5882 }
5883 
5884 QualType ASTContext::getIntPtrType() const {
5885   return getFromTargetType(Target->getIntPtrType());
5886 }
5887 
5888 QualType ASTContext::getUIntPtrType() const {
5889   return getCorrespondingUnsignedType(getIntPtrType());
5890 }
5891 
5892 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5893 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5894 QualType ASTContext::getPointerDiffType() const {
5895   return getFromTargetType(Target->getPtrDiffType(0));
5896 }
5897 
5898 /// Return the unique unsigned counterpart of "ptrdiff_t"
5899 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5900 /// in the definition of %tu format specifier.
5901 QualType ASTContext::getUnsignedPointerDiffType() const {
5902   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5903 }
5904 
5905 /// Return the unique type for "pid_t" defined in
5906 /// <sys/types.h>. We need this to compute the correct type for vfork().
5907 QualType ASTContext::getProcessIDType() const {
5908   return getFromTargetType(Target->getProcessIDType());
5909 }
5910 
5911 //===----------------------------------------------------------------------===//
5912 //                              Type Operators
5913 //===----------------------------------------------------------------------===//
5914 
5915 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5916   // Push qualifiers into arrays, and then discard any remaining
5917   // qualifiers.
5918   T = getCanonicalType(T);
5919   T = getVariableArrayDecayedType(T);
5920   const Type *Ty = T.getTypePtr();
5921   QualType Result;
5922   if (isa<ArrayType>(Ty)) {
5923     Result = getArrayDecayedType(QualType(Ty,0));
5924   } else if (isa<FunctionType>(Ty)) {
5925     Result = getPointerType(QualType(Ty, 0));
5926   } else {
5927     Result = QualType(Ty, 0);
5928   }
5929 
5930   return CanQualType::CreateUnsafe(Result);
5931 }
5932 
5933 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5934                                              Qualifiers &quals) {
5935   SplitQualType splitType = type.getSplitUnqualifiedType();
5936 
5937   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5938   // the unqualified desugared type and then drops it on the floor.
5939   // We then have to strip that sugar back off with
5940   // getUnqualifiedDesugaredType(), which is silly.
5941   const auto *AT =
5942       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5943 
5944   // If we don't have an array, just use the results in splitType.
5945   if (!AT) {
5946     quals = splitType.Quals;
5947     return QualType(splitType.Ty, 0);
5948   }
5949 
5950   // Otherwise, recurse on the array's element type.
5951   QualType elementType = AT->getElementType();
5952   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5953 
5954   // If that didn't change the element type, AT has no qualifiers, so we
5955   // can just use the results in splitType.
5956   if (elementType == unqualElementType) {
5957     assert(quals.empty()); // from the recursive call
5958     quals = splitType.Quals;
5959     return QualType(splitType.Ty, 0);
5960   }
5961 
5962   // Otherwise, add in the qualifiers from the outermost type, then
5963   // build the type back up.
5964   quals.addConsistentQualifiers(splitType.Quals);
5965 
5966   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5967     return getConstantArrayType(unqualElementType, CAT->getSize(),
5968                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5969   }
5970 
5971   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5972     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5973   }
5974 
5975   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5976     return getVariableArrayType(unqualElementType,
5977                                 VAT->getSizeExpr(),
5978                                 VAT->getSizeModifier(),
5979                                 VAT->getIndexTypeCVRQualifiers(),
5980                                 VAT->getBracketsRange());
5981   }
5982 
5983   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5984   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5985                                     DSAT->getSizeModifier(), 0,
5986                                     SourceRange());
5987 }
5988 
5989 /// Attempt to unwrap two types that may both be array types with the same bound
5990 /// (or both be array types of unknown bound) for the purpose of comparing the
5991 /// cv-decomposition of two types per C++ [conv.qual].
5992 ///
5993 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
5994 ///        C++20 [conv.qual], if permitted by the current language mode.
5995 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
5996                                          bool AllowPiMismatch) {
5997   while (true) {
5998     auto *AT1 = getAsArrayType(T1);
5999     if (!AT1)
6000       return;
6001 
6002     auto *AT2 = getAsArrayType(T2);
6003     if (!AT2)
6004       return;
6005 
6006     // If we don't have two array types with the same constant bound nor two
6007     // incomplete array types, we've unwrapped everything we can.
6008     // C++20 also permits one type to be a constant array type and the other
6009     // to be an incomplete array type.
6010     // FIXME: Consider also unwrapping array of unknown bound and VLA.
6011     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6012       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6013       if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6014             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6015              isa<IncompleteArrayType>(AT2))))
6016         return;
6017     } else if (isa<IncompleteArrayType>(AT1)) {
6018       if (!(isa<IncompleteArrayType>(AT2) ||
6019             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6020              isa<ConstantArrayType>(AT2))))
6021         return;
6022     } else {
6023       return;
6024     }
6025 
6026     T1 = AT1->getElementType();
6027     T2 = AT2->getElementType();
6028   }
6029 }
6030 
6031 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6032 ///
6033 /// If T1 and T2 are both pointer types of the same kind, or both array types
6034 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6035 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6036 ///
6037 /// This function will typically be called in a loop that successively
6038 /// "unwraps" pointer and pointer-to-member types to compare them at each
6039 /// level.
6040 ///
6041 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6042 ///        C++20 [conv.qual], if permitted by the current language mode.
6043 ///
6044 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
6045 /// pair of types that can't be unwrapped further.
6046 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
6047                                     bool AllowPiMismatch) {
6048   UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6049 
6050   const auto *T1PtrType = T1->getAs<PointerType>();
6051   const auto *T2PtrType = T2->getAs<PointerType>();
6052   if (T1PtrType && T2PtrType) {
6053     T1 = T1PtrType->getPointeeType();
6054     T2 = T2PtrType->getPointeeType();
6055     return true;
6056   }
6057 
6058   const auto *T1MPType = T1->getAs<MemberPointerType>();
6059   const auto *T2MPType = T2->getAs<MemberPointerType>();
6060   if (T1MPType && T2MPType &&
6061       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6062                              QualType(T2MPType->getClass(), 0))) {
6063     T1 = T1MPType->getPointeeType();
6064     T2 = T2MPType->getPointeeType();
6065     return true;
6066   }
6067 
6068   if (getLangOpts().ObjC) {
6069     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6070     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6071     if (T1OPType && T2OPType) {
6072       T1 = T1OPType->getPointeeType();
6073       T2 = T2OPType->getPointeeType();
6074       return true;
6075     }
6076   }
6077 
6078   // FIXME: Block pointers, too?
6079 
6080   return false;
6081 }
6082 
6083 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
6084   while (true) {
6085     Qualifiers Quals;
6086     T1 = getUnqualifiedArrayType(T1, Quals);
6087     T2 = getUnqualifiedArrayType(T2, Quals);
6088     if (hasSameType(T1, T2))
6089       return true;
6090     if (!UnwrapSimilarTypes(T1, T2))
6091       return false;
6092   }
6093 }
6094 
6095 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
6096   while (true) {
6097     Qualifiers Quals1, Quals2;
6098     T1 = getUnqualifiedArrayType(T1, Quals1);
6099     T2 = getUnqualifiedArrayType(T2, Quals2);
6100 
6101     Quals1.removeCVRQualifiers();
6102     Quals2.removeCVRQualifiers();
6103     if (Quals1 != Quals2)
6104       return false;
6105 
6106     if (hasSameType(T1, T2))
6107       return true;
6108 
6109     if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6110       return false;
6111   }
6112 }
6113 
6114 DeclarationNameInfo
6115 ASTContext::getNameForTemplate(TemplateName Name,
6116                                SourceLocation NameLoc) const {
6117   switch (Name.getKind()) {
6118   case TemplateName::QualifiedTemplate:
6119   case TemplateName::Template:
6120     // DNInfo work in progress: CHECKME: what about DNLoc?
6121     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6122                                NameLoc);
6123 
6124   case TemplateName::OverloadedTemplate: {
6125     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6126     // DNInfo work in progress: CHECKME: what about DNLoc?
6127     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6128   }
6129 
6130   case TemplateName::AssumedTemplate: {
6131     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6132     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6133   }
6134 
6135   case TemplateName::DependentTemplate: {
6136     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6137     DeclarationName DName;
6138     if (DTN->isIdentifier()) {
6139       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
6140       return DeclarationNameInfo(DName, NameLoc);
6141     } else {
6142       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
6143       // DNInfo work in progress: FIXME: source locations?
6144       DeclarationNameLoc DNLoc =
6145           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
6146       return DeclarationNameInfo(DName, NameLoc, DNLoc);
6147     }
6148   }
6149 
6150   case TemplateName::SubstTemplateTemplateParm: {
6151     SubstTemplateTemplateParmStorage *subst
6152       = Name.getAsSubstTemplateTemplateParm();
6153     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6154                                NameLoc);
6155   }
6156 
6157   case TemplateName::SubstTemplateTemplateParmPack: {
6158     SubstTemplateTemplateParmPackStorage *subst
6159       = Name.getAsSubstTemplateTemplateParmPack();
6160     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
6161                                NameLoc);
6162   }
6163   case TemplateName::UsingTemplate:
6164     return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6165                                NameLoc);
6166   }
6167 
6168   llvm_unreachable("bad template name kind!");
6169 }
6170 
6171 TemplateName
6172 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
6173   switch (Name.getKind()) {
6174   case TemplateName::UsingTemplate:
6175   case TemplateName::QualifiedTemplate:
6176   case TemplateName::Template: {
6177     TemplateDecl *Template = Name.getAsTemplateDecl();
6178     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
6179       Template = getCanonicalTemplateTemplateParmDecl(TTP);
6180 
6181     // The canonical template name is the canonical template declaration.
6182     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6183   }
6184 
6185   case TemplateName::OverloadedTemplate:
6186   case TemplateName::AssumedTemplate:
6187     llvm_unreachable("cannot canonicalize unresolved template");
6188 
6189   case TemplateName::DependentTemplate: {
6190     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6191     assert(DTN && "Non-dependent template names must refer to template decls.");
6192     return DTN->CanonicalTemplateName;
6193   }
6194 
6195   case TemplateName::SubstTemplateTemplateParm: {
6196     SubstTemplateTemplateParmStorage *subst
6197       = Name.getAsSubstTemplateTemplateParm();
6198     return getCanonicalTemplateName(subst->getReplacement());
6199   }
6200 
6201   case TemplateName::SubstTemplateTemplateParmPack: {
6202     SubstTemplateTemplateParmPackStorage *subst
6203                                   = Name.getAsSubstTemplateTemplateParmPack();
6204     TemplateTemplateParmDecl *canonParameter
6205       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
6206     TemplateArgument canonArgPack
6207       = getCanonicalTemplateArgument(subst->getArgumentPack());
6208     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
6209   }
6210   }
6211 
6212   llvm_unreachable("bad template name!");
6213 }
6214 
6215 bool ASTContext::hasSameTemplateName(const TemplateName &X,
6216                                      const TemplateName &Y) const {
6217   return getCanonicalTemplateName(X).getAsVoidPointer() ==
6218          getCanonicalTemplateName(Y).getAsVoidPointer();
6219 }
6220 
6221 bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
6222                                          const NamedDecl *Y) const {
6223   if (X->getKind() != Y->getKind())
6224     return false;
6225 
6226   if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6227     auto *TY = cast<TemplateTypeParmDecl>(Y);
6228     if (TX->isParameterPack() != TY->isParameterPack())
6229       return false;
6230     if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6231       return false;
6232     const TypeConstraint *TXTC = TX->getTypeConstraint();
6233     const TypeConstraint *TYTC = TY->getTypeConstraint();
6234     if (!TXTC != !TYTC)
6235       return false;
6236     if (TXTC && TYTC) {
6237       auto *NCX = TXTC->getNamedConcept();
6238       auto *NCY = TYTC->getNamedConcept();
6239       if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6240         return false;
6241       if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
6242         return false;
6243       if (TXTC->hasExplicitTemplateArgs()) {
6244         auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
6245         auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
6246         if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
6247           return false;
6248         llvm::FoldingSetNodeID XID, YID;
6249         for (auto &ArgLoc : TXTCArgs->arguments())
6250           ArgLoc.getArgument().Profile(XID, X->getASTContext());
6251         for (auto &ArgLoc : TYTCArgs->arguments())
6252           ArgLoc.getArgument().Profile(YID, Y->getASTContext());
6253         if (XID != YID)
6254           return false;
6255       }
6256     }
6257     return true;
6258   }
6259 
6260   if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6261     auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6262     return TX->isParameterPack() == TY->isParameterPack() &&
6263            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
6264   }
6265 
6266   auto *TX = cast<TemplateTemplateParmDecl>(X);
6267   auto *TY = cast<TemplateTemplateParmDecl>(Y);
6268   return TX->isParameterPack() == TY->isParameterPack() &&
6269          isSameTemplateParameterList(TX->getTemplateParameters(),
6270                                      TY->getTemplateParameters());
6271 }
6272 
6273 bool ASTContext::isSameTemplateParameterList(
6274     const TemplateParameterList *X, const TemplateParameterList *Y) const {
6275   if (X->size() != Y->size())
6276     return false;
6277 
6278   for (unsigned I = 0, N = X->size(); I != N; ++I)
6279     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6280       return false;
6281 
6282   const Expr *XRC = X->getRequiresClause();
6283   const Expr *YRC = Y->getRequiresClause();
6284   if (!XRC != !YRC)
6285     return false;
6286   if (XRC) {
6287     llvm::FoldingSetNodeID XRCID, YRCID;
6288     XRC->Profile(XRCID, *this, /*Canonical=*/true);
6289     YRC->Profile(YRCID, *this, /*Canonical=*/true);
6290     if (XRCID != YRCID)
6291       return false;
6292   }
6293 
6294   return true;
6295 }
6296 
6297 bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
6298                                                const NamedDecl *Y) const {
6299   // If the type parameter isn't the same already, we don't need to check the
6300   // default argument further.
6301   if (!isSameTemplateParameter(X, Y))
6302     return false;
6303 
6304   if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6305     auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6306     if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6307       return false;
6308 
6309     return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
6310   }
6311 
6312   if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6313     auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6314     if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6315       return false;
6316 
6317     Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
6318     Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
6319     llvm::FoldingSetNodeID XID, YID;
6320     DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6321     DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6322     return XID == YID;
6323   }
6324 
6325   auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6326   auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6327 
6328   if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6329     return false;
6330 
6331   const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6332   const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6333   return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6334 }
6335 
6336 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
6337   if (auto *NS = X->getAsNamespace())
6338     return NS;
6339   if (auto *NAS = X->getAsNamespaceAlias())
6340     return NAS->getNamespace();
6341   return nullptr;
6342 }
6343 
6344 static bool isSameQualifier(const NestedNameSpecifier *X,
6345                             const NestedNameSpecifier *Y) {
6346   if (auto *NSX = getNamespace(X)) {
6347     auto *NSY = getNamespace(Y);
6348     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6349       return false;
6350   } else if (X->getKind() != Y->getKind())
6351     return false;
6352 
6353   // FIXME: For namespaces and types, we're permitted to check that the entity
6354   // is named via the same tokens. We should probably do so.
6355   switch (X->getKind()) {
6356   case NestedNameSpecifier::Identifier:
6357     if (X->getAsIdentifier() != Y->getAsIdentifier())
6358       return false;
6359     break;
6360   case NestedNameSpecifier::Namespace:
6361   case NestedNameSpecifier::NamespaceAlias:
6362     // We've already checked that we named the same namespace.
6363     break;
6364   case NestedNameSpecifier::TypeSpec:
6365   case NestedNameSpecifier::TypeSpecWithTemplate:
6366     if (X->getAsType()->getCanonicalTypeInternal() !=
6367         Y->getAsType()->getCanonicalTypeInternal())
6368       return false;
6369     break;
6370   case NestedNameSpecifier::Global:
6371   case NestedNameSpecifier::Super:
6372     return true;
6373   }
6374 
6375   // Recurse into earlier portion of NNS, if any.
6376   auto *PX = X->getPrefix();
6377   auto *PY = Y->getPrefix();
6378   if (PX && PY)
6379     return isSameQualifier(PX, PY);
6380   return !PX && !PY;
6381 }
6382 
6383 /// Determine whether the attributes we can overload on are identical for A and
6384 /// B. Will ignore any overloadable attrs represented in the type of A and B.
6385 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
6386                                      const FunctionDecl *B) {
6387   // Note that pass_object_size attributes are represented in the function's
6388   // ExtParameterInfo, so we don't need to check them here.
6389 
6390   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6391   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6392   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6393 
6394   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6395     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6396     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6397 
6398     // Return false if the number of enable_if attributes is different.
6399     if (!Cand1A || !Cand2A)
6400       return false;
6401 
6402     Cand1ID.clear();
6403     Cand2ID.clear();
6404 
6405     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6406     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6407 
6408     // Return false if any of the enable_if expressions of A and B are
6409     // different.
6410     if (Cand1ID != Cand2ID)
6411       return false;
6412   }
6413   return true;
6414 }
6415 
6416 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6417   if (X == Y)
6418     return true;
6419 
6420   if (X->getDeclName() != Y->getDeclName())
6421     return false;
6422 
6423   // Must be in the same context.
6424   //
6425   // Note that we can't use DeclContext::Equals here, because the DeclContexts
6426   // could be two different declarations of the same function. (We will fix the
6427   // semantic DC to refer to the primary definition after merging.)
6428   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6429                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6430     return false;
6431 
6432   // Two typedefs refer to the same entity if they have the same underlying
6433   // type.
6434   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6435     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6436       return hasSameType(TypedefX->getUnderlyingType(),
6437                          TypedefY->getUnderlyingType());
6438 
6439   // Must have the same kind.
6440   if (X->getKind() != Y->getKind())
6441     return false;
6442 
6443   // Objective-C classes and protocols with the same name always match.
6444   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6445     return true;
6446 
6447   if (isa<ClassTemplateSpecializationDecl>(X)) {
6448     // No need to handle these here: we merge them when adding them to the
6449     // template.
6450     return false;
6451   }
6452 
6453   // Compatible tags match.
6454   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6455     const auto *TagY = cast<TagDecl>(Y);
6456     return (TagX->getTagKind() == TagY->getTagKind()) ||
6457            ((TagX->getTagKind() == TTK_Struct ||
6458              TagX->getTagKind() == TTK_Class ||
6459              TagX->getTagKind() == TTK_Interface) &&
6460             (TagY->getTagKind() == TTK_Struct ||
6461              TagY->getTagKind() == TTK_Class ||
6462              TagY->getTagKind() == TTK_Interface));
6463   }
6464 
6465   // Functions with the same type and linkage match.
6466   // FIXME: This needs to cope with merging of prototyped/non-prototyped
6467   // functions, etc.
6468   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6469     const auto *FuncY = cast<FunctionDecl>(Y);
6470     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6471       const auto *CtorY = cast<CXXConstructorDecl>(Y);
6472       if (CtorX->getInheritedConstructor() &&
6473           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6474                         CtorY->getInheritedConstructor().getConstructor()))
6475         return false;
6476     }
6477 
6478     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6479       return false;
6480 
6481     // Multiversioned functions with different feature strings are represented
6482     // as separate declarations.
6483     if (FuncX->isMultiVersion()) {
6484       const auto *TAX = FuncX->getAttr<TargetAttr>();
6485       const auto *TAY = FuncY->getAttr<TargetAttr>();
6486       assert(TAX && TAY && "Multiversion Function without target attribute");
6487 
6488       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6489         return false;
6490     }
6491 
6492     const Expr *XRC = FuncX->getTrailingRequiresClause();
6493     const Expr *YRC = FuncY->getTrailingRequiresClause();
6494     if (!XRC != !YRC)
6495       return false;
6496     if (XRC) {
6497       llvm::FoldingSetNodeID XRCID, YRCID;
6498       XRC->Profile(XRCID, *this, /*Canonical=*/true);
6499       YRC->Profile(YRCID, *this, /*Canonical=*/true);
6500       if (XRCID != YRCID)
6501         return false;
6502     }
6503 
6504     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6505       // Map to the first declaration that we've already merged into this one.
6506       // The TSI of redeclarations might not match (due to calling conventions
6507       // being inherited onto the type but not the TSI), but the TSI type of
6508       // the first declaration of the function should match across modules.
6509       FD = FD->getCanonicalDecl();
6510       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6511                                      : FD->getType();
6512     };
6513     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6514     if (!hasSameType(XT, YT)) {
6515       // We can get functions with different types on the redecl chain in C++17
6516       // if they have differing exception specifications and at least one of
6517       // the excpetion specs is unresolved.
6518       auto *XFPT = XT->getAs<FunctionProtoType>();
6519       auto *YFPT = YT->getAs<FunctionProtoType>();
6520       if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6521           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6522            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
6523           hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
6524         return true;
6525       return false;
6526     }
6527 
6528     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6529            hasSameOverloadableAttrs(FuncX, FuncY);
6530   }
6531 
6532   // Variables with the same type and linkage match.
6533   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6534     const auto *VarY = cast<VarDecl>(Y);
6535     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6536       if (hasSameType(VarX->getType(), VarY->getType()))
6537         return true;
6538 
6539       // We can get decls with different types on the redecl chain. Eg.
6540       // template <typename T> struct S { static T Var[]; }; // #1
6541       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6542       // Only? happens when completing an incomplete array type. In this case
6543       // when comparing #1 and #2 we should go through their element type.
6544       const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6545       const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6546       if (!VarXTy || !VarYTy)
6547         return false;
6548       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6549         return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6550     }
6551     return false;
6552   }
6553 
6554   // Namespaces with the same name and inlinedness match.
6555   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6556     const auto *NamespaceY = cast<NamespaceDecl>(Y);
6557     return NamespaceX->isInline() == NamespaceY->isInline();
6558   }
6559 
6560   // Identical template names and kinds match if their template parameter lists
6561   // and patterns match.
6562   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6563     const auto *TemplateY = cast<TemplateDecl>(Y);
6564     return isSameEntity(TemplateX->getTemplatedDecl(),
6565                         TemplateY->getTemplatedDecl()) &&
6566            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6567                                        TemplateY->getTemplateParameters());
6568   }
6569 
6570   // Fields with the same name and the same type match.
6571   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6572     const auto *FDY = cast<FieldDecl>(Y);
6573     // FIXME: Also check the bitwidth is odr-equivalent, if any.
6574     return hasSameType(FDX->getType(), FDY->getType());
6575   }
6576 
6577   // Indirect fields with the same target field match.
6578   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6579     const auto *IFDY = cast<IndirectFieldDecl>(Y);
6580     return IFDX->getAnonField()->getCanonicalDecl() ==
6581            IFDY->getAnonField()->getCanonicalDecl();
6582   }
6583 
6584   // Enumerators with the same name match.
6585   if (isa<EnumConstantDecl>(X))
6586     // FIXME: Also check the value is odr-equivalent.
6587     return true;
6588 
6589   // Using shadow declarations with the same target match.
6590   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6591     const auto *USY = cast<UsingShadowDecl>(Y);
6592     return USX->getTargetDecl() == USY->getTargetDecl();
6593   }
6594 
6595   // Using declarations with the same qualifier match. (We already know that
6596   // the name matches.)
6597   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6598     const auto *UY = cast<UsingDecl>(Y);
6599     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6600            UX->hasTypename() == UY->hasTypename() &&
6601            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6602   }
6603   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6604     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6605     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6606            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6607   }
6608   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6609     return isSameQualifier(
6610         UX->getQualifier(),
6611         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6612   }
6613 
6614   // Using-pack declarations are only created by instantiation, and match if
6615   // they're instantiated from matching UnresolvedUsing...Decls.
6616   if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6617     return declaresSameEntity(
6618         UX->getInstantiatedFromUsingDecl(),
6619         cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6620   }
6621 
6622   // Namespace alias definitions with the same target match.
6623   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6624     const auto *NAY = cast<NamespaceAliasDecl>(Y);
6625     return NAX->getNamespace()->Equals(NAY->getNamespace());
6626   }
6627 
6628   return false;
6629 }
6630 
6631 TemplateArgument
6632 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
6633   switch (Arg.getKind()) {
6634     case TemplateArgument::Null:
6635       return Arg;
6636 
6637     case TemplateArgument::Expression:
6638       return Arg;
6639 
6640     case TemplateArgument::Declaration: {
6641       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6642       return TemplateArgument(D, Arg.getParamTypeForDecl());
6643     }
6644 
6645     case TemplateArgument::NullPtr:
6646       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
6647                               /*isNullPtr*/true);
6648 
6649     case TemplateArgument::Template:
6650       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
6651 
6652     case TemplateArgument::TemplateExpansion:
6653       return TemplateArgument(getCanonicalTemplateName(
6654                                          Arg.getAsTemplateOrTemplatePattern()),
6655                               Arg.getNumTemplateExpansions());
6656 
6657     case TemplateArgument::Integral:
6658       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
6659 
6660     case TemplateArgument::Type:
6661       return TemplateArgument(getCanonicalType(Arg.getAsType()));
6662 
6663     case TemplateArgument::Pack: {
6664       if (Arg.pack_size() == 0)
6665         return Arg;
6666 
6667       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6668       unsigned Idx = 0;
6669       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6670                                         AEnd = Arg.pack_end();
6671            A != AEnd; (void)++A, ++Idx)
6672         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6673 
6674       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6675     }
6676   }
6677 
6678   // Silence GCC warning
6679   llvm_unreachable("Unhandled template argument kind");
6680 }
6681 
6682 NestedNameSpecifier *
6683 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6684   if (!NNS)
6685     return nullptr;
6686 
6687   switch (NNS->getKind()) {
6688   case NestedNameSpecifier::Identifier:
6689     // Canonicalize the prefix but keep the identifier the same.
6690     return NestedNameSpecifier::Create(*this,
6691                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6692                                        NNS->getAsIdentifier());
6693 
6694   case NestedNameSpecifier::Namespace:
6695     // A namespace is canonical; build a nested-name-specifier with
6696     // this namespace and no prefix.
6697     return NestedNameSpecifier::Create(*this, nullptr,
6698                                  NNS->getAsNamespace()->getOriginalNamespace());
6699 
6700   case NestedNameSpecifier::NamespaceAlias:
6701     // A namespace is canonical; build a nested-name-specifier with
6702     // this namespace and no prefix.
6703     return NestedNameSpecifier::Create(*this, nullptr,
6704                                     NNS->getAsNamespaceAlias()->getNamespace()
6705                                                       ->getOriginalNamespace());
6706 
6707   // The difference between TypeSpec and TypeSpecWithTemplate is that the
6708   // latter will have the 'template' keyword when printed.
6709   case NestedNameSpecifier::TypeSpec:
6710   case NestedNameSpecifier::TypeSpecWithTemplate: {
6711     const Type *T = getCanonicalType(NNS->getAsType());
6712 
6713     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6714     // break it apart into its prefix and identifier, then reconsititute those
6715     // as the canonical nested-name-specifier. This is required to canonicalize
6716     // a dependent nested-name-specifier involving typedefs of dependent-name
6717     // types, e.g.,
6718     //   typedef typename T::type T1;
6719     //   typedef typename T1::type T2;
6720     if (const auto *DNT = T->getAs<DependentNameType>())
6721       return NestedNameSpecifier::Create(
6722           *this, DNT->getQualifier(),
6723           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6724     if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6725       return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6726                                          const_cast<Type *>(T));
6727 
6728     // TODO: Set 'Template' parameter to true for other template types.
6729     return NestedNameSpecifier::Create(*this, nullptr, false,
6730                                        const_cast<Type *>(T));
6731   }
6732 
6733   case NestedNameSpecifier::Global:
6734   case NestedNameSpecifier::Super:
6735     // The global specifier and __super specifer are canonical and unique.
6736     return NNS;
6737   }
6738 
6739   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6740 }
6741 
6742 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6743   // Handle the non-qualified case efficiently.
6744   if (!T.hasLocalQualifiers()) {
6745     // Handle the common positive case fast.
6746     if (const auto *AT = dyn_cast<ArrayType>(T))
6747       return AT;
6748   }
6749 
6750   // Handle the common negative case fast.
6751   if (!isa<ArrayType>(T.getCanonicalType()))
6752     return nullptr;
6753 
6754   // Apply any qualifiers from the array type to the element type.  This
6755   // implements C99 6.7.3p8: "If the specification of an array type includes
6756   // any type qualifiers, the element type is so qualified, not the array type."
6757 
6758   // If we get here, we either have type qualifiers on the type, or we have
6759   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6760   // we must propagate them down into the element type.
6761 
6762   SplitQualType split = T.getSplitDesugaredType();
6763   Qualifiers qs = split.Quals;
6764 
6765   // If we have a simple case, just return now.
6766   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6767   if (!ATy || qs.empty())
6768     return ATy;
6769 
6770   // Otherwise, we have an array and we have qualifiers on it.  Push the
6771   // qualifiers into the array element type and return a new array type.
6772   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6773 
6774   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6775     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6776                                                 CAT->getSizeExpr(),
6777                                                 CAT->getSizeModifier(),
6778                                            CAT->getIndexTypeCVRQualifiers()));
6779   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6780     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6781                                                   IAT->getSizeModifier(),
6782                                            IAT->getIndexTypeCVRQualifiers()));
6783 
6784   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6785     return cast<ArrayType>(
6786                      getDependentSizedArrayType(NewEltTy,
6787                                                 DSAT->getSizeExpr(),
6788                                                 DSAT->getSizeModifier(),
6789                                               DSAT->getIndexTypeCVRQualifiers(),
6790                                                 DSAT->getBracketsRange()));
6791 
6792   const auto *VAT = cast<VariableArrayType>(ATy);
6793   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6794                                               VAT->getSizeExpr(),
6795                                               VAT->getSizeModifier(),
6796                                               VAT->getIndexTypeCVRQualifiers(),
6797                                               VAT->getBracketsRange()));
6798 }
6799 
6800 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6801   if (T->isArrayType() || T->isFunctionType())
6802     return getDecayedType(T);
6803   return T;
6804 }
6805 
6806 QualType ASTContext::getSignatureParameterType(QualType T) const {
6807   T = getVariableArrayDecayedType(T);
6808   T = getAdjustedParameterType(T);
6809   return T.getUnqualifiedType();
6810 }
6811 
6812 QualType ASTContext::getExceptionObjectType(QualType T) const {
6813   // C++ [except.throw]p3:
6814   //   A throw-expression initializes a temporary object, called the exception
6815   //   object, the type of which is determined by removing any top-level
6816   //   cv-qualifiers from the static type of the operand of throw and adjusting
6817   //   the type from "array of T" or "function returning T" to "pointer to T"
6818   //   or "pointer to function returning T", [...]
6819   T = getVariableArrayDecayedType(T);
6820   if (T->isArrayType() || T->isFunctionType())
6821     T = getDecayedType(T);
6822   return T.getUnqualifiedType();
6823 }
6824 
6825 /// getArrayDecayedType - Return the properly qualified result of decaying the
6826 /// specified array type to a pointer.  This operation is non-trivial when
6827 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6828 /// this returns a pointer to a properly qualified element of the array.
6829 ///
6830 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6831 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6832   // Get the element type with 'getAsArrayType' so that we don't lose any
6833   // typedefs in the element type of the array.  This also handles propagation
6834   // of type qualifiers from the array type into the element type if present
6835   // (C99 6.7.3p8).
6836   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6837   assert(PrettyArrayType && "Not an array type!");
6838 
6839   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6840 
6841   // int x[restrict 4] ->  int *restrict
6842   QualType Result = getQualifiedType(PtrTy,
6843                                      PrettyArrayType->getIndexTypeQualifiers());
6844 
6845   // int x[_Nullable] -> int * _Nullable
6846   if (auto Nullability = Ty->getNullability(*this)) {
6847     Result = const_cast<ASTContext *>(this)->getAttributedType(
6848         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6849   }
6850   return Result;
6851 }
6852 
6853 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6854   return getBaseElementType(array->getElementType());
6855 }
6856 
6857 QualType ASTContext::getBaseElementType(QualType type) const {
6858   Qualifiers qs;
6859   while (true) {
6860     SplitQualType split = type.getSplitDesugaredType();
6861     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6862     if (!array) break;
6863 
6864     type = array->getElementType();
6865     qs.addConsistentQualifiers(split.Quals);
6866   }
6867 
6868   return getQualifiedType(type, qs);
6869 }
6870 
6871 /// getConstantArrayElementCount - Returns number of constant array elements.
6872 uint64_t
6873 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6874   uint64_t ElementCount = 1;
6875   do {
6876     ElementCount *= CA->getSize().getZExtValue();
6877     CA = dyn_cast_or_null<ConstantArrayType>(
6878       CA->getElementType()->getAsArrayTypeUnsafe());
6879   } while (CA);
6880   return ElementCount;
6881 }
6882 
6883 /// getFloatingRank - Return a relative rank for floating point types.
6884 /// This routine will assert if passed a built-in type that isn't a float.
6885 static FloatingRank getFloatingRank(QualType T) {
6886   if (const auto *CT = T->getAs<ComplexType>())
6887     return getFloatingRank(CT->getElementType());
6888 
6889   switch (T->castAs<BuiltinType>()->getKind()) {
6890   default: llvm_unreachable("getFloatingRank(): not a floating type");
6891   case BuiltinType::Float16:    return Float16Rank;
6892   case BuiltinType::Half:       return HalfRank;
6893   case BuiltinType::Float:      return FloatRank;
6894   case BuiltinType::Double:     return DoubleRank;
6895   case BuiltinType::LongDouble: return LongDoubleRank;
6896   case BuiltinType::Float128:   return Float128Rank;
6897   case BuiltinType::BFloat16:   return BFloat16Rank;
6898   case BuiltinType::Ibm128:     return Ibm128Rank;
6899   }
6900 }
6901 
6902 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6903 /// point types, ignoring the domain of the type (i.e. 'double' ==
6904 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6905 /// LHS < RHS, return -1.
6906 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6907   FloatingRank LHSR = getFloatingRank(LHS);
6908   FloatingRank RHSR = getFloatingRank(RHS);
6909 
6910   if (LHSR == RHSR)
6911     return 0;
6912   if (LHSR > RHSR)
6913     return 1;
6914   return -1;
6915 }
6916 
6917 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6918   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6919     return 0;
6920   return getFloatingTypeOrder(LHS, RHS);
6921 }
6922 
6923 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6924 /// routine will assert if passed a built-in type that isn't an integer or enum,
6925 /// or if it is not canonicalized.
6926 unsigned ASTContext::getIntegerRank(const Type *T) const {
6927   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6928 
6929   // Results in this 'losing' to any type of the same size, but winning if
6930   // larger.
6931   if (const auto *EIT = dyn_cast<BitIntType>(T))
6932     return 0 + (EIT->getNumBits() << 3);
6933 
6934   switch (cast<BuiltinType>(T)->getKind()) {
6935   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6936   case BuiltinType::Bool:
6937     return 1 + (getIntWidth(BoolTy) << 3);
6938   case BuiltinType::Char_S:
6939   case BuiltinType::Char_U:
6940   case BuiltinType::SChar:
6941   case BuiltinType::UChar:
6942     return 2 + (getIntWidth(CharTy) << 3);
6943   case BuiltinType::Short:
6944   case BuiltinType::UShort:
6945     return 3 + (getIntWidth(ShortTy) << 3);
6946   case BuiltinType::Int:
6947   case BuiltinType::UInt:
6948     return 4 + (getIntWidth(IntTy) << 3);
6949   case BuiltinType::Long:
6950   case BuiltinType::ULong:
6951     return 5 + (getIntWidth(LongTy) << 3);
6952   case BuiltinType::LongLong:
6953   case BuiltinType::ULongLong:
6954     return 6 + (getIntWidth(LongLongTy) << 3);
6955   case BuiltinType::Int128:
6956   case BuiltinType::UInt128:
6957     return 7 + (getIntWidth(Int128Ty) << 3);
6958   }
6959 }
6960 
6961 /// Whether this is a promotable bitfield reference according
6962 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6963 ///
6964 /// \returns the type this bit-field will promote to, or NULL if no
6965 /// promotion occurs.
6966 QualType ASTContext::isPromotableBitField(Expr *E) const {
6967   if (E->isTypeDependent() || E->isValueDependent())
6968     return {};
6969 
6970   // C++ [conv.prom]p5:
6971   //    If the bit-field has an enumerated type, it is treated as any other
6972   //    value of that type for promotion purposes.
6973   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6974     return {};
6975 
6976   // FIXME: We should not do this unless E->refersToBitField() is true. This
6977   // matters in C where getSourceBitField() will find bit-fields for various
6978   // cases where the source expression is not a bit-field designator.
6979 
6980   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6981   if (!Field)
6982     return {};
6983 
6984   QualType FT = Field->getType();
6985 
6986   uint64_t BitWidth = Field->getBitWidthValue(*this);
6987   uint64_t IntSize = getTypeSize(IntTy);
6988   // C++ [conv.prom]p5:
6989   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6990   //   int if int can represent all the values of the bit-field; otherwise, it
6991   //   can be converted to unsigned int if unsigned int can represent all the
6992   //   values of the bit-field. If the bit-field is larger yet, no integral
6993   //   promotion applies to it.
6994   // C11 6.3.1.1/2:
6995   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6996   //   If an int can represent all values of the original type (as restricted by
6997   //   the width, for a bit-field), the value is converted to an int; otherwise,
6998   //   it is converted to an unsigned int.
6999   //
7000   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7001   //        We perform that promotion here to match GCC and C++.
7002   // FIXME: C does not permit promotion of an enum bit-field whose rank is
7003   //        greater than that of 'int'. We perform that promotion to match GCC.
7004   if (BitWidth < IntSize)
7005     return IntTy;
7006 
7007   if (BitWidth == IntSize)
7008     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7009 
7010   // Bit-fields wider than int are not subject to promotions, and therefore act
7011   // like the base type. GCC has some weird bugs in this area that we
7012   // deliberately do not follow (GCC follows a pre-standard resolution to
7013   // C's DR315 which treats bit-width as being part of the type, and this leaks
7014   // into their semantics in some cases).
7015   return {};
7016 }
7017 
7018 /// getPromotedIntegerType - Returns the type that Promotable will
7019 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7020 /// integer type.
7021 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
7022   assert(!Promotable.isNull());
7023   assert(Promotable->isPromotableIntegerType());
7024   if (const auto *ET = Promotable->getAs<EnumType>())
7025     return ET->getDecl()->getPromotionType();
7026 
7027   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7028     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7029     // (3.9.1) can be converted to a prvalue of the first of the following
7030     // types that can represent all the values of its underlying type:
7031     // int, unsigned int, long int, unsigned long int, long long int, or
7032     // unsigned long long int [...]
7033     // FIXME: Is there some better way to compute this?
7034     if (BT->getKind() == BuiltinType::WChar_S ||
7035         BT->getKind() == BuiltinType::WChar_U ||
7036         BT->getKind() == BuiltinType::Char8 ||
7037         BT->getKind() == BuiltinType::Char16 ||
7038         BT->getKind() == BuiltinType::Char32) {
7039       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7040       uint64_t FromSize = getTypeSize(BT);
7041       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7042                                   LongLongTy, UnsignedLongLongTy };
7043       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
7044         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
7045         if (FromSize < ToSize ||
7046             (FromSize == ToSize &&
7047              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
7048           return PromoteTypes[Idx];
7049       }
7050       llvm_unreachable("char type should fit into long long");
7051     }
7052   }
7053 
7054   // At this point, we should have a signed or unsigned integer type.
7055   if (Promotable->isSignedIntegerType())
7056     return IntTy;
7057   uint64_t PromotableSize = getIntWidth(Promotable);
7058   uint64_t IntSize = getIntWidth(IntTy);
7059   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7060   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7061 }
7062 
7063 /// Recurses in pointer/array types until it finds an objc retainable
7064 /// type and returns its ownership.
7065 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
7066   while (!T.isNull()) {
7067     if (T.getObjCLifetime() != Qualifiers::OCL_None)
7068       return T.getObjCLifetime();
7069     if (T->isArrayType())
7070       T = getBaseElementType(T);
7071     else if (const auto *PT = T->getAs<PointerType>())
7072       T = PT->getPointeeType();
7073     else if (const auto *RT = T->getAs<ReferenceType>())
7074       T = RT->getPointeeType();
7075     else
7076       break;
7077   }
7078 
7079   return Qualifiers::OCL_None;
7080 }
7081 
7082 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7083   // Incomplete enum types are not treated as integer types.
7084   // FIXME: In C++, enum types are never integer types.
7085   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7086     return ET->getDecl()->getIntegerType().getTypePtr();
7087   return nullptr;
7088 }
7089 
7090 /// getIntegerTypeOrder - Returns the highest ranked integer type:
7091 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7092 /// LHS < RHS, return -1.
7093 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
7094   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7095   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7096 
7097   // Unwrap enums to their underlying type.
7098   if (const auto *ET = dyn_cast<EnumType>(LHSC))
7099     LHSC = getIntegerTypeForEnum(ET);
7100   if (const auto *ET = dyn_cast<EnumType>(RHSC))
7101     RHSC = getIntegerTypeForEnum(ET);
7102 
7103   if (LHSC == RHSC) return 0;
7104 
7105   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7106   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7107 
7108   unsigned LHSRank = getIntegerRank(LHSC);
7109   unsigned RHSRank = getIntegerRank(RHSC);
7110 
7111   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
7112     if (LHSRank == RHSRank) return 0;
7113     return LHSRank > RHSRank ? 1 : -1;
7114   }
7115 
7116   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7117   if (LHSUnsigned) {
7118     // If the unsigned [LHS] type is larger, return it.
7119     if (LHSRank >= RHSRank)
7120       return 1;
7121 
7122     // If the signed type can represent all values of the unsigned type, it
7123     // wins.  Because we are dealing with 2's complement and types that are
7124     // powers of two larger than each other, this is always safe.
7125     return -1;
7126   }
7127 
7128   // If the unsigned [RHS] type is larger, return it.
7129   if (RHSRank >= LHSRank)
7130     return -1;
7131 
7132   // If the signed type can represent all values of the unsigned type, it
7133   // wins.  Because we are dealing with 2's complement and types that are
7134   // powers of two larger than each other, this is always safe.
7135   return 1;
7136 }
7137 
7138 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
7139   if (CFConstantStringTypeDecl)
7140     return CFConstantStringTypeDecl;
7141 
7142   assert(!CFConstantStringTagDecl &&
7143          "tag and typedef should be initialized together");
7144   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7145   CFConstantStringTagDecl->startDefinition();
7146 
7147   struct {
7148     QualType Type;
7149     const char *Name;
7150   } Fields[5];
7151   unsigned Count = 0;
7152 
7153   /// Objective-C ABI
7154   ///
7155   ///    typedef struct __NSConstantString_tag {
7156   ///      const int *isa;
7157   ///      int flags;
7158   ///      const char *str;
7159   ///      long length;
7160   ///    } __NSConstantString;
7161   ///
7162   /// Swift ABI (4.1, 4.2)
7163   ///
7164   ///    typedef struct __NSConstantString_tag {
7165   ///      uintptr_t _cfisa;
7166   ///      uintptr_t _swift_rc;
7167   ///      _Atomic(uint64_t) _cfinfoa;
7168   ///      const char *_ptr;
7169   ///      uint32_t _length;
7170   ///    } __NSConstantString;
7171   ///
7172   /// Swift ABI (5.0)
7173   ///
7174   ///    typedef struct __NSConstantString_tag {
7175   ///      uintptr_t _cfisa;
7176   ///      uintptr_t _swift_rc;
7177   ///      _Atomic(uint64_t) _cfinfoa;
7178   ///      const char *_ptr;
7179   ///      uintptr_t _length;
7180   ///    } __NSConstantString;
7181 
7182   const auto CFRuntime = getLangOpts().CFRuntime;
7183   if (static_cast<unsigned>(CFRuntime) <
7184       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7185     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7186     Fields[Count++] = { IntTy, "flags" };
7187     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7188     Fields[Count++] = { LongTy, "length" };
7189   } else {
7190     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7191     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7192     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7193     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7194     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
7195         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
7196       Fields[Count++] = { IntTy, "_ptr" };
7197     else
7198       Fields[Count++] = { getUIntPtrType(), "_ptr" };
7199   }
7200 
7201   // Create fields
7202   for (unsigned i = 0; i < Count; ++i) {
7203     FieldDecl *Field =
7204         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7205                           SourceLocation(), &Idents.get(Fields[i].Name),
7206                           Fields[i].Type, /*TInfo=*/nullptr,
7207                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7208     Field->setAccess(AS_public);
7209     CFConstantStringTagDecl->addDecl(Field);
7210   }
7211 
7212   CFConstantStringTagDecl->completeDefinition();
7213   // This type is designed to be compatible with NSConstantString, but cannot
7214   // use the same name, since NSConstantString is an interface.
7215   auto tagType = getTagDeclType(CFConstantStringTagDecl);
7216   CFConstantStringTypeDecl =
7217       buildImplicitTypedef(tagType, "__NSConstantString");
7218 
7219   return CFConstantStringTypeDecl;
7220 }
7221 
7222 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
7223   if (!CFConstantStringTagDecl)
7224     getCFConstantStringDecl(); // Build the tag and the typedef.
7225   return CFConstantStringTagDecl;
7226 }
7227 
7228 // getCFConstantStringType - Return the type used for constant CFStrings.
7229 QualType ASTContext::getCFConstantStringType() const {
7230   return getTypedefType(getCFConstantStringDecl());
7231 }
7232 
7233 QualType ASTContext::getObjCSuperType() const {
7234   if (ObjCSuperType.isNull()) {
7235     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7236     getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7237     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7238   }
7239   return ObjCSuperType;
7240 }
7241 
7242 void ASTContext::setCFConstantStringType(QualType T) {
7243   const auto *TD = T->castAs<TypedefType>();
7244   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7245   const auto *TagType =
7246       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7247   CFConstantStringTagDecl = TagType->getDecl();
7248 }
7249 
7250 QualType ASTContext::getBlockDescriptorType() const {
7251   if (BlockDescriptorType)
7252     return getTagDeclType(BlockDescriptorType);
7253 
7254   RecordDecl *RD;
7255   // FIXME: Needs the FlagAppleBlock bit.
7256   RD = buildImplicitRecord("__block_descriptor");
7257   RD->startDefinition();
7258 
7259   QualType FieldTypes[] = {
7260     UnsignedLongTy,
7261     UnsignedLongTy,
7262   };
7263 
7264   static const char *const FieldNames[] = {
7265     "reserved",
7266     "Size"
7267   };
7268 
7269   for (size_t i = 0; i < 2; ++i) {
7270     FieldDecl *Field = FieldDecl::Create(
7271         *this, RD, SourceLocation(), SourceLocation(),
7272         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7273         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7274     Field->setAccess(AS_public);
7275     RD->addDecl(Field);
7276   }
7277 
7278   RD->completeDefinition();
7279 
7280   BlockDescriptorType = RD;
7281 
7282   return getTagDeclType(BlockDescriptorType);
7283 }
7284 
7285 QualType ASTContext::getBlockDescriptorExtendedType() const {
7286   if (BlockDescriptorExtendedType)
7287     return getTagDeclType(BlockDescriptorExtendedType);
7288 
7289   RecordDecl *RD;
7290   // FIXME: Needs the FlagAppleBlock bit.
7291   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7292   RD->startDefinition();
7293 
7294   QualType FieldTypes[] = {
7295     UnsignedLongTy,
7296     UnsignedLongTy,
7297     getPointerType(VoidPtrTy),
7298     getPointerType(VoidPtrTy)
7299   };
7300 
7301   static const char *const FieldNames[] = {
7302     "reserved",
7303     "Size",
7304     "CopyFuncPtr",
7305     "DestroyFuncPtr"
7306   };
7307 
7308   for (size_t i = 0; i < 4; ++i) {
7309     FieldDecl *Field = FieldDecl::Create(
7310         *this, RD, SourceLocation(), SourceLocation(),
7311         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7312         /*BitWidth=*/nullptr,
7313         /*Mutable=*/false, ICIS_NoInit);
7314     Field->setAccess(AS_public);
7315     RD->addDecl(Field);
7316   }
7317 
7318   RD->completeDefinition();
7319 
7320   BlockDescriptorExtendedType = RD;
7321   return getTagDeclType(BlockDescriptorExtendedType);
7322 }
7323 
7324 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
7325   const auto *BT = dyn_cast<BuiltinType>(T);
7326 
7327   if (!BT) {
7328     if (isa<PipeType>(T))
7329       return OCLTK_Pipe;
7330 
7331     return OCLTK_Default;
7332   }
7333 
7334   switch (BT->getKind()) {
7335 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
7336   case BuiltinType::Id:                                                        \
7337     return OCLTK_Image;
7338 #include "clang/Basic/OpenCLImageTypes.def"
7339 
7340   case BuiltinType::OCLClkEvent:
7341     return OCLTK_ClkEvent;
7342 
7343   case BuiltinType::OCLEvent:
7344     return OCLTK_Event;
7345 
7346   case BuiltinType::OCLQueue:
7347     return OCLTK_Queue;
7348 
7349   case BuiltinType::OCLReserveID:
7350     return OCLTK_ReserveID;
7351 
7352   case BuiltinType::OCLSampler:
7353     return OCLTK_Sampler;
7354 
7355   default:
7356     return OCLTK_Default;
7357   }
7358 }
7359 
7360 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
7361   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7362 }
7363 
7364 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7365 /// requires copy/dispose. Note that this must match the logic
7366 /// in buildByrefHelpers.
7367 bool ASTContext::BlockRequiresCopying(QualType Ty,
7368                                       const VarDecl *D) {
7369   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7370     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7371     if (!copyExpr && record->hasTrivialDestructor()) return false;
7372 
7373     return true;
7374   }
7375 
7376   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7377   // move or destroy.
7378   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
7379     return true;
7380 
7381   if (!Ty->isObjCRetainableType()) return false;
7382 
7383   Qualifiers qs = Ty.getQualifiers();
7384 
7385   // If we have lifetime, that dominates.
7386   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7387     switch (lifetime) {
7388       case Qualifiers::OCL_None: llvm_unreachable("impossible");
7389 
7390       // These are just bits as far as the runtime is concerned.
7391       case Qualifiers::OCL_ExplicitNone:
7392       case Qualifiers::OCL_Autoreleasing:
7393         return false;
7394 
7395       // These cases should have been taken care of when checking the type's
7396       // non-triviality.
7397       case Qualifiers::OCL_Weak:
7398       case Qualifiers::OCL_Strong:
7399         llvm_unreachable("impossible");
7400     }
7401     llvm_unreachable("fell out of lifetime switch!");
7402   }
7403   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7404           Ty->isObjCObjectPointerType());
7405 }
7406 
7407 bool ASTContext::getByrefLifetime(QualType Ty,
7408                               Qualifiers::ObjCLifetime &LifeTime,
7409                               bool &HasByrefExtendedLayout) const {
7410   if (!getLangOpts().ObjC ||
7411       getLangOpts().getGC() != LangOptions::NonGC)
7412     return false;
7413 
7414   HasByrefExtendedLayout = false;
7415   if (Ty->isRecordType()) {
7416     HasByrefExtendedLayout = true;
7417     LifeTime = Qualifiers::OCL_None;
7418   } else if ((LifeTime = Ty.getObjCLifetime())) {
7419     // Honor the ARC qualifiers.
7420   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7421     // The MRR rule.
7422     LifeTime = Qualifiers::OCL_ExplicitNone;
7423   } else {
7424     LifeTime = Qualifiers::OCL_None;
7425   }
7426   return true;
7427 }
7428 
7429 CanQualType ASTContext::getNSUIntegerType() const {
7430   assert(Target && "Expected target to be initialized");
7431   const llvm::Triple &T = Target->getTriple();
7432   // Windows is LLP64 rather than LP64
7433   if (T.isOSWindows() && T.isArch64Bit())
7434     return UnsignedLongLongTy;
7435   return UnsignedLongTy;
7436 }
7437 
7438 CanQualType ASTContext::getNSIntegerType() const {
7439   assert(Target && "Expected target to be initialized");
7440   const llvm::Triple &T = Target->getTriple();
7441   // Windows is LLP64 rather than LP64
7442   if (T.isOSWindows() && T.isArch64Bit())
7443     return LongLongTy;
7444   return LongTy;
7445 }
7446 
7447 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
7448   if (!ObjCInstanceTypeDecl)
7449     ObjCInstanceTypeDecl =
7450         buildImplicitTypedef(getObjCIdType(), "instancetype");
7451   return ObjCInstanceTypeDecl;
7452 }
7453 
7454 // This returns true if a type has been typedefed to BOOL:
7455 // typedef <type> BOOL;
7456 static bool isTypeTypedefedAsBOOL(QualType T) {
7457   if (const auto *TT = dyn_cast<TypedefType>(T))
7458     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7459       return II->isStr("BOOL");
7460 
7461   return false;
7462 }
7463 
7464 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
7465 /// purpose.
7466 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
7467   if (!type->isIncompleteArrayType() && type->isIncompleteType())
7468     return CharUnits::Zero();
7469 
7470   CharUnits sz = getTypeSizeInChars(type);
7471 
7472   // Make all integer and enum types at least as large as an int
7473   if (sz.isPositive() && type->isIntegralOrEnumerationType())
7474     sz = std::max(sz, getTypeSizeInChars(IntTy));
7475   // Treat arrays as pointers, since that's how they're passed in.
7476   else if (type->isArrayType())
7477     sz = getTypeSizeInChars(VoidPtrTy);
7478   return sz;
7479 }
7480 
7481 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
7482   return getTargetInfo().getCXXABI().isMicrosoft() &&
7483          VD->isStaticDataMember() &&
7484          VD->getType()->isIntegralOrEnumerationType() &&
7485          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7486 }
7487 
7488 ASTContext::InlineVariableDefinitionKind
7489 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
7490   if (!VD->isInline())
7491     return InlineVariableDefinitionKind::None;
7492 
7493   // In almost all cases, it's a weak definition.
7494   auto *First = VD->getFirstDecl();
7495   if (First->isInlineSpecified() || !First->isStaticDataMember())
7496     return InlineVariableDefinitionKind::Weak;
7497 
7498   // If there's a file-context declaration in this translation unit, it's a
7499   // non-discardable definition.
7500   for (auto *D : VD->redecls())
7501     if (D->getLexicalDeclContext()->isFileContext() &&
7502         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7503       return InlineVariableDefinitionKind::Strong;
7504 
7505   // If we've not seen one yet, we don't know.
7506   return InlineVariableDefinitionKind::WeakUnknown;
7507 }
7508 
7509 static std::string charUnitsToString(const CharUnits &CU) {
7510   return llvm::itostr(CU.getQuantity());
7511 }
7512 
7513 /// getObjCEncodingForBlock - Return the encoded type for this block
7514 /// declaration.
7515 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
7516   std::string S;
7517 
7518   const BlockDecl *Decl = Expr->getBlockDecl();
7519   QualType BlockTy =
7520       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7521   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7522   // Encode result type.
7523   if (getLangOpts().EncodeExtendedBlockSig)
7524     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
7525                                       true /*Extended*/);
7526   else
7527     getObjCEncodingForType(BlockReturnTy, S);
7528   // Compute size of all parameters.
7529   // Start with computing size of a pointer in number of bytes.
7530   // FIXME: There might(should) be a better way of doing this computation!
7531   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7532   CharUnits ParmOffset = PtrSize;
7533   for (auto PI : Decl->parameters()) {
7534     QualType PType = PI->getType();
7535     CharUnits sz = getObjCEncodingTypeSize(PType);
7536     if (sz.isZero())
7537       continue;
7538     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7539     ParmOffset += sz;
7540   }
7541   // Size of the argument frame
7542   S += charUnitsToString(ParmOffset);
7543   // Block pointer and offset.
7544   S += "@?0";
7545 
7546   // Argument types.
7547   ParmOffset = PtrSize;
7548   for (auto PVDecl : Decl->parameters()) {
7549     QualType PType = PVDecl->getOriginalType();
7550     if (const auto *AT =
7551             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7552       // Use array's original type only if it has known number of
7553       // elements.
7554       if (!isa<ConstantArrayType>(AT))
7555         PType = PVDecl->getType();
7556     } else if (PType->isFunctionType())
7557       PType = PVDecl->getType();
7558     if (getLangOpts().EncodeExtendedBlockSig)
7559       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
7560                                       S, true /*Extended*/);
7561     else
7562       getObjCEncodingForType(PType, S);
7563     S += charUnitsToString(ParmOffset);
7564     ParmOffset += getObjCEncodingTypeSize(PType);
7565   }
7566 
7567   return S;
7568 }
7569 
7570 std::string
7571 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
7572   std::string S;
7573   // Encode result type.
7574   getObjCEncodingForType(Decl->getReturnType(), S);
7575   CharUnits ParmOffset;
7576   // Compute size of all parameters.
7577   for (auto PI : Decl->parameters()) {
7578     QualType PType = PI->getType();
7579     CharUnits sz = getObjCEncodingTypeSize(PType);
7580     if (sz.isZero())
7581       continue;
7582 
7583     assert(sz.isPositive() &&
7584            "getObjCEncodingForFunctionDecl - Incomplete param type");
7585     ParmOffset += sz;
7586   }
7587   S += charUnitsToString(ParmOffset);
7588   ParmOffset = CharUnits::Zero();
7589 
7590   // Argument types.
7591   for (auto PVDecl : Decl->parameters()) {
7592     QualType PType = PVDecl->getOriginalType();
7593     if (const auto *AT =
7594             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7595       // Use array's original type only if it has known number of
7596       // elements.
7597       if (!isa<ConstantArrayType>(AT))
7598         PType = PVDecl->getType();
7599     } else if (PType->isFunctionType())
7600       PType = PVDecl->getType();
7601     getObjCEncodingForType(PType, S);
7602     S += charUnitsToString(ParmOffset);
7603     ParmOffset += getObjCEncodingTypeSize(PType);
7604   }
7605 
7606   return S;
7607 }
7608 
7609 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
7610 /// method parameter or return type. If Extended, include class names and
7611 /// block object types.
7612 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
7613                                                    QualType T, std::string& S,
7614                                                    bool Extended) const {
7615   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7616   getObjCEncodingForTypeQualifier(QT, S);
7617   // Encode parameter type.
7618   ObjCEncOptions Options = ObjCEncOptions()
7619                                .setExpandPointedToStructures()
7620                                .setExpandStructures()
7621                                .setIsOutermostType();
7622   if (Extended)
7623     Options.setEncodeBlockParameters().setEncodeClassNames();
7624   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7625 }
7626 
7627 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
7628 /// declaration.
7629 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
7630                                                      bool Extended) const {
7631   // FIXME: This is not very efficient.
7632   // Encode return type.
7633   std::string S;
7634   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7635                                     Decl->getReturnType(), S, Extended);
7636   // Compute size of all parameters.
7637   // Start with computing size of a pointer in number of bytes.
7638   // FIXME: There might(should) be a better way of doing this computation!
7639   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7640   // The first two arguments (self and _cmd) are pointers; account for
7641   // their size.
7642   CharUnits ParmOffset = 2 * PtrSize;
7643   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7644        E = Decl->sel_param_end(); PI != E; ++PI) {
7645     QualType PType = (*PI)->getType();
7646     CharUnits sz = getObjCEncodingTypeSize(PType);
7647     if (sz.isZero())
7648       continue;
7649 
7650     assert(sz.isPositive() &&
7651            "getObjCEncodingForMethodDecl - Incomplete param type");
7652     ParmOffset += sz;
7653   }
7654   S += charUnitsToString(ParmOffset);
7655   S += "@0:";
7656   S += charUnitsToString(PtrSize);
7657 
7658   // Argument types.
7659   ParmOffset = 2 * PtrSize;
7660   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7661        E = Decl->sel_param_end(); PI != E; ++PI) {
7662     const ParmVarDecl *PVDecl = *PI;
7663     QualType PType = PVDecl->getOriginalType();
7664     if (const auto *AT =
7665             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7666       // Use array's original type only if it has known number of
7667       // elements.
7668       if (!isa<ConstantArrayType>(AT))
7669         PType = PVDecl->getType();
7670     } else if (PType->isFunctionType())
7671       PType = PVDecl->getType();
7672     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7673                                       PType, S, Extended);
7674     S += charUnitsToString(ParmOffset);
7675     ParmOffset += getObjCEncodingTypeSize(PType);
7676   }
7677 
7678   return S;
7679 }
7680 
7681 ObjCPropertyImplDecl *
7682 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7683                                       const ObjCPropertyDecl *PD,
7684                                       const Decl *Container) const {
7685   if (!Container)
7686     return nullptr;
7687   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7688     for (auto *PID : CID->property_impls())
7689       if (PID->getPropertyDecl() == PD)
7690         return PID;
7691   } else {
7692     const auto *OID = cast<ObjCImplementationDecl>(Container);
7693     for (auto *PID : OID->property_impls())
7694       if (PID->getPropertyDecl() == PD)
7695         return PID;
7696   }
7697   return nullptr;
7698 }
7699 
7700 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7701 /// property declaration. If non-NULL, Container must be either an
7702 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7703 /// NULL when getting encodings for protocol properties.
7704 /// Property attributes are stored as a comma-delimited C string. The simple
7705 /// attributes readonly and bycopy are encoded as single characters. The
7706 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7707 /// encoded as single characters, followed by an identifier. Property types
7708 /// are also encoded as a parametrized attribute. The characters used to encode
7709 /// these attributes are defined by the following enumeration:
7710 /// @code
7711 /// enum PropertyAttributes {
7712 /// kPropertyReadOnly = 'R',   // property is read-only.
7713 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7714 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7715 /// kPropertyDynamic = 'D',    // property is dynamic
7716 /// kPropertyGetter = 'G',     // followed by getter selector name
7717 /// kPropertySetter = 'S',     // followed by setter selector name
7718 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7719 /// kPropertyType = 'T'              // followed by old-style type encoding.
7720 /// kPropertyWeak = 'W'              // 'weak' property
7721 /// kPropertyStrong = 'P'            // property GC'able
7722 /// kPropertyNonAtomic = 'N'         // property non-atomic
7723 /// };
7724 /// @endcode
7725 std::string
7726 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7727                                            const Decl *Container) const {
7728   // Collect information from the property implementation decl(s).
7729   bool Dynamic = false;
7730   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7731 
7732   if (ObjCPropertyImplDecl *PropertyImpDecl =
7733       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7734     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7735       Dynamic = true;
7736     else
7737       SynthesizePID = PropertyImpDecl;
7738   }
7739 
7740   // FIXME: This is not very efficient.
7741   std::string S = "T";
7742 
7743   // Encode result type.
7744   // GCC has some special rules regarding encoding of properties which
7745   // closely resembles encoding of ivars.
7746   getObjCEncodingForPropertyType(PD->getType(), S);
7747 
7748   if (PD->isReadOnly()) {
7749     S += ",R";
7750     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7751       S += ",C";
7752     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7753       S += ",&";
7754     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7755       S += ",W";
7756   } else {
7757     switch (PD->getSetterKind()) {
7758     case ObjCPropertyDecl::Assign: break;
7759     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7760     case ObjCPropertyDecl::Retain: S += ",&"; break;
7761     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7762     }
7763   }
7764 
7765   // It really isn't clear at all what this means, since properties
7766   // are "dynamic by default".
7767   if (Dynamic)
7768     S += ",D";
7769 
7770   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7771     S += ",N";
7772 
7773   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7774     S += ",G";
7775     S += PD->getGetterName().getAsString();
7776   }
7777 
7778   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7779     S += ",S";
7780     S += PD->getSetterName().getAsString();
7781   }
7782 
7783   if (SynthesizePID) {
7784     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7785     S += ",V";
7786     S += OID->getNameAsString();
7787   }
7788 
7789   // FIXME: OBJCGC: weak & strong
7790   return S;
7791 }
7792 
7793 /// getLegacyIntegralTypeEncoding -
7794 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7795 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7796 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7797 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7798   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7799     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7800       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7801         PointeeTy = UnsignedIntTy;
7802       else
7803         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7804           PointeeTy = IntTy;
7805     }
7806   }
7807 }
7808 
7809 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7810                                         const FieldDecl *Field,
7811                                         QualType *NotEncodedT) const {
7812   // We follow the behavior of gcc, expanding structures which are
7813   // directly pointed to, and expanding embedded structures. Note that
7814   // these rules are sufficient to prevent recursive encoding of the
7815   // same type.
7816   getObjCEncodingForTypeImpl(T, S,
7817                              ObjCEncOptions()
7818                                  .setExpandPointedToStructures()
7819                                  .setExpandStructures()
7820                                  .setIsOutermostType(),
7821                              Field, NotEncodedT);
7822 }
7823 
7824 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7825                                                 std::string& S) const {
7826   // Encode result type.
7827   // GCC has some special rules regarding encoding of properties which
7828   // closely resembles encoding of ivars.
7829   getObjCEncodingForTypeImpl(T, S,
7830                              ObjCEncOptions()
7831                                  .setExpandPointedToStructures()
7832                                  .setExpandStructures()
7833                                  .setIsOutermostType()
7834                                  .setEncodingProperty(),
7835                              /*Field=*/nullptr);
7836 }
7837 
7838 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7839                                             const BuiltinType *BT) {
7840     BuiltinType::Kind kind = BT->getKind();
7841     switch (kind) {
7842     case BuiltinType::Void:       return 'v';
7843     case BuiltinType::Bool:       return 'B';
7844     case BuiltinType::Char8:
7845     case BuiltinType::Char_U:
7846     case BuiltinType::UChar:      return 'C';
7847     case BuiltinType::Char16:
7848     case BuiltinType::UShort:     return 'S';
7849     case BuiltinType::Char32:
7850     case BuiltinType::UInt:       return 'I';
7851     case BuiltinType::ULong:
7852         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7853     case BuiltinType::UInt128:    return 'T';
7854     case BuiltinType::ULongLong:  return 'Q';
7855     case BuiltinType::Char_S:
7856     case BuiltinType::SChar:      return 'c';
7857     case BuiltinType::Short:      return 's';
7858     case BuiltinType::WChar_S:
7859     case BuiltinType::WChar_U:
7860     case BuiltinType::Int:        return 'i';
7861     case BuiltinType::Long:
7862       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7863     case BuiltinType::LongLong:   return 'q';
7864     case BuiltinType::Int128:     return 't';
7865     case BuiltinType::Float:      return 'f';
7866     case BuiltinType::Double:     return 'd';
7867     case BuiltinType::LongDouble: return 'D';
7868     case BuiltinType::NullPtr:    return '*'; // like char*
7869 
7870     case BuiltinType::BFloat16:
7871     case BuiltinType::Float16:
7872     case BuiltinType::Float128:
7873     case BuiltinType::Ibm128:
7874     case BuiltinType::Half:
7875     case BuiltinType::ShortAccum:
7876     case BuiltinType::Accum:
7877     case BuiltinType::LongAccum:
7878     case BuiltinType::UShortAccum:
7879     case BuiltinType::UAccum:
7880     case BuiltinType::ULongAccum:
7881     case BuiltinType::ShortFract:
7882     case BuiltinType::Fract:
7883     case BuiltinType::LongFract:
7884     case BuiltinType::UShortFract:
7885     case BuiltinType::UFract:
7886     case BuiltinType::ULongFract:
7887     case BuiltinType::SatShortAccum:
7888     case BuiltinType::SatAccum:
7889     case BuiltinType::SatLongAccum:
7890     case BuiltinType::SatUShortAccum:
7891     case BuiltinType::SatUAccum:
7892     case BuiltinType::SatULongAccum:
7893     case BuiltinType::SatShortFract:
7894     case BuiltinType::SatFract:
7895     case BuiltinType::SatLongFract:
7896     case BuiltinType::SatUShortFract:
7897     case BuiltinType::SatUFract:
7898     case BuiltinType::SatULongFract:
7899       // FIXME: potentially need @encodes for these!
7900       return ' ';
7901 
7902 #define SVE_TYPE(Name, Id, SingletonId) \
7903     case BuiltinType::Id:
7904 #include "clang/Basic/AArch64SVEACLETypes.def"
7905 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7906 #include "clang/Basic/RISCVVTypes.def"
7907       {
7908         DiagnosticsEngine &Diags = C->getDiagnostics();
7909         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7910                                                 "cannot yet @encode type %0");
7911         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7912         return ' ';
7913       }
7914 
7915     case BuiltinType::ObjCId:
7916     case BuiltinType::ObjCClass:
7917     case BuiltinType::ObjCSel:
7918       llvm_unreachable("@encoding ObjC primitive type");
7919 
7920     // OpenCL and placeholder types don't need @encodings.
7921 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7922     case BuiltinType::Id:
7923 #include "clang/Basic/OpenCLImageTypes.def"
7924 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7925     case BuiltinType::Id:
7926 #include "clang/Basic/OpenCLExtensionTypes.def"
7927     case BuiltinType::OCLEvent:
7928     case BuiltinType::OCLClkEvent:
7929     case BuiltinType::OCLQueue:
7930     case BuiltinType::OCLReserveID:
7931     case BuiltinType::OCLSampler:
7932     case BuiltinType::Dependent:
7933 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7934     case BuiltinType::Id:
7935 #include "clang/Basic/PPCTypes.def"
7936 #define BUILTIN_TYPE(KIND, ID)
7937 #define PLACEHOLDER_TYPE(KIND, ID) \
7938     case BuiltinType::KIND:
7939 #include "clang/AST/BuiltinTypes.def"
7940       llvm_unreachable("invalid builtin type for @encode");
7941     }
7942     llvm_unreachable("invalid BuiltinType::Kind value");
7943 }
7944 
7945 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7946   EnumDecl *Enum = ET->getDecl();
7947 
7948   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7949   if (!Enum->isFixed())
7950     return 'i';
7951 
7952   // The encoding of a fixed enum type matches its fixed underlying type.
7953   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7954   return getObjCEncodingForPrimitiveType(C, BT);
7955 }
7956 
7957 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7958                            QualType T, const FieldDecl *FD) {
7959   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7960   S += 'b';
7961   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7962   // The GNU runtime requires more information; bitfields are encoded as b,
7963   // then the offset (in bits) of the first element, then the type of the
7964   // bitfield, then the size in bits.  For example, in this structure:
7965   //
7966   // struct
7967   // {
7968   //    int integer;
7969   //    int flags:2;
7970   // };
7971   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7972   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7973   // information is not especially sensible, but we're stuck with it for
7974   // compatibility with GCC, although providing it breaks anything that
7975   // actually uses runtime introspection and wants to work on both runtimes...
7976   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7977     uint64_t Offset;
7978 
7979     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7980       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7981                                          IVD);
7982     } else {
7983       const RecordDecl *RD = FD->getParent();
7984       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7985       Offset = RL.getFieldOffset(FD->getFieldIndex());
7986     }
7987 
7988     S += llvm::utostr(Offset);
7989 
7990     if (const auto *ET = T->getAs<EnumType>())
7991       S += ObjCEncodingForEnumType(Ctx, ET);
7992     else {
7993       const auto *BT = T->castAs<BuiltinType>();
7994       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7995     }
7996   }
7997   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7998 }
7999 
8000 // Helper function for determining whether the encoded type string would include
8001 // a template specialization type.
8002 static bool hasTemplateSpecializationInEncodedString(const Type *T,
8003                                                      bool VisitBasesAndFields) {
8004   T = T->getBaseElementTypeUnsafe();
8005 
8006   if (auto *PT = T->getAs<PointerType>())
8007     return hasTemplateSpecializationInEncodedString(
8008         PT->getPointeeType().getTypePtr(), false);
8009 
8010   auto *CXXRD = T->getAsCXXRecordDecl();
8011 
8012   if (!CXXRD)
8013     return false;
8014 
8015   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8016     return true;
8017 
8018   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8019     return false;
8020 
8021   for (auto B : CXXRD->bases())
8022     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8023                                                  true))
8024       return true;
8025 
8026   for (auto *FD : CXXRD->fields())
8027     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8028                                                  true))
8029       return true;
8030 
8031   return false;
8032 }
8033 
8034 // FIXME: Use SmallString for accumulating string.
8035 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8036                                             const ObjCEncOptions Options,
8037                                             const FieldDecl *FD,
8038                                             QualType *NotEncodedT) const {
8039   CanQualType CT = getCanonicalType(T);
8040   switch (CT->getTypeClass()) {
8041   case Type::Builtin:
8042   case Type::Enum:
8043     if (FD && FD->isBitField())
8044       return EncodeBitField(this, S, T, FD);
8045     if (const auto *BT = dyn_cast<BuiltinType>(CT))
8046       S += getObjCEncodingForPrimitiveType(this, BT);
8047     else
8048       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8049     return;
8050 
8051   case Type::Complex:
8052     S += 'j';
8053     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8054                                ObjCEncOptions(),
8055                                /*Field=*/nullptr);
8056     return;
8057 
8058   case Type::Atomic:
8059     S += 'A';
8060     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8061                                ObjCEncOptions(),
8062                                /*Field=*/nullptr);
8063     return;
8064 
8065   // encoding for pointer or reference types.
8066   case Type::Pointer:
8067   case Type::LValueReference:
8068   case Type::RValueReference: {
8069     QualType PointeeTy;
8070     if (isa<PointerType>(CT)) {
8071       const auto *PT = T->castAs<PointerType>();
8072       if (PT->isObjCSelType()) {
8073         S += ':';
8074         return;
8075       }
8076       PointeeTy = PT->getPointeeType();
8077     } else {
8078       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8079     }
8080 
8081     bool isReadOnly = false;
8082     // For historical/compatibility reasons, the read-only qualifier of the
8083     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
8084     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8085     // Also, do not emit the 'r' for anything but the outermost type!
8086     if (isa<TypedefType>(T.getTypePtr())) {
8087       if (Options.IsOutermostType() && T.isConstQualified()) {
8088         isReadOnly = true;
8089         S += 'r';
8090       }
8091     } else if (Options.IsOutermostType()) {
8092       QualType P = PointeeTy;
8093       while (auto PT = P->getAs<PointerType>())
8094         P = PT->getPointeeType();
8095       if (P.isConstQualified()) {
8096         isReadOnly = true;
8097         S += 'r';
8098       }
8099     }
8100     if (isReadOnly) {
8101       // Another legacy compatibility encoding. Some ObjC qualifier and type
8102       // combinations need to be rearranged.
8103       // Rewrite "in const" from "nr" to "rn"
8104       if (StringRef(S).endswith("nr"))
8105         S.replace(S.end()-2, S.end(), "rn");
8106     }
8107 
8108     if (PointeeTy->isCharType()) {
8109       // char pointer types should be encoded as '*' unless it is a
8110       // type that has been typedef'd to 'BOOL'.
8111       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8112         S += '*';
8113         return;
8114       }
8115     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8116       // GCC binary compat: Need to convert "struct objc_class *" to "#".
8117       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8118         S += '#';
8119         return;
8120       }
8121       // GCC binary compat: Need to convert "struct objc_object *" to "@".
8122       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8123         S += '@';
8124         return;
8125       }
8126       // If the encoded string for the class includes template names, just emit
8127       // "^v" for pointers to the class.
8128       if (getLangOpts().CPlusPlus &&
8129           (!getLangOpts().EncodeCXXClassTemplateSpec &&
8130            hasTemplateSpecializationInEncodedString(
8131                RTy, Options.ExpandPointedToStructures()))) {
8132         S += "^v";
8133         return;
8134       }
8135       // fall through...
8136     }
8137     S += '^';
8138     getLegacyIntegralTypeEncoding(PointeeTy);
8139 
8140     ObjCEncOptions NewOptions;
8141     if (Options.ExpandPointedToStructures())
8142       NewOptions.setExpandStructures();
8143     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8144                                /*Field=*/nullptr, NotEncodedT);
8145     return;
8146   }
8147 
8148   case Type::ConstantArray:
8149   case Type::IncompleteArray:
8150   case Type::VariableArray: {
8151     const auto *AT = cast<ArrayType>(CT);
8152 
8153     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8154       // Incomplete arrays are encoded as a pointer to the array element.
8155       S += '^';
8156 
8157       getObjCEncodingForTypeImpl(
8158           AT->getElementType(), S,
8159           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8160     } else {
8161       S += '[';
8162 
8163       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8164         S += llvm::utostr(CAT->getSize().getZExtValue());
8165       else {
8166         //Variable length arrays are encoded as a regular array with 0 elements.
8167         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8168                "Unknown array type!");
8169         S += '0';
8170       }
8171 
8172       getObjCEncodingForTypeImpl(
8173           AT->getElementType(), S,
8174           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8175           NotEncodedT);
8176       S += ']';
8177     }
8178     return;
8179   }
8180 
8181   case Type::FunctionNoProto:
8182   case Type::FunctionProto:
8183     S += '?';
8184     return;
8185 
8186   case Type::Record: {
8187     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8188     S += RDecl->isUnion() ? '(' : '{';
8189     // Anonymous structures print as '?'
8190     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8191       S += II->getName();
8192       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8193         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8194         llvm::raw_string_ostream OS(S);
8195         printTemplateArgumentList(OS, TemplateArgs.asArray(),
8196                                   getPrintingPolicy());
8197       }
8198     } else {
8199       S += '?';
8200     }
8201     if (Options.ExpandStructures()) {
8202       S += '=';
8203       if (!RDecl->isUnion()) {
8204         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8205       } else {
8206         for (const auto *Field : RDecl->fields()) {
8207           if (FD) {
8208             S += '"';
8209             S += Field->getNameAsString();
8210             S += '"';
8211           }
8212 
8213           // Special case bit-fields.
8214           if (Field->isBitField()) {
8215             getObjCEncodingForTypeImpl(Field->getType(), S,
8216                                        ObjCEncOptions().setExpandStructures(),
8217                                        Field);
8218           } else {
8219             QualType qt = Field->getType();
8220             getLegacyIntegralTypeEncoding(qt);
8221             getObjCEncodingForTypeImpl(
8222                 qt, S,
8223                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8224                 NotEncodedT);
8225           }
8226         }
8227       }
8228     }
8229     S += RDecl->isUnion() ? ')' : '}';
8230     return;
8231   }
8232 
8233   case Type::BlockPointer: {
8234     const auto *BT = T->castAs<BlockPointerType>();
8235     S += "@?"; // Unlike a pointer-to-function, which is "^?".
8236     if (Options.EncodeBlockParameters()) {
8237       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8238 
8239       S += '<';
8240       // Block return type
8241       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8242                                  Options.forComponentType(), FD, NotEncodedT);
8243       // Block self
8244       S += "@?";
8245       // Block parameters
8246       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8247         for (const auto &I : FPT->param_types())
8248           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8249                                      NotEncodedT);
8250       }
8251       S += '>';
8252     }
8253     return;
8254   }
8255 
8256   case Type::ObjCObject: {
8257     // hack to match legacy encoding of *id and *Class
8258     QualType Ty = getObjCObjectPointerType(CT);
8259     if (Ty->isObjCIdType()) {
8260       S += "{objc_object=}";
8261       return;
8262     }
8263     else if (Ty->isObjCClassType()) {
8264       S += "{objc_class=}";
8265       return;
8266     }
8267     // TODO: Double check to make sure this intentionally falls through.
8268     LLVM_FALLTHROUGH;
8269   }
8270 
8271   case Type::ObjCInterface: {
8272     // Ignore protocol qualifiers when mangling at this level.
8273     // @encode(class_name)
8274     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8275     S += '{';
8276     S += OI->getObjCRuntimeNameAsString();
8277     if (Options.ExpandStructures()) {
8278       S += '=';
8279       SmallVector<const ObjCIvarDecl*, 32> Ivars;
8280       DeepCollectObjCIvars(OI, true, Ivars);
8281       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8282         const FieldDecl *Field = Ivars[i];
8283         if (Field->isBitField())
8284           getObjCEncodingForTypeImpl(Field->getType(), S,
8285                                      ObjCEncOptions().setExpandStructures(),
8286                                      Field);
8287         else
8288           getObjCEncodingForTypeImpl(Field->getType(), S,
8289                                      ObjCEncOptions().setExpandStructures(), FD,
8290                                      NotEncodedT);
8291       }
8292     }
8293     S += '}';
8294     return;
8295   }
8296 
8297   case Type::ObjCObjectPointer: {
8298     const auto *OPT = T->castAs<ObjCObjectPointerType>();
8299     if (OPT->isObjCIdType()) {
8300       S += '@';
8301       return;
8302     }
8303 
8304     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8305       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8306       // Since this is a binary compatibility issue, need to consult with
8307       // runtime folks. Fortunately, this is a *very* obscure construct.
8308       S += '#';
8309       return;
8310     }
8311 
8312     if (OPT->isObjCQualifiedIdType()) {
8313       getObjCEncodingForTypeImpl(
8314           getObjCIdType(), S,
8315           Options.keepingOnly(ObjCEncOptions()
8316                                   .setExpandPointedToStructures()
8317                                   .setExpandStructures()),
8318           FD);
8319       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8320         // Note that we do extended encoding of protocol qualifier list
8321         // Only when doing ivar or property encoding.
8322         S += '"';
8323         for (const auto *I : OPT->quals()) {
8324           S += '<';
8325           S += I->getObjCRuntimeNameAsString();
8326           S += '>';
8327         }
8328         S += '"';
8329       }
8330       return;
8331     }
8332 
8333     S += '@';
8334     if (OPT->getInterfaceDecl() &&
8335         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8336       S += '"';
8337       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8338       for (const auto *I : OPT->quals()) {
8339         S += '<';
8340         S += I->getObjCRuntimeNameAsString();
8341         S += '>';
8342       }
8343       S += '"';
8344     }
8345     return;
8346   }
8347 
8348   // gcc just blithely ignores member pointers.
8349   // FIXME: we should do better than that.  'M' is available.
8350   case Type::MemberPointer:
8351   // This matches gcc's encoding, even though technically it is insufficient.
8352   //FIXME. We should do a better job than gcc.
8353   case Type::Vector:
8354   case Type::ExtVector:
8355   // Until we have a coherent encoding of these three types, issue warning.
8356     if (NotEncodedT)
8357       *NotEncodedT = T;
8358     return;
8359 
8360   case Type::ConstantMatrix:
8361     if (NotEncodedT)
8362       *NotEncodedT = T;
8363     return;
8364 
8365   case Type::BitInt:
8366     if (NotEncodedT)
8367       *NotEncodedT = T;
8368     return;
8369 
8370   // We could see an undeduced auto type here during error recovery.
8371   // Just ignore it.
8372   case Type::Auto:
8373   case Type::DeducedTemplateSpecialization:
8374     return;
8375 
8376   case Type::Pipe:
8377 #define ABSTRACT_TYPE(KIND, BASE)
8378 #define TYPE(KIND, BASE)
8379 #define DEPENDENT_TYPE(KIND, BASE) \
8380   case Type::KIND:
8381 #define NON_CANONICAL_TYPE(KIND, BASE) \
8382   case Type::KIND:
8383 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8384   case Type::KIND:
8385 #include "clang/AST/TypeNodes.inc"
8386     llvm_unreachable("@encode for dependent type!");
8387   }
8388   llvm_unreachable("bad type kind!");
8389 }
8390 
8391 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8392                                                  std::string &S,
8393                                                  const FieldDecl *FD,
8394                                                  bool includeVBases,
8395                                                  QualType *NotEncodedT) const {
8396   assert(RDecl && "Expected non-null RecordDecl");
8397   assert(!RDecl->isUnion() && "Should not be called for unions");
8398   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8399     return;
8400 
8401   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8402   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8403   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8404 
8405   if (CXXRec) {
8406     for (const auto &BI : CXXRec->bases()) {
8407       if (!BI.isVirtual()) {
8408         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8409         if (base->isEmpty())
8410           continue;
8411         uint64_t offs = toBits(layout.getBaseClassOffset(base));
8412         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8413                                   std::make_pair(offs, base));
8414       }
8415     }
8416   }
8417 
8418   unsigned i = 0;
8419   for (FieldDecl *Field : RDecl->fields()) {
8420     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8421       continue;
8422     uint64_t offs = layout.getFieldOffset(i);
8423     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8424                               std::make_pair(offs, Field));
8425     ++i;
8426   }
8427 
8428   if (CXXRec && includeVBases) {
8429     for (const auto &BI : CXXRec->vbases()) {
8430       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8431       if (base->isEmpty())
8432         continue;
8433       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8434       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8435           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8436         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8437                                   std::make_pair(offs, base));
8438     }
8439   }
8440 
8441   CharUnits size;
8442   if (CXXRec) {
8443     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8444   } else {
8445     size = layout.getSize();
8446   }
8447 
8448 #ifndef NDEBUG
8449   uint64_t CurOffs = 0;
8450 #endif
8451   std::multimap<uint64_t, NamedDecl *>::iterator
8452     CurLayObj = FieldOrBaseOffsets.begin();
8453 
8454   if (CXXRec && CXXRec->isDynamicClass() &&
8455       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8456     if (FD) {
8457       S += "\"_vptr$";
8458       std::string recname = CXXRec->getNameAsString();
8459       if (recname.empty()) recname = "?";
8460       S += recname;
8461       S += '"';
8462     }
8463     S += "^^?";
8464 #ifndef NDEBUG
8465     CurOffs += getTypeSize(VoidPtrTy);
8466 #endif
8467   }
8468 
8469   if (!RDecl->hasFlexibleArrayMember()) {
8470     // Mark the end of the structure.
8471     uint64_t offs = toBits(size);
8472     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8473                               std::make_pair(offs, nullptr));
8474   }
8475 
8476   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8477 #ifndef NDEBUG
8478     assert(CurOffs <= CurLayObj->first);
8479     if (CurOffs < CurLayObj->first) {
8480       uint64_t padding = CurLayObj->first - CurOffs;
8481       // FIXME: There doesn't seem to be a way to indicate in the encoding that
8482       // packing/alignment of members is different that normal, in which case
8483       // the encoding will be out-of-sync with the real layout.
8484       // If the runtime switches to just consider the size of types without
8485       // taking into account alignment, we could make padding explicit in the
8486       // encoding (e.g. using arrays of chars). The encoding strings would be
8487       // longer then though.
8488       CurOffs += padding;
8489     }
8490 #endif
8491 
8492     NamedDecl *dcl = CurLayObj->second;
8493     if (!dcl)
8494       break; // reached end of structure.
8495 
8496     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8497       // We expand the bases without their virtual bases since those are going
8498       // in the initial structure. Note that this differs from gcc which
8499       // expands virtual bases each time one is encountered in the hierarchy,
8500       // making the encoding type bigger than it really is.
8501       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8502                                       NotEncodedT);
8503       assert(!base->isEmpty());
8504 #ifndef NDEBUG
8505       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8506 #endif
8507     } else {
8508       const auto *field = cast<FieldDecl>(dcl);
8509       if (FD) {
8510         S += '"';
8511         S += field->getNameAsString();
8512         S += '"';
8513       }
8514 
8515       if (field->isBitField()) {
8516         EncodeBitField(this, S, field->getType(), field);
8517 #ifndef NDEBUG
8518         CurOffs += field->getBitWidthValue(*this);
8519 #endif
8520       } else {
8521         QualType qt = field->getType();
8522         getLegacyIntegralTypeEncoding(qt);
8523         getObjCEncodingForTypeImpl(
8524             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8525             FD, NotEncodedT);
8526 #ifndef NDEBUG
8527         CurOffs += getTypeSize(field->getType());
8528 #endif
8529       }
8530     }
8531   }
8532 }
8533 
8534 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
8535                                                  std::string& S) const {
8536   if (QT & Decl::OBJC_TQ_In)
8537     S += 'n';
8538   if (QT & Decl::OBJC_TQ_Inout)
8539     S += 'N';
8540   if (QT & Decl::OBJC_TQ_Out)
8541     S += 'o';
8542   if (QT & Decl::OBJC_TQ_Bycopy)
8543     S += 'O';
8544   if (QT & Decl::OBJC_TQ_Byref)
8545     S += 'R';
8546   if (QT & Decl::OBJC_TQ_Oneway)
8547     S += 'V';
8548 }
8549 
8550 TypedefDecl *ASTContext::getObjCIdDecl() const {
8551   if (!ObjCIdDecl) {
8552     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
8553     T = getObjCObjectPointerType(T);
8554     ObjCIdDecl = buildImplicitTypedef(T, "id");
8555   }
8556   return ObjCIdDecl;
8557 }
8558 
8559 TypedefDecl *ASTContext::getObjCSelDecl() const {
8560   if (!ObjCSelDecl) {
8561     QualType T = getPointerType(ObjCBuiltinSelTy);
8562     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8563   }
8564   return ObjCSelDecl;
8565 }
8566 
8567 TypedefDecl *ASTContext::getObjCClassDecl() const {
8568   if (!ObjCClassDecl) {
8569     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
8570     T = getObjCObjectPointerType(T);
8571     ObjCClassDecl = buildImplicitTypedef(T, "Class");
8572   }
8573   return ObjCClassDecl;
8574 }
8575 
8576 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
8577   if (!ObjCProtocolClassDecl) {
8578     ObjCProtocolClassDecl
8579       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
8580                                   SourceLocation(),
8581                                   &Idents.get("Protocol"),
8582                                   /*typeParamList=*/nullptr,
8583                                   /*PrevDecl=*/nullptr,
8584                                   SourceLocation(), true);
8585   }
8586 
8587   return ObjCProtocolClassDecl;
8588 }
8589 
8590 //===----------------------------------------------------------------------===//
8591 // __builtin_va_list Construction Functions
8592 //===----------------------------------------------------------------------===//
8593 
8594 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
8595                                                  StringRef Name) {
8596   // typedef char* __builtin[_ms]_va_list;
8597   QualType T = Context->getPointerType(Context->CharTy);
8598   return Context->buildImplicitTypedef(T, Name);
8599 }
8600 
8601 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
8602   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8603 }
8604 
8605 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
8606   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8607 }
8608 
8609 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
8610   // typedef void* __builtin_va_list;
8611   QualType T = Context->getPointerType(Context->VoidTy);
8612   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8613 }
8614 
8615 static TypedefDecl *
8616 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
8617   // struct __va_list
8618   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8619   if (Context->getLangOpts().CPlusPlus) {
8620     // namespace std { struct __va_list {
8621     auto *NS = NamespaceDecl::Create(
8622         const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8623         /*Inline*/ false, SourceLocation(), SourceLocation(),
8624         &Context->Idents.get("std"),
8625         /*PrevDecl*/ nullptr);
8626     NS->setImplicit();
8627     VaListTagDecl->setDeclContext(NS);
8628   }
8629 
8630   VaListTagDecl->startDefinition();
8631 
8632   const size_t NumFields = 5;
8633   QualType FieldTypes[NumFields];
8634   const char *FieldNames[NumFields];
8635 
8636   // void *__stack;
8637   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8638   FieldNames[0] = "__stack";
8639 
8640   // void *__gr_top;
8641   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8642   FieldNames[1] = "__gr_top";
8643 
8644   // void *__vr_top;
8645   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8646   FieldNames[2] = "__vr_top";
8647 
8648   // int __gr_offs;
8649   FieldTypes[3] = Context->IntTy;
8650   FieldNames[3] = "__gr_offs";
8651 
8652   // int __vr_offs;
8653   FieldTypes[4] = Context->IntTy;
8654   FieldNames[4] = "__vr_offs";
8655 
8656   // Create fields
8657   for (unsigned i = 0; i < NumFields; ++i) {
8658     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8659                                          VaListTagDecl,
8660                                          SourceLocation(),
8661                                          SourceLocation(),
8662                                          &Context->Idents.get(FieldNames[i]),
8663                                          FieldTypes[i], /*TInfo=*/nullptr,
8664                                          /*BitWidth=*/nullptr,
8665                                          /*Mutable=*/false,
8666                                          ICIS_NoInit);
8667     Field->setAccess(AS_public);
8668     VaListTagDecl->addDecl(Field);
8669   }
8670   VaListTagDecl->completeDefinition();
8671   Context->VaListTagDecl = VaListTagDecl;
8672   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8673 
8674   // } __builtin_va_list;
8675   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8676 }
8677 
8678 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8679   // typedef struct __va_list_tag {
8680   RecordDecl *VaListTagDecl;
8681 
8682   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8683   VaListTagDecl->startDefinition();
8684 
8685   const size_t NumFields = 5;
8686   QualType FieldTypes[NumFields];
8687   const char *FieldNames[NumFields];
8688 
8689   //   unsigned char gpr;
8690   FieldTypes[0] = Context->UnsignedCharTy;
8691   FieldNames[0] = "gpr";
8692 
8693   //   unsigned char fpr;
8694   FieldTypes[1] = Context->UnsignedCharTy;
8695   FieldNames[1] = "fpr";
8696 
8697   //   unsigned short reserved;
8698   FieldTypes[2] = Context->UnsignedShortTy;
8699   FieldNames[2] = "reserved";
8700 
8701   //   void* overflow_arg_area;
8702   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8703   FieldNames[3] = "overflow_arg_area";
8704 
8705   //   void* reg_save_area;
8706   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8707   FieldNames[4] = "reg_save_area";
8708 
8709   // Create fields
8710   for (unsigned i = 0; i < NumFields; ++i) {
8711     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8712                                          SourceLocation(),
8713                                          SourceLocation(),
8714                                          &Context->Idents.get(FieldNames[i]),
8715                                          FieldTypes[i], /*TInfo=*/nullptr,
8716                                          /*BitWidth=*/nullptr,
8717                                          /*Mutable=*/false,
8718                                          ICIS_NoInit);
8719     Field->setAccess(AS_public);
8720     VaListTagDecl->addDecl(Field);
8721   }
8722   VaListTagDecl->completeDefinition();
8723   Context->VaListTagDecl = VaListTagDecl;
8724   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8725 
8726   // } __va_list_tag;
8727   TypedefDecl *VaListTagTypedefDecl =
8728       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8729 
8730   QualType VaListTagTypedefType =
8731     Context->getTypedefType(VaListTagTypedefDecl);
8732 
8733   // typedef __va_list_tag __builtin_va_list[1];
8734   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8735   QualType VaListTagArrayType
8736     = Context->getConstantArrayType(VaListTagTypedefType,
8737                                     Size, nullptr, ArrayType::Normal, 0);
8738   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8739 }
8740 
8741 static TypedefDecl *
8742 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8743   // struct __va_list_tag {
8744   RecordDecl *VaListTagDecl;
8745   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8746   VaListTagDecl->startDefinition();
8747 
8748   const size_t NumFields = 4;
8749   QualType FieldTypes[NumFields];
8750   const char *FieldNames[NumFields];
8751 
8752   //   unsigned gp_offset;
8753   FieldTypes[0] = Context->UnsignedIntTy;
8754   FieldNames[0] = "gp_offset";
8755 
8756   //   unsigned fp_offset;
8757   FieldTypes[1] = Context->UnsignedIntTy;
8758   FieldNames[1] = "fp_offset";
8759 
8760   //   void* overflow_arg_area;
8761   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8762   FieldNames[2] = "overflow_arg_area";
8763 
8764   //   void* reg_save_area;
8765   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8766   FieldNames[3] = "reg_save_area";
8767 
8768   // Create fields
8769   for (unsigned i = 0; i < NumFields; ++i) {
8770     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8771                                          VaListTagDecl,
8772                                          SourceLocation(),
8773                                          SourceLocation(),
8774                                          &Context->Idents.get(FieldNames[i]),
8775                                          FieldTypes[i], /*TInfo=*/nullptr,
8776                                          /*BitWidth=*/nullptr,
8777                                          /*Mutable=*/false,
8778                                          ICIS_NoInit);
8779     Field->setAccess(AS_public);
8780     VaListTagDecl->addDecl(Field);
8781   }
8782   VaListTagDecl->completeDefinition();
8783   Context->VaListTagDecl = VaListTagDecl;
8784   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8785 
8786   // };
8787 
8788   // typedef struct __va_list_tag __builtin_va_list[1];
8789   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8790   QualType VaListTagArrayType = Context->getConstantArrayType(
8791       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8792   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8793 }
8794 
8795 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8796   // typedef int __builtin_va_list[4];
8797   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8798   QualType IntArrayType = Context->getConstantArrayType(
8799       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8800   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8801 }
8802 
8803 static TypedefDecl *
8804 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8805   // struct __va_list
8806   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8807   if (Context->getLangOpts().CPlusPlus) {
8808     // namespace std { struct __va_list {
8809     NamespaceDecl *NS;
8810     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8811                                Context->getTranslationUnitDecl(),
8812                                /*Inline*/false, SourceLocation(),
8813                                SourceLocation(), &Context->Idents.get("std"),
8814                                /*PrevDecl*/ nullptr);
8815     NS->setImplicit();
8816     VaListDecl->setDeclContext(NS);
8817   }
8818 
8819   VaListDecl->startDefinition();
8820 
8821   // void * __ap;
8822   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8823                                        VaListDecl,
8824                                        SourceLocation(),
8825                                        SourceLocation(),
8826                                        &Context->Idents.get("__ap"),
8827                                        Context->getPointerType(Context->VoidTy),
8828                                        /*TInfo=*/nullptr,
8829                                        /*BitWidth=*/nullptr,
8830                                        /*Mutable=*/false,
8831                                        ICIS_NoInit);
8832   Field->setAccess(AS_public);
8833   VaListDecl->addDecl(Field);
8834 
8835   // };
8836   VaListDecl->completeDefinition();
8837   Context->VaListTagDecl = VaListDecl;
8838 
8839   // typedef struct __va_list __builtin_va_list;
8840   QualType T = Context->getRecordType(VaListDecl);
8841   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8842 }
8843 
8844 static TypedefDecl *
8845 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8846   // struct __va_list_tag {
8847   RecordDecl *VaListTagDecl;
8848   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8849   VaListTagDecl->startDefinition();
8850 
8851   const size_t NumFields = 4;
8852   QualType FieldTypes[NumFields];
8853   const char *FieldNames[NumFields];
8854 
8855   //   long __gpr;
8856   FieldTypes[0] = Context->LongTy;
8857   FieldNames[0] = "__gpr";
8858 
8859   //   long __fpr;
8860   FieldTypes[1] = Context->LongTy;
8861   FieldNames[1] = "__fpr";
8862 
8863   //   void *__overflow_arg_area;
8864   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8865   FieldNames[2] = "__overflow_arg_area";
8866 
8867   //   void *__reg_save_area;
8868   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8869   FieldNames[3] = "__reg_save_area";
8870 
8871   // Create fields
8872   for (unsigned i = 0; i < NumFields; ++i) {
8873     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8874                                          VaListTagDecl,
8875                                          SourceLocation(),
8876                                          SourceLocation(),
8877                                          &Context->Idents.get(FieldNames[i]),
8878                                          FieldTypes[i], /*TInfo=*/nullptr,
8879                                          /*BitWidth=*/nullptr,
8880                                          /*Mutable=*/false,
8881                                          ICIS_NoInit);
8882     Field->setAccess(AS_public);
8883     VaListTagDecl->addDecl(Field);
8884   }
8885   VaListTagDecl->completeDefinition();
8886   Context->VaListTagDecl = VaListTagDecl;
8887   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8888 
8889   // };
8890 
8891   // typedef __va_list_tag __builtin_va_list[1];
8892   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8893   QualType VaListTagArrayType = Context->getConstantArrayType(
8894       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8895 
8896   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8897 }
8898 
8899 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8900   // typedef struct __va_list_tag {
8901   RecordDecl *VaListTagDecl;
8902   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8903   VaListTagDecl->startDefinition();
8904 
8905   const size_t NumFields = 3;
8906   QualType FieldTypes[NumFields];
8907   const char *FieldNames[NumFields];
8908 
8909   //   void *CurrentSavedRegisterArea;
8910   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8911   FieldNames[0] = "__current_saved_reg_area_pointer";
8912 
8913   //   void *SavedRegAreaEnd;
8914   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8915   FieldNames[1] = "__saved_reg_area_end_pointer";
8916 
8917   //   void *OverflowArea;
8918   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8919   FieldNames[2] = "__overflow_area_pointer";
8920 
8921   // Create fields
8922   for (unsigned i = 0; i < NumFields; ++i) {
8923     FieldDecl *Field = FieldDecl::Create(
8924         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8925         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8926         /*TInfo=*/nullptr,
8927         /*BitWidth=*/nullptr,
8928         /*Mutable=*/false, ICIS_NoInit);
8929     Field->setAccess(AS_public);
8930     VaListTagDecl->addDecl(Field);
8931   }
8932   VaListTagDecl->completeDefinition();
8933   Context->VaListTagDecl = VaListTagDecl;
8934   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8935 
8936   // } __va_list_tag;
8937   TypedefDecl *VaListTagTypedefDecl =
8938       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8939 
8940   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8941 
8942   // typedef __va_list_tag __builtin_va_list[1];
8943   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8944   QualType VaListTagArrayType = Context->getConstantArrayType(
8945       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8946 
8947   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8948 }
8949 
8950 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8951                                      TargetInfo::BuiltinVaListKind Kind) {
8952   switch (Kind) {
8953   case TargetInfo::CharPtrBuiltinVaList:
8954     return CreateCharPtrBuiltinVaListDecl(Context);
8955   case TargetInfo::VoidPtrBuiltinVaList:
8956     return CreateVoidPtrBuiltinVaListDecl(Context);
8957   case TargetInfo::AArch64ABIBuiltinVaList:
8958     return CreateAArch64ABIBuiltinVaListDecl(Context);
8959   case TargetInfo::PowerABIBuiltinVaList:
8960     return CreatePowerABIBuiltinVaListDecl(Context);
8961   case TargetInfo::X86_64ABIBuiltinVaList:
8962     return CreateX86_64ABIBuiltinVaListDecl(Context);
8963   case TargetInfo::PNaClABIBuiltinVaList:
8964     return CreatePNaClABIBuiltinVaListDecl(Context);
8965   case TargetInfo::AAPCSABIBuiltinVaList:
8966     return CreateAAPCSABIBuiltinVaListDecl(Context);
8967   case TargetInfo::SystemZBuiltinVaList:
8968     return CreateSystemZBuiltinVaListDecl(Context);
8969   case TargetInfo::HexagonBuiltinVaList:
8970     return CreateHexagonBuiltinVaListDecl(Context);
8971   }
8972 
8973   llvm_unreachable("Unhandled __builtin_va_list type kind");
8974 }
8975 
8976 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8977   if (!BuiltinVaListDecl) {
8978     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8979     assert(BuiltinVaListDecl->isImplicit());
8980   }
8981 
8982   return BuiltinVaListDecl;
8983 }
8984 
8985 Decl *ASTContext::getVaListTagDecl() const {
8986   // Force the creation of VaListTagDecl by building the __builtin_va_list
8987   // declaration.
8988   if (!VaListTagDecl)
8989     (void)getBuiltinVaListDecl();
8990 
8991   return VaListTagDecl;
8992 }
8993 
8994 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8995   if (!BuiltinMSVaListDecl)
8996     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8997 
8998   return BuiltinMSVaListDecl;
8999 }
9000 
9001 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
9002   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
9003 }
9004 
9005 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
9006   assert(ObjCConstantStringType.isNull() &&
9007          "'NSConstantString' type already set!");
9008 
9009   ObjCConstantStringType = getObjCInterfaceType(Decl);
9010 }
9011 
9012 /// Retrieve the template name that corresponds to a non-empty
9013 /// lookup.
9014 TemplateName
9015 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
9016                                       UnresolvedSetIterator End) const {
9017   unsigned size = End - Begin;
9018   assert(size > 1 && "set is not overloaded!");
9019 
9020   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9021                           size * sizeof(FunctionTemplateDecl*));
9022   auto *OT = new (memory) OverloadedTemplateStorage(size);
9023 
9024   NamedDecl **Storage = OT->getStorage();
9025   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9026     NamedDecl *D = *I;
9027     assert(isa<FunctionTemplateDecl>(D) ||
9028            isa<UnresolvedUsingValueDecl>(D) ||
9029            (isa<UsingShadowDecl>(D) &&
9030             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9031     *Storage++ = D;
9032   }
9033 
9034   return TemplateName(OT);
9035 }
9036 
9037 /// Retrieve a template name representing an unqualified-id that has been
9038 /// assumed to name a template for ADL purposes.
9039 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
9040   auto *OT = new (*this) AssumedTemplateStorage(Name);
9041   return TemplateName(OT);
9042 }
9043 
9044 /// Retrieve the template name that represents a qualified
9045 /// template name such as \c std::vector.
9046 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
9047                                                   bool TemplateKeyword,
9048                                                   TemplateName Template) const {
9049   assert(NNS && "Missing nested-name-specifier in qualified template name");
9050 
9051   // FIXME: Canonicalization?
9052   llvm::FoldingSetNodeID ID;
9053   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9054 
9055   void *InsertPos = nullptr;
9056   QualifiedTemplateName *QTN =
9057     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9058   if (!QTN) {
9059     QTN = new (*this, alignof(QualifiedTemplateName))
9060         QualifiedTemplateName(NNS, TemplateKeyword, Template);
9061     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9062   }
9063 
9064   return TemplateName(QTN);
9065 }
9066 
9067 /// Retrieve the template name that represents a dependent
9068 /// template name such as \c MetaFun::template apply.
9069 TemplateName
9070 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9071                                      const IdentifierInfo *Name) const {
9072   assert((!NNS || NNS->isDependent()) &&
9073          "Nested name specifier must be dependent");
9074 
9075   llvm::FoldingSetNodeID ID;
9076   DependentTemplateName::Profile(ID, NNS, Name);
9077 
9078   void *InsertPos = nullptr;
9079   DependentTemplateName *QTN =
9080     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9081 
9082   if (QTN)
9083     return TemplateName(QTN);
9084 
9085   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9086   if (CanonNNS == NNS) {
9087     QTN = new (*this, alignof(DependentTemplateName))
9088         DependentTemplateName(NNS, Name);
9089   } else {
9090     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9091     QTN = new (*this, alignof(DependentTemplateName))
9092         DependentTemplateName(NNS, Name, Canon);
9093     DependentTemplateName *CheckQTN =
9094       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9095     assert(!CheckQTN && "Dependent type name canonicalization broken");
9096     (void)CheckQTN;
9097   }
9098 
9099   DependentTemplateNames.InsertNode(QTN, InsertPos);
9100   return TemplateName(QTN);
9101 }
9102 
9103 /// Retrieve the template name that represents a dependent
9104 /// template name such as \c MetaFun::template operator+.
9105 TemplateName
9106 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9107                                      OverloadedOperatorKind Operator) const {
9108   assert((!NNS || NNS->isDependent()) &&
9109          "Nested name specifier must be dependent");
9110 
9111   llvm::FoldingSetNodeID ID;
9112   DependentTemplateName::Profile(ID, NNS, Operator);
9113 
9114   void *InsertPos = nullptr;
9115   DependentTemplateName *QTN
9116     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9117 
9118   if (QTN)
9119     return TemplateName(QTN);
9120 
9121   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9122   if (CanonNNS == NNS) {
9123     QTN = new (*this, alignof(DependentTemplateName))
9124         DependentTemplateName(NNS, Operator);
9125   } else {
9126     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9127     QTN = new (*this, alignof(DependentTemplateName))
9128         DependentTemplateName(NNS, Operator, Canon);
9129 
9130     DependentTemplateName *CheckQTN
9131       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9132     assert(!CheckQTN && "Dependent template name canonicalization broken");
9133     (void)CheckQTN;
9134   }
9135 
9136   DependentTemplateNames.InsertNode(QTN, InsertPos);
9137   return TemplateName(QTN);
9138 }
9139 
9140 TemplateName
9141 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
9142                                          TemplateName replacement) const {
9143   llvm::FoldingSetNodeID ID;
9144   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
9145 
9146   void *insertPos = nullptr;
9147   SubstTemplateTemplateParmStorage *subst
9148     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9149 
9150   if (!subst) {
9151     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
9152     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9153   }
9154 
9155   return TemplateName(subst);
9156 }
9157 
9158 TemplateName
9159 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
9160                                        const TemplateArgument &ArgPack) const {
9161   auto &Self = const_cast<ASTContext &>(*this);
9162   llvm::FoldingSetNodeID ID;
9163   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
9164 
9165   void *InsertPos = nullptr;
9166   SubstTemplateTemplateParmPackStorage *Subst
9167     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9168 
9169   if (!Subst) {
9170     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
9171                                                            ArgPack.pack_size(),
9172                                                          ArgPack.pack_begin());
9173     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9174   }
9175 
9176   return TemplateName(Subst);
9177 }
9178 
9179 /// getFromTargetType - Given one of the integer types provided by
9180 /// TargetInfo, produce the corresponding type. The unsigned @p Type
9181 /// is actually a value of type @c TargetInfo::IntType.
9182 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9183   switch (Type) {
9184   case TargetInfo::NoInt: return {};
9185   case TargetInfo::SignedChar: return SignedCharTy;
9186   case TargetInfo::UnsignedChar: return UnsignedCharTy;
9187   case TargetInfo::SignedShort: return ShortTy;
9188   case TargetInfo::UnsignedShort: return UnsignedShortTy;
9189   case TargetInfo::SignedInt: return IntTy;
9190   case TargetInfo::UnsignedInt: return UnsignedIntTy;
9191   case TargetInfo::SignedLong: return LongTy;
9192   case TargetInfo::UnsignedLong: return UnsignedLongTy;
9193   case TargetInfo::SignedLongLong: return LongLongTy;
9194   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
9195   }
9196 
9197   llvm_unreachable("Unhandled TargetInfo::IntType value");
9198 }
9199 
9200 //===----------------------------------------------------------------------===//
9201 //                        Type Predicates.
9202 //===----------------------------------------------------------------------===//
9203 
9204 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9205 /// garbage collection attribute.
9206 ///
9207 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
9208   if (getLangOpts().getGC() == LangOptions::NonGC)
9209     return Qualifiers::GCNone;
9210 
9211   assert(getLangOpts().ObjC);
9212   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9213 
9214   // Default behaviour under objective-C's gc is for ObjC pointers
9215   // (or pointers to them) be treated as though they were declared
9216   // as __strong.
9217   if (GCAttrs == Qualifiers::GCNone) {
9218     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
9219       return Qualifiers::Strong;
9220     else if (Ty->isPointerType())
9221       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
9222   } else {
9223     // It's not valid to set GC attributes on anything that isn't a
9224     // pointer.
9225 #ifndef NDEBUG
9226     QualType CT = Ty->getCanonicalTypeInternal();
9227     while (const auto *AT = dyn_cast<ArrayType>(CT))
9228       CT = AT->getElementType();
9229     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9230 #endif
9231   }
9232   return GCAttrs;
9233 }
9234 
9235 //===----------------------------------------------------------------------===//
9236 //                        Type Compatibility Testing
9237 //===----------------------------------------------------------------------===//
9238 
9239 /// areCompatVectorTypes - Return true if the two specified vector types are
9240 /// compatible.
9241 static bool areCompatVectorTypes(const VectorType *LHS,
9242                                  const VectorType *RHS) {
9243   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9244   return LHS->getElementType() == RHS->getElementType() &&
9245          LHS->getNumElements() == RHS->getNumElements();
9246 }
9247 
9248 /// areCompatMatrixTypes - Return true if the two specified matrix types are
9249 /// compatible.
9250 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
9251                                  const ConstantMatrixType *RHS) {
9252   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9253   return LHS->getElementType() == RHS->getElementType() &&
9254          LHS->getNumRows() == RHS->getNumRows() &&
9255          LHS->getNumColumns() == RHS->getNumColumns();
9256 }
9257 
9258 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
9259                                           QualType SecondVec) {
9260   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9261   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9262 
9263   if (hasSameUnqualifiedType(FirstVec, SecondVec))
9264     return true;
9265 
9266   // Treat Neon vector types and most AltiVec vector types as if they are the
9267   // equivalent GCC vector types.
9268   const auto *First = FirstVec->castAs<VectorType>();
9269   const auto *Second = SecondVec->castAs<VectorType>();
9270   if (First->getNumElements() == Second->getNumElements() &&
9271       hasSameType(First->getElementType(), Second->getElementType()) &&
9272       First->getVectorKind() != VectorType::AltiVecPixel &&
9273       First->getVectorKind() != VectorType::AltiVecBool &&
9274       Second->getVectorKind() != VectorType::AltiVecPixel &&
9275       Second->getVectorKind() != VectorType::AltiVecBool &&
9276       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9277       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
9278       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9279       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
9280     return true;
9281 
9282   return false;
9283 }
9284 
9285 /// getSVETypeSize - Return SVE vector or predicate register size.
9286 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9287   assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
9288   return Ty->getKind() == BuiltinType::SveBool
9289              ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
9290              : Context.getLangOpts().VScaleMin * 128;
9291 }
9292 
9293 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
9294                                        QualType SecondType) {
9295   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9296           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9297          "Expected SVE builtin type and vector type!");
9298 
9299   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9300     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9301       if (const auto *VT = SecondType->getAs<VectorType>()) {
9302         // Predicates have the same representation as uint8 so we also have to
9303         // check the kind to make these types incompatible.
9304         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
9305           return BT->getKind() == BuiltinType::SveBool;
9306         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
9307           return VT->getElementType().getCanonicalType() ==
9308                  FirstType->getSveEltType(*this);
9309         else if (VT->getVectorKind() == VectorType::GenericVector)
9310           return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9311                  hasSameType(VT->getElementType(),
9312                              getBuiltinVectorTypeInfo(BT).ElementType);
9313       }
9314     }
9315     return false;
9316   };
9317 
9318   return IsValidCast(FirstType, SecondType) ||
9319          IsValidCast(SecondType, FirstType);
9320 }
9321 
9322 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
9323                                           QualType SecondType) {
9324   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9325           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9326          "Expected SVE builtin type and vector type!");
9327 
9328   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9329     const auto *BT = FirstType->getAs<BuiltinType>();
9330     if (!BT)
9331       return false;
9332 
9333     const auto *VecTy = SecondType->getAs<VectorType>();
9334     if (VecTy &&
9335         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9336          VecTy->getVectorKind() == VectorType::GenericVector)) {
9337       const LangOptions::LaxVectorConversionKind LVCKind =
9338           getLangOpts().getLaxVectorConversions();
9339 
9340       // Can not convert between sve predicates and sve vectors because of
9341       // different size.
9342       if (BT->getKind() == BuiltinType::SveBool &&
9343           VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
9344         return false;
9345 
9346       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9347       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9348       // converts to VLAT and VLAT implicitly converts to GNUT."
9349       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9350       // predicates.
9351       if (VecTy->getVectorKind() == VectorType::GenericVector &&
9352           getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9353         return false;
9354 
9355       // If -flax-vector-conversions=all is specified, the types are
9356       // certainly compatible.
9357       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9358         return true;
9359 
9360       // If -flax-vector-conversions=integer is specified, the types are
9361       // compatible if the elements are integer types.
9362       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9363         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9364                FirstType->getSveEltType(*this)->isIntegerType();
9365     }
9366 
9367     return false;
9368   };
9369 
9370   return IsLaxCompatible(FirstType, SecondType) ||
9371          IsLaxCompatible(SecondType, FirstType);
9372 }
9373 
9374 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
9375   while (true) {
9376     // __strong id
9377     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9378       if (Attr->getAttrKind() == attr::ObjCOwnership)
9379         return true;
9380 
9381       Ty = Attr->getModifiedType();
9382 
9383     // X *__strong (...)
9384     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9385       Ty = Paren->getInnerType();
9386 
9387     // We do not want to look through typedefs, typeof(expr),
9388     // typeof(type), or any other way that the type is somehow
9389     // abstracted.
9390     } else {
9391       return false;
9392     }
9393   }
9394 }
9395 
9396 //===----------------------------------------------------------------------===//
9397 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9398 //===----------------------------------------------------------------------===//
9399 
9400 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9401 /// inheritance hierarchy of 'rProto'.
9402 bool
9403 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
9404                                            ObjCProtocolDecl *rProto) const {
9405   if (declaresSameEntity(lProto, rProto))
9406     return true;
9407   for (auto *PI : rProto->protocols())
9408     if (ProtocolCompatibleWithProtocol(lProto, PI))
9409       return true;
9410   return false;
9411 }
9412 
9413 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
9414 /// Class<pr1, ...>.
9415 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
9416     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9417   for (auto *lhsProto : lhs->quals()) {
9418     bool match = false;
9419     for (auto *rhsProto : rhs->quals()) {
9420       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9421         match = true;
9422         break;
9423       }
9424     }
9425     if (!match)
9426       return false;
9427   }
9428   return true;
9429 }
9430 
9431 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9432 /// ObjCQualifiedIDType.
9433 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
9434     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9435     bool compare) {
9436   // Allow id<P..> and an 'id' in all cases.
9437   if (lhs->isObjCIdType() || rhs->isObjCIdType())
9438     return true;
9439 
9440   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9441   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9442       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
9443     return false;
9444 
9445   if (lhs->isObjCQualifiedIdType()) {
9446     if (rhs->qual_empty()) {
9447       // If the RHS is a unqualified interface pointer "NSString*",
9448       // make sure we check the class hierarchy.
9449       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9450         for (auto *I : lhs->quals()) {
9451           // when comparing an id<P> on lhs with a static type on rhs,
9452           // see if static class implements all of id's protocols, directly or
9453           // through its super class and categories.
9454           if (!rhsID->ClassImplementsProtocol(I, true))
9455             return false;
9456         }
9457       }
9458       // If there are no qualifiers and no interface, we have an 'id'.
9459       return true;
9460     }
9461     // Both the right and left sides have qualifiers.
9462     for (auto *lhsProto : lhs->quals()) {
9463       bool match = false;
9464 
9465       // when comparing an id<P> on lhs with a static type on rhs,
9466       // see if static class implements all of id's protocols, directly or
9467       // through its super class and categories.
9468       for (auto *rhsProto : rhs->quals()) {
9469         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9470             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9471           match = true;
9472           break;
9473         }
9474       }
9475       // If the RHS is a qualified interface pointer "NSString<P>*",
9476       // make sure we check the class hierarchy.
9477       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9478         for (auto *I : lhs->quals()) {
9479           // when comparing an id<P> on lhs with a static type on rhs,
9480           // see if static class implements all of id's protocols, directly or
9481           // through its super class and categories.
9482           if (rhsID->ClassImplementsProtocol(I, true)) {
9483             match = true;
9484             break;
9485           }
9486         }
9487       }
9488       if (!match)
9489         return false;
9490     }
9491 
9492     return true;
9493   }
9494 
9495   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9496 
9497   if (lhs->getInterfaceType()) {
9498     // If both the right and left sides have qualifiers.
9499     for (auto *lhsProto : lhs->quals()) {
9500       bool match = false;
9501 
9502       // when comparing an id<P> on rhs with a static type on lhs,
9503       // see if static class implements all of id's protocols, directly or
9504       // through its super class and categories.
9505       // First, lhs protocols in the qualifier list must be found, direct
9506       // or indirect in rhs's qualifier list or it is a mismatch.
9507       for (auto *rhsProto : rhs->quals()) {
9508         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9509             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9510           match = true;
9511           break;
9512         }
9513       }
9514       if (!match)
9515         return false;
9516     }
9517 
9518     // Static class's protocols, or its super class or category protocols
9519     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9520     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9521       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9522       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9523       // This is rather dubious but matches gcc's behavior. If lhs has
9524       // no type qualifier and its class has no static protocol(s)
9525       // assume that it is mismatch.
9526       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9527         return false;
9528       for (auto *lhsProto : LHSInheritedProtocols) {
9529         bool match = false;
9530         for (auto *rhsProto : rhs->quals()) {
9531           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9532               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9533             match = true;
9534             break;
9535           }
9536         }
9537         if (!match)
9538           return false;
9539       }
9540     }
9541     return true;
9542   }
9543   return false;
9544 }
9545 
9546 /// canAssignObjCInterfaces - Return true if the two interface types are
9547 /// compatible for assignment from RHS to LHS.  This handles validation of any
9548 /// protocol qualifiers on the LHS or RHS.
9549 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
9550                                          const ObjCObjectPointerType *RHSOPT) {
9551   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9552   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9553 
9554   // If either type represents the built-in 'id' type, return true.
9555   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9556     return true;
9557 
9558   // Function object that propagates a successful result or handles
9559   // __kindof types.
9560   auto finish = [&](bool succeeded) -> bool {
9561     if (succeeded)
9562       return true;
9563 
9564     if (!RHS->isKindOfType())
9565       return false;
9566 
9567     // Strip off __kindof and protocol qualifiers, then check whether
9568     // we can assign the other way.
9569     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9570                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9571   };
9572 
9573   // Casts from or to id<P> are allowed when the other side has compatible
9574   // protocols.
9575   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9576     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9577   }
9578 
9579   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9580   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9581     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9582   }
9583 
9584   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9585   if (LHS->isObjCClass() && RHS->isObjCClass()) {
9586     return true;
9587   }
9588 
9589   // If we have 2 user-defined types, fall into that path.
9590   if (LHS->getInterface() && RHS->getInterface()) {
9591     return finish(canAssignObjCInterfaces(LHS, RHS));
9592   }
9593 
9594   return false;
9595 }
9596 
9597 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9598 /// for providing type-safety for objective-c pointers used to pass/return
9599 /// arguments in block literals. When passed as arguments, passing 'A*' where
9600 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9601 /// not OK. For the return type, the opposite is not OK.
9602 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
9603                                          const ObjCObjectPointerType *LHSOPT,
9604                                          const ObjCObjectPointerType *RHSOPT,
9605                                          bool BlockReturnType) {
9606 
9607   // Function object that propagates a successful result or handles
9608   // __kindof types.
9609   auto finish = [&](bool succeeded) -> bool {
9610     if (succeeded)
9611       return true;
9612 
9613     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9614     if (!Expected->isKindOfType())
9615       return false;
9616 
9617     // Strip off __kindof and protocol qualifiers, then check whether
9618     // we can assign the other way.
9619     return canAssignObjCInterfacesInBlockPointer(
9620              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9621              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9622              BlockReturnType);
9623   };
9624 
9625   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9626     return true;
9627 
9628   if (LHSOPT->isObjCBuiltinType()) {
9629     return finish(RHSOPT->isObjCBuiltinType() ||
9630                   RHSOPT->isObjCQualifiedIdType());
9631   }
9632 
9633   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9634     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9635       // Use for block parameters previous type checking for compatibility.
9636       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9637                     // Or corrected type checking as in non-compat mode.
9638                     (!BlockReturnType &&
9639                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9640     else
9641       return finish(ObjCQualifiedIdTypesAreCompatible(
9642           (BlockReturnType ? LHSOPT : RHSOPT),
9643           (BlockReturnType ? RHSOPT : LHSOPT), false));
9644   }
9645 
9646   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9647   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9648   if (LHS && RHS)  { // We have 2 user-defined types.
9649     if (LHS != RHS) {
9650       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9651         return finish(BlockReturnType);
9652       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9653         return finish(!BlockReturnType);
9654     }
9655     else
9656       return true;
9657   }
9658   return false;
9659 }
9660 
9661 /// Comparison routine for Objective-C protocols to be used with
9662 /// llvm::array_pod_sort.
9663 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9664                                       ObjCProtocolDecl * const *rhs) {
9665   return (*lhs)->getName().compare((*rhs)->getName());
9666 }
9667 
9668 /// getIntersectionOfProtocols - This routine finds the intersection of set
9669 /// of protocols inherited from two distinct objective-c pointer objects with
9670 /// the given common base.
9671 /// It is used to build composite qualifier list of the composite type of
9672 /// the conditional expression involving two objective-c pointer objects.
9673 static
9674 void getIntersectionOfProtocols(ASTContext &Context,
9675                                 const ObjCInterfaceDecl *CommonBase,
9676                                 const ObjCObjectPointerType *LHSOPT,
9677                                 const ObjCObjectPointerType *RHSOPT,
9678       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9679 
9680   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9681   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9682   assert(LHS->getInterface() && "LHS must have an interface base");
9683   assert(RHS->getInterface() && "RHS must have an interface base");
9684 
9685   // Add all of the protocols for the LHS.
9686   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9687 
9688   // Start with the protocol qualifiers.
9689   for (auto proto : LHS->quals()) {
9690     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9691   }
9692 
9693   // Also add the protocols associated with the LHS interface.
9694   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9695 
9696   // Add all of the protocols for the RHS.
9697   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9698 
9699   // Start with the protocol qualifiers.
9700   for (auto proto : RHS->quals()) {
9701     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9702   }
9703 
9704   // Also add the protocols associated with the RHS interface.
9705   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9706 
9707   // Compute the intersection of the collected protocol sets.
9708   for (auto proto : LHSProtocolSet) {
9709     if (RHSProtocolSet.count(proto))
9710       IntersectionSet.push_back(proto);
9711   }
9712 
9713   // Compute the set of protocols that is implied by either the common type or
9714   // the protocols within the intersection.
9715   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9716   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9717 
9718   // Remove any implied protocols from the list of inherited protocols.
9719   if (!ImpliedProtocols.empty()) {
9720     llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
9721       return ImpliedProtocols.contains(proto);
9722     });
9723   }
9724 
9725   // Sort the remaining protocols by name.
9726   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9727                        compareObjCProtocolsByName);
9728 }
9729 
9730 /// Determine whether the first type is a subtype of the second.
9731 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9732                                      QualType rhs) {
9733   // Common case: two object pointers.
9734   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9735   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9736   if (lhsOPT && rhsOPT)
9737     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9738 
9739   // Two block pointers.
9740   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9741   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9742   if (lhsBlock && rhsBlock)
9743     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9744 
9745   // If either is an unqualified 'id' and the other is a block, it's
9746   // acceptable.
9747   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9748       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9749     return true;
9750 
9751   return false;
9752 }
9753 
9754 // Check that the given Objective-C type argument lists are equivalent.
9755 static bool sameObjCTypeArgs(ASTContext &ctx,
9756                              const ObjCInterfaceDecl *iface,
9757                              ArrayRef<QualType> lhsArgs,
9758                              ArrayRef<QualType> rhsArgs,
9759                              bool stripKindOf) {
9760   if (lhsArgs.size() != rhsArgs.size())
9761     return false;
9762 
9763   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9764   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9765     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9766       continue;
9767 
9768     switch (typeParams->begin()[i]->getVariance()) {
9769     case ObjCTypeParamVariance::Invariant:
9770       if (!stripKindOf ||
9771           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9772                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9773         return false;
9774       }
9775       break;
9776 
9777     case ObjCTypeParamVariance::Covariant:
9778       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9779         return false;
9780       break;
9781 
9782     case ObjCTypeParamVariance::Contravariant:
9783       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9784         return false;
9785       break;
9786     }
9787   }
9788 
9789   return true;
9790 }
9791 
9792 QualType ASTContext::areCommonBaseCompatible(
9793            const ObjCObjectPointerType *Lptr,
9794            const ObjCObjectPointerType *Rptr) {
9795   const ObjCObjectType *LHS = Lptr->getObjectType();
9796   const ObjCObjectType *RHS = Rptr->getObjectType();
9797   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9798   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9799 
9800   if (!LDecl || !RDecl)
9801     return {};
9802 
9803   // When either LHS or RHS is a kindof type, we should return a kindof type.
9804   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9805   // kindof(A).
9806   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9807 
9808   // Follow the left-hand side up the class hierarchy until we either hit a
9809   // root or find the RHS. Record the ancestors in case we don't find it.
9810   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9811     LHSAncestors;
9812   while (true) {
9813     // Record this ancestor. We'll need this if the common type isn't in the
9814     // path from the LHS to the root.
9815     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9816 
9817     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9818       // Get the type arguments.
9819       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9820       bool anyChanges = false;
9821       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9822         // Both have type arguments, compare them.
9823         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9824                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9825                               /*stripKindOf=*/true))
9826           return {};
9827       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9828         // If only one has type arguments, the result will not have type
9829         // arguments.
9830         LHSTypeArgs = {};
9831         anyChanges = true;
9832       }
9833 
9834       // Compute the intersection of protocols.
9835       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9836       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9837                                  Protocols);
9838       if (!Protocols.empty())
9839         anyChanges = true;
9840 
9841       // If anything in the LHS will have changed, build a new result type.
9842       // If we need to return a kindof type but LHS is not a kindof type, we
9843       // build a new result type.
9844       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9845         QualType Result = getObjCInterfaceType(LHS->getInterface());
9846         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9847                                    anyKindOf || LHS->isKindOfType());
9848         return getObjCObjectPointerType(Result);
9849       }
9850 
9851       return getObjCObjectPointerType(QualType(LHS, 0));
9852     }
9853 
9854     // Find the superclass.
9855     QualType LHSSuperType = LHS->getSuperClassType();
9856     if (LHSSuperType.isNull())
9857       break;
9858 
9859     LHS = LHSSuperType->castAs<ObjCObjectType>();
9860   }
9861 
9862   // We didn't find anything by following the LHS to its root; now check
9863   // the RHS against the cached set of ancestors.
9864   while (true) {
9865     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9866     if (KnownLHS != LHSAncestors.end()) {
9867       LHS = KnownLHS->second;
9868 
9869       // Get the type arguments.
9870       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9871       bool anyChanges = false;
9872       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9873         // Both have type arguments, compare them.
9874         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9875                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9876                               /*stripKindOf=*/true))
9877           return {};
9878       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9879         // If only one has type arguments, the result will not have type
9880         // arguments.
9881         RHSTypeArgs = {};
9882         anyChanges = true;
9883       }
9884 
9885       // Compute the intersection of protocols.
9886       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9887       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9888                                  Protocols);
9889       if (!Protocols.empty())
9890         anyChanges = true;
9891 
9892       // If we need to return a kindof type but RHS is not a kindof type, we
9893       // build a new result type.
9894       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9895         QualType Result = getObjCInterfaceType(RHS->getInterface());
9896         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9897                                    anyKindOf || RHS->isKindOfType());
9898         return getObjCObjectPointerType(Result);
9899       }
9900 
9901       return getObjCObjectPointerType(QualType(RHS, 0));
9902     }
9903 
9904     // Find the superclass of the RHS.
9905     QualType RHSSuperType = RHS->getSuperClassType();
9906     if (RHSSuperType.isNull())
9907       break;
9908 
9909     RHS = RHSSuperType->castAs<ObjCObjectType>();
9910   }
9911 
9912   return {};
9913 }
9914 
9915 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9916                                          const ObjCObjectType *RHS) {
9917   assert(LHS->getInterface() && "LHS is not an interface type");
9918   assert(RHS->getInterface() && "RHS is not an interface type");
9919 
9920   // Verify that the base decls are compatible: the RHS must be a subclass of
9921   // the LHS.
9922   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9923   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9924   if (!IsSuperClass)
9925     return false;
9926 
9927   // If the LHS has protocol qualifiers, determine whether all of them are
9928   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9929   // LHS).
9930   if (LHS->getNumProtocols() > 0) {
9931     // OK if conversion of LHS to SuperClass results in narrowing of types
9932     // ; i.e., SuperClass may implement at least one of the protocols
9933     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9934     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9935     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9936     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9937     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9938     // qualifiers.
9939     for (auto *RHSPI : RHS->quals())
9940       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9941     // If there is no protocols associated with RHS, it is not a match.
9942     if (SuperClassInheritedProtocols.empty())
9943       return false;
9944 
9945     for (const auto *LHSProto : LHS->quals()) {
9946       bool SuperImplementsProtocol = false;
9947       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9948         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9949           SuperImplementsProtocol = true;
9950           break;
9951         }
9952       if (!SuperImplementsProtocol)
9953         return false;
9954     }
9955   }
9956 
9957   // If the LHS is specialized, we may need to check type arguments.
9958   if (LHS->isSpecialized()) {
9959     // Follow the superclass chain until we've matched the LHS class in the
9960     // hierarchy. This substitutes type arguments through.
9961     const ObjCObjectType *RHSSuper = RHS;
9962     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9963       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9964 
9965     // If the RHS is specializd, compare type arguments.
9966     if (RHSSuper->isSpecialized() &&
9967         !sameObjCTypeArgs(*this, LHS->getInterface(),
9968                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9969                           /*stripKindOf=*/true)) {
9970       return false;
9971     }
9972   }
9973 
9974   return true;
9975 }
9976 
9977 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9978   // get the "pointed to" types
9979   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9980   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9981 
9982   if (!LHSOPT || !RHSOPT)
9983     return false;
9984 
9985   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9986          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9987 }
9988 
9989 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9990   return canAssignObjCInterfaces(
9991       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9992       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9993 }
9994 
9995 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9996 /// both shall have the identically qualified version of a compatible type.
9997 /// C99 6.2.7p1: Two types have compatible types if their types are the
9998 /// same. See 6.7.[2,3,5] for additional rules.
9999 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
10000                                     bool CompareUnqualified) {
10001   if (getLangOpts().CPlusPlus)
10002     return hasSameType(LHS, RHS);
10003 
10004   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10005 }
10006 
10007 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
10008   return typesAreCompatible(LHS, RHS);
10009 }
10010 
10011 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
10012   return !mergeTypes(LHS, RHS, true).isNull();
10013 }
10014 
10015 /// mergeTransparentUnionType - if T is a transparent union type and a member
10016 /// of T is compatible with SubType, return the merged type, else return
10017 /// QualType()
10018 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
10019                                                bool OfBlockPointer,
10020                                                bool Unqualified) {
10021   if (const RecordType *UT = T->getAsUnionType()) {
10022     RecordDecl *UD = UT->getDecl();
10023     if (UD->hasAttr<TransparentUnionAttr>()) {
10024       for (const auto *I : UD->fields()) {
10025         QualType ET = I->getType().getUnqualifiedType();
10026         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10027         if (!MT.isNull())
10028           return MT;
10029       }
10030     }
10031   }
10032 
10033   return {};
10034 }
10035 
10036 /// mergeFunctionParameterTypes - merge two types which appear as function
10037 /// parameter types
10038 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
10039                                                  bool OfBlockPointer,
10040                                                  bool Unqualified) {
10041   // GNU extension: two types are compatible if they appear as a function
10042   // argument, one of the types is a transparent union type and the other
10043   // type is compatible with a union member
10044   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10045                                               Unqualified);
10046   if (!lmerge.isNull())
10047     return lmerge;
10048 
10049   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10050                                               Unqualified);
10051   if (!rmerge.isNull())
10052     return rmerge;
10053 
10054   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10055 }
10056 
10057 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
10058                                         bool OfBlockPointer, bool Unqualified,
10059                                         bool AllowCXX) {
10060   const auto *lbase = lhs->castAs<FunctionType>();
10061   const auto *rbase = rhs->castAs<FunctionType>();
10062   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10063   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10064   bool allLTypes = true;
10065   bool allRTypes = true;
10066 
10067   // Check return type
10068   QualType retType;
10069   if (OfBlockPointer) {
10070     QualType RHS = rbase->getReturnType();
10071     QualType LHS = lbase->getReturnType();
10072     bool UnqualifiedResult = Unqualified;
10073     if (!UnqualifiedResult)
10074       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10075     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10076   }
10077   else
10078     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10079                          Unqualified);
10080   if (retType.isNull())
10081     return {};
10082 
10083   if (Unqualified)
10084     retType = retType.getUnqualifiedType();
10085 
10086   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10087   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10088   if (Unqualified) {
10089     LRetType = LRetType.getUnqualifiedType();
10090     RRetType = RRetType.getUnqualifiedType();
10091   }
10092 
10093   if (getCanonicalType(retType) != LRetType)
10094     allLTypes = false;
10095   if (getCanonicalType(retType) != RRetType)
10096     allRTypes = false;
10097 
10098   // FIXME: double check this
10099   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10100   //                           rbase->getRegParmAttr() != 0 &&
10101   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10102   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10103   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10104 
10105   // Compatible functions must have compatible calling conventions
10106   if (lbaseInfo.getCC() != rbaseInfo.getCC())
10107     return {};
10108 
10109   // Regparm is part of the calling convention.
10110   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10111     return {};
10112   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10113     return {};
10114 
10115   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10116     return {};
10117   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10118     return {};
10119   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10120     return {};
10121 
10122   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
10123   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10124 
10125   if (lbaseInfo.getNoReturn() != NoReturn)
10126     allLTypes = false;
10127   if (rbaseInfo.getNoReturn() != NoReturn)
10128     allRTypes = false;
10129 
10130   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10131 
10132   if (lproto && rproto) { // two C99 style function prototypes
10133     assert((AllowCXX ||
10134             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10135            "C++ shouldn't be here");
10136     // Compatible functions must have the same number of parameters
10137     if (lproto->getNumParams() != rproto->getNumParams())
10138       return {};
10139 
10140     // Variadic and non-variadic functions aren't compatible
10141     if (lproto->isVariadic() != rproto->isVariadic())
10142       return {};
10143 
10144     if (lproto->getMethodQuals() != rproto->getMethodQuals())
10145       return {};
10146 
10147     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
10148     bool canUseLeft, canUseRight;
10149     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10150                                newParamInfos))
10151       return {};
10152 
10153     if (!canUseLeft)
10154       allLTypes = false;
10155     if (!canUseRight)
10156       allRTypes = false;
10157 
10158     // Check parameter type compatibility
10159     SmallVector<QualType, 10> types;
10160     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10161       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10162       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10163       QualType paramType = mergeFunctionParameterTypes(
10164           lParamType, rParamType, OfBlockPointer, Unqualified);
10165       if (paramType.isNull())
10166         return {};
10167 
10168       if (Unqualified)
10169         paramType = paramType.getUnqualifiedType();
10170 
10171       types.push_back(paramType);
10172       if (Unqualified) {
10173         lParamType = lParamType.getUnqualifiedType();
10174         rParamType = rParamType.getUnqualifiedType();
10175       }
10176 
10177       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10178         allLTypes = false;
10179       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10180         allRTypes = false;
10181     }
10182 
10183     if (allLTypes) return lhs;
10184     if (allRTypes) return rhs;
10185 
10186     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10187     EPI.ExtInfo = einfo;
10188     EPI.ExtParameterInfos =
10189         newParamInfos.empty() ? nullptr : newParamInfos.data();
10190     return getFunctionType(retType, types, EPI);
10191   }
10192 
10193   if (lproto) allRTypes = false;
10194   if (rproto) allLTypes = false;
10195 
10196   const FunctionProtoType *proto = lproto ? lproto : rproto;
10197   if (proto) {
10198     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10199     if (proto->isVariadic())
10200       return {};
10201     // Check that the types are compatible with the types that
10202     // would result from default argument promotions (C99 6.7.5.3p15).
10203     // The only types actually affected are promotable integer
10204     // types and floats, which would be passed as a different
10205     // type depending on whether the prototype is visible.
10206     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10207       QualType paramTy = proto->getParamType(i);
10208 
10209       // Look at the converted type of enum types, since that is the type used
10210       // to pass enum values.
10211       if (const auto *Enum = paramTy->getAs<EnumType>()) {
10212         paramTy = Enum->getDecl()->getIntegerType();
10213         if (paramTy.isNull())
10214           return {};
10215       }
10216 
10217       if (paramTy->isPromotableIntegerType() ||
10218           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10219         return {};
10220     }
10221 
10222     if (allLTypes) return lhs;
10223     if (allRTypes) return rhs;
10224 
10225     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
10226     EPI.ExtInfo = einfo;
10227     return getFunctionType(retType, proto->getParamTypes(), EPI);
10228   }
10229 
10230   if (allLTypes) return lhs;
10231   if (allRTypes) return rhs;
10232   return getFunctionNoProtoType(retType, einfo);
10233 }
10234 
10235 /// Given that we have an enum type and a non-enum type, try to merge them.
10236 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
10237                                      QualType other, bool isBlockReturnType) {
10238   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10239   // a signed integer type, or an unsigned integer type.
10240   // Compatibility is based on the underlying type, not the promotion
10241   // type.
10242   QualType underlyingType = ET->getDecl()->getIntegerType();
10243   if (underlyingType.isNull())
10244     return {};
10245   if (Context.hasSameType(underlyingType, other))
10246     return other;
10247 
10248   // In block return types, we're more permissive and accept any
10249   // integral type of the same size.
10250   if (isBlockReturnType && other->isIntegerType() &&
10251       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10252     return other;
10253 
10254   return {};
10255 }
10256 
10257 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
10258                                 bool OfBlockPointer,
10259                                 bool Unqualified, bool BlockReturnType) {
10260   // For C++ we will not reach this code with reference types (see below),
10261   // for OpenMP variant call overloading we might.
10262   //
10263   // C++ [expr]: If an expression initially has the type "reference to T", the
10264   // type is adjusted to "T" prior to any further analysis, the expression
10265   // designates the object or function denoted by the reference, and the
10266   // expression is an lvalue unless the reference is an rvalue reference and
10267   // the expression is a function call (possibly inside parentheses).
10268   auto *LHSRefTy = LHS->getAs<ReferenceType>();
10269   auto *RHSRefTy = RHS->getAs<ReferenceType>();
10270   if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10271       LHS->getTypeClass() == RHS->getTypeClass())
10272     return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10273                       OfBlockPointer, Unqualified, BlockReturnType);
10274   if (LHSRefTy || RHSRefTy)
10275     return {};
10276 
10277   if (Unqualified) {
10278     LHS = LHS.getUnqualifiedType();
10279     RHS = RHS.getUnqualifiedType();
10280   }
10281 
10282   QualType LHSCan = getCanonicalType(LHS),
10283            RHSCan = getCanonicalType(RHS);
10284 
10285   // If two types are identical, they are compatible.
10286   if (LHSCan == RHSCan)
10287     return LHS;
10288 
10289   // If the qualifiers are different, the types aren't compatible... mostly.
10290   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10291   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10292   if (LQuals != RQuals) {
10293     // If any of these qualifiers are different, we have a type
10294     // mismatch.
10295     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10296         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10297         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10298         LQuals.hasUnaligned() != RQuals.hasUnaligned())
10299       return {};
10300 
10301     // Exactly one GC qualifier difference is allowed: __strong is
10302     // okay if the other type has no GC qualifier but is an Objective
10303     // C object pointer (i.e. implicitly strong by default).  We fix
10304     // this by pretending that the unqualified type was actually
10305     // qualified __strong.
10306     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10307     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10308     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10309 
10310     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10311       return {};
10312 
10313     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10314       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
10315     }
10316     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10317       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
10318     }
10319     return {};
10320   }
10321 
10322   // Okay, qualifiers are equal.
10323 
10324   Type::TypeClass LHSClass = LHSCan->getTypeClass();
10325   Type::TypeClass RHSClass = RHSCan->getTypeClass();
10326 
10327   // We want to consider the two function types to be the same for these
10328   // comparisons, just force one to the other.
10329   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10330   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10331 
10332   // Same as above for arrays
10333   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10334     LHSClass = Type::ConstantArray;
10335   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10336     RHSClass = Type::ConstantArray;
10337 
10338   // ObjCInterfaces are just specialized ObjCObjects.
10339   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10340   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10341 
10342   // Canonicalize ExtVector -> Vector.
10343   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10344   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10345 
10346   // If the canonical type classes don't match.
10347   if (LHSClass != RHSClass) {
10348     // Note that we only have special rules for turning block enum
10349     // returns into block int returns, not vice-versa.
10350     if (const auto *ETy = LHS->getAs<EnumType>()) {
10351       return mergeEnumWithInteger(*this, ETy, RHS, false);
10352     }
10353     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10354       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10355     }
10356     // allow block pointer type to match an 'id' type.
10357     if (OfBlockPointer && !BlockReturnType) {
10358        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10359          return LHS;
10360       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10361         return RHS;
10362     }
10363     // Allow __auto_type to match anything; it merges to the type with more
10364     // information.
10365     if (const auto *AT = LHS->getAs<AutoType>()) {
10366       if (!AT->isDeduced() && AT->isGNUAutoType())
10367         return RHS;
10368     }
10369     if (const auto *AT = RHS->getAs<AutoType>()) {
10370       if (!AT->isDeduced() && AT->isGNUAutoType())
10371         return LHS;
10372     }
10373     return {};
10374   }
10375 
10376   // The canonical type classes match.
10377   switch (LHSClass) {
10378 #define TYPE(Class, Base)
10379 #define ABSTRACT_TYPE(Class, Base)
10380 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10381 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10382 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
10383 #include "clang/AST/TypeNodes.inc"
10384     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10385 
10386   case Type::Auto:
10387   case Type::DeducedTemplateSpecialization:
10388   case Type::LValueReference:
10389   case Type::RValueReference:
10390   case Type::MemberPointer:
10391     llvm_unreachable("C++ should never be in mergeTypes");
10392 
10393   case Type::ObjCInterface:
10394   case Type::IncompleteArray:
10395   case Type::VariableArray:
10396   case Type::FunctionProto:
10397   case Type::ExtVector:
10398     llvm_unreachable("Types are eliminated above");
10399 
10400   case Type::Pointer:
10401   {
10402     // Merge two pointer types, while trying to preserve typedef info
10403     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10404     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10405     if (Unqualified) {
10406       LHSPointee = LHSPointee.getUnqualifiedType();
10407       RHSPointee = RHSPointee.getUnqualifiedType();
10408     }
10409     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10410                                      Unqualified);
10411     if (ResultType.isNull())
10412       return {};
10413     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10414       return LHS;
10415     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10416       return RHS;
10417     return getPointerType(ResultType);
10418   }
10419   case Type::BlockPointer:
10420   {
10421     // Merge two block pointer types, while trying to preserve typedef info
10422     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10423     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10424     if (Unqualified) {
10425       LHSPointee = LHSPointee.getUnqualifiedType();
10426       RHSPointee = RHSPointee.getUnqualifiedType();
10427     }
10428     if (getLangOpts().OpenCL) {
10429       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10430       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10431       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10432       // 6.12.5) thus the following check is asymmetric.
10433       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10434         return {};
10435       LHSPteeQual.removeAddressSpace();
10436       RHSPteeQual.removeAddressSpace();
10437       LHSPointee =
10438           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10439       RHSPointee =
10440           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10441     }
10442     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10443                                      Unqualified);
10444     if (ResultType.isNull())
10445       return {};
10446     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10447       return LHS;
10448     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10449       return RHS;
10450     return getBlockPointerType(ResultType);
10451   }
10452   case Type::Atomic:
10453   {
10454     // Merge two pointer types, while trying to preserve typedef info
10455     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10456     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10457     if (Unqualified) {
10458       LHSValue = LHSValue.getUnqualifiedType();
10459       RHSValue = RHSValue.getUnqualifiedType();
10460     }
10461     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10462                                      Unqualified);
10463     if (ResultType.isNull())
10464       return {};
10465     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10466       return LHS;
10467     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10468       return RHS;
10469     return getAtomicType(ResultType);
10470   }
10471   case Type::ConstantArray:
10472   {
10473     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10474     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10475     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10476       return {};
10477 
10478     QualType LHSElem = getAsArrayType(LHS)->getElementType();
10479     QualType RHSElem = getAsArrayType(RHS)->getElementType();
10480     if (Unqualified) {
10481       LHSElem = LHSElem.getUnqualifiedType();
10482       RHSElem = RHSElem.getUnqualifiedType();
10483     }
10484 
10485     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10486     if (ResultType.isNull())
10487       return {};
10488 
10489     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10490     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10491 
10492     // If either side is a variable array, and both are complete, check whether
10493     // the current dimension is definite.
10494     if (LVAT || RVAT) {
10495       auto SizeFetch = [this](const VariableArrayType* VAT,
10496           const ConstantArrayType* CAT)
10497           -> std::pair<bool,llvm::APInt> {
10498         if (VAT) {
10499           Optional<llvm::APSInt> TheInt;
10500           Expr *E = VAT->getSizeExpr();
10501           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10502             return std::make_pair(true, *TheInt);
10503           return std::make_pair(false, llvm::APSInt());
10504         }
10505         if (CAT)
10506           return std::make_pair(true, CAT->getSize());
10507         return std::make_pair(false, llvm::APInt());
10508       };
10509 
10510       bool HaveLSize, HaveRSize;
10511       llvm::APInt LSize, RSize;
10512       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10513       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10514       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10515         return {}; // Definite, but unequal, array dimension
10516     }
10517 
10518     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10519       return LHS;
10520     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10521       return RHS;
10522     if (LCAT)
10523       return getConstantArrayType(ResultType, LCAT->getSize(),
10524                                   LCAT->getSizeExpr(),
10525                                   ArrayType::ArraySizeModifier(), 0);
10526     if (RCAT)
10527       return getConstantArrayType(ResultType, RCAT->getSize(),
10528                                   RCAT->getSizeExpr(),
10529                                   ArrayType::ArraySizeModifier(), 0);
10530     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10531       return LHS;
10532     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10533       return RHS;
10534     if (LVAT) {
10535       // FIXME: This isn't correct! But tricky to implement because
10536       // the array's size has to be the size of LHS, but the type
10537       // has to be different.
10538       return LHS;
10539     }
10540     if (RVAT) {
10541       // FIXME: This isn't correct! But tricky to implement because
10542       // the array's size has to be the size of RHS, but the type
10543       // has to be different.
10544       return RHS;
10545     }
10546     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10547     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10548     return getIncompleteArrayType(ResultType,
10549                                   ArrayType::ArraySizeModifier(), 0);
10550   }
10551   case Type::FunctionNoProto:
10552     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
10553   case Type::Record:
10554   case Type::Enum:
10555     return {};
10556   case Type::Builtin:
10557     // Only exactly equal builtin types are compatible, which is tested above.
10558     return {};
10559   case Type::Complex:
10560     // Distinct complex types are incompatible.
10561     return {};
10562   case Type::Vector:
10563     // FIXME: The merged type should be an ExtVector!
10564     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10565                              RHSCan->castAs<VectorType>()))
10566       return LHS;
10567     return {};
10568   case Type::ConstantMatrix:
10569     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
10570                              RHSCan->castAs<ConstantMatrixType>()))
10571       return LHS;
10572     return {};
10573   case Type::ObjCObject: {
10574     // Check if the types are assignment compatible.
10575     // FIXME: This should be type compatibility, e.g. whether
10576     // "LHS x; RHS x;" at global scope is legal.
10577     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
10578                                 RHS->castAs<ObjCObjectType>()))
10579       return LHS;
10580     return {};
10581   }
10582   case Type::ObjCObjectPointer:
10583     if (OfBlockPointer) {
10584       if (canAssignObjCInterfacesInBlockPointer(
10585               LHS->castAs<ObjCObjectPointerType>(),
10586               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10587         return LHS;
10588       return {};
10589     }
10590     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
10591                                 RHS->castAs<ObjCObjectPointerType>()))
10592       return LHS;
10593     return {};
10594   case Type::Pipe:
10595     assert(LHS != RHS &&
10596            "Equivalent pipe types should have already been handled!");
10597     return {};
10598   case Type::BitInt: {
10599     // Merge two bit-precise int types, while trying to preserve typedef info.
10600     bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10601     bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10602     unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10603     unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10604 
10605     // Like unsigned/int, shouldn't have a type if they don't match.
10606     if (LHSUnsigned != RHSUnsigned)
10607       return {};
10608 
10609     if (LHSBits != RHSBits)
10610       return {};
10611     return LHS;
10612   }
10613   }
10614 
10615   llvm_unreachable("Invalid Type::Class!");
10616 }
10617 
10618 bool ASTContext::mergeExtParameterInfo(
10619     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10620     bool &CanUseFirst, bool &CanUseSecond,
10621     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
10622   assert(NewParamInfos.empty() && "param info list not empty");
10623   CanUseFirst = CanUseSecond = true;
10624   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10625   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10626 
10627   // Fast path: if the first type doesn't have ext parameter infos,
10628   // we match if and only if the second type also doesn't have them.
10629   if (!FirstHasInfo && !SecondHasInfo)
10630     return true;
10631 
10632   bool NeedParamInfo = false;
10633   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10634                           : SecondFnType->getExtParameterInfos().size();
10635 
10636   for (size_t I = 0; I < E; ++I) {
10637     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10638     if (FirstHasInfo)
10639       FirstParam = FirstFnType->getExtParameterInfo(I);
10640     if (SecondHasInfo)
10641       SecondParam = SecondFnType->getExtParameterInfo(I);
10642 
10643     // Cannot merge unless everything except the noescape flag matches.
10644     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10645       return false;
10646 
10647     bool FirstNoEscape = FirstParam.isNoEscape();
10648     bool SecondNoEscape = SecondParam.isNoEscape();
10649     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10650     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10651     if (NewParamInfos.back().getOpaqueValue())
10652       NeedParamInfo = true;
10653     if (FirstNoEscape != IsNoEscape)
10654       CanUseFirst = false;
10655     if (SecondNoEscape != IsNoEscape)
10656       CanUseSecond = false;
10657   }
10658 
10659   if (!NeedParamInfo)
10660     NewParamInfos.clear();
10661 
10662   return true;
10663 }
10664 
10665 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10666   ObjCLayouts[CD] = nullptr;
10667 }
10668 
10669 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10670 /// 'RHS' attributes and returns the merged version; including for function
10671 /// return types.
10672 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10673   QualType LHSCan = getCanonicalType(LHS),
10674   RHSCan = getCanonicalType(RHS);
10675   // If two types are identical, they are compatible.
10676   if (LHSCan == RHSCan)
10677     return LHS;
10678   if (RHSCan->isFunctionType()) {
10679     if (!LHSCan->isFunctionType())
10680       return {};
10681     QualType OldReturnType =
10682         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10683     QualType NewReturnType =
10684         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10685     QualType ResReturnType =
10686       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10687     if (ResReturnType.isNull())
10688       return {};
10689     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10690       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10691       // In either case, use OldReturnType to build the new function type.
10692       const auto *F = LHS->castAs<FunctionType>();
10693       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10694         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10695         EPI.ExtInfo = getFunctionExtInfo(LHS);
10696         QualType ResultType =
10697             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10698         return ResultType;
10699       }
10700     }
10701     return {};
10702   }
10703 
10704   // If the qualifiers are different, the types can still be merged.
10705   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10706   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10707   if (LQuals != RQuals) {
10708     // If any of these qualifiers are different, we have a type mismatch.
10709     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10710         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10711       return {};
10712 
10713     // Exactly one GC qualifier difference is allowed: __strong is
10714     // okay if the other type has no GC qualifier but is an Objective
10715     // C object pointer (i.e. implicitly strong by default).  We fix
10716     // this by pretending that the unqualified type was actually
10717     // qualified __strong.
10718     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10719     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10720     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10721 
10722     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10723       return {};
10724 
10725     if (GC_L == Qualifiers::Strong)
10726       return LHS;
10727     if (GC_R == Qualifiers::Strong)
10728       return RHS;
10729     return {};
10730   }
10731 
10732   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10733     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10734     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10735     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10736     if (ResQT == LHSBaseQT)
10737       return LHS;
10738     if (ResQT == RHSBaseQT)
10739       return RHS;
10740   }
10741   return {};
10742 }
10743 
10744 //===----------------------------------------------------------------------===//
10745 //                         Integer Predicates
10746 //===----------------------------------------------------------------------===//
10747 
10748 unsigned ASTContext::getIntWidth(QualType T) const {
10749   if (const auto *ET = T->getAs<EnumType>())
10750     T = ET->getDecl()->getIntegerType();
10751   if (T->isBooleanType())
10752     return 1;
10753   if (const auto *EIT = T->getAs<BitIntType>())
10754     return EIT->getNumBits();
10755   // For builtin types, just use the standard type sizing method
10756   return (unsigned)getTypeSize(T);
10757 }
10758 
10759 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10760   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10761          "Unexpected type");
10762 
10763   // Turn <4 x signed int> -> <4 x unsigned int>
10764   if (const auto *VTy = T->getAs<VectorType>())
10765     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10766                          VTy->getNumElements(), VTy->getVectorKind());
10767 
10768   // For _BitInt, return an unsigned _BitInt with same width.
10769   if (const auto *EITy = T->getAs<BitIntType>())
10770     return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
10771 
10772   // For enums, get the underlying integer type of the enum, and let the general
10773   // integer type signchanging code handle it.
10774   if (const auto *ETy = T->getAs<EnumType>())
10775     T = ETy->getDecl()->getIntegerType();
10776 
10777   switch (T->castAs<BuiltinType>()->getKind()) {
10778   case BuiltinType::Char_S:
10779   case BuiltinType::SChar:
10780     return UnsignedCharTy;
10781   case BuiltinType::Short:
10782     return UnsignedShortTy;
10783   case BuiltinType::Int:
10784     return UnsignedIntTy;
10785   case BuiltinType::Long:
10786     return UnsignedLongTy;
10787   case BuiltinType::LongLong:
10788     return UnsignedLongLongTy;
10789   case BuiltinType::Int128:
10790     return UnsignedInt128Ty;
10791   // wchar_t is special. It is either signed or not, but when it's signed,
10792   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10793   // version of it's underlying type instead.
10794   case BuiltinType::WChar_S:
10795     return getUnsignedWCharType();
10796 
10797   case BuiltinType::ShortAccum:
10798     return UnsignedShortAccumTy;
10799   case BuiltinType::Accum:
10800     return UnsignedAccumTy;
10801   case BuiltinType::LongAccum:
10802     return UnsignedLongAccumTy;
10803   case BuiltinType::SatShortAccum:
10804     return SatUnsignedShortAccumTy;
10805   case BuiltinType::SatAccum:
10806     return SatUnsignedAccumTy;
10807   case BuiltinType::SatLongAccum:
10808     return SatUnsignedLongAccumTy;
10809   case BuiltinType::ShortFract:
10810     return UnsignedShortFractTy;
10811   case BuiltinType::Fract:
10812     return UnsignedFractTy;
10813   case BuiltinType::LongFract:
10814     return UnsignedLongFractTy;
10815   case BuiltinType::SatShortFract:
10816     return SatUnsignedShortFractTy;
10817   case BuiltinType::SatFract:
10818     return SatUnsignedFractTy;
10819   case BuiltinType::SatLongFract:
10820     return SatUnsignedLongFractTy;
10821   default:
10822     llvm_unreachable("Unexpected signed integer or fixed point type");
10823   }
10824 }
10825 
10826 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
10827   assert((T->hasUnsignedIntegerRepresentation() ||
10828           T->isUnsignedFixedPointType()) &&
10829          "Unexpected type");
10830 
10831   // Turn <4 x unsigned int> -> <4 x signed int>
10832   if (const auto *VTy = T->getAs<VectorType>())
10833     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
10834                          VTy->getNumElements(), VTy->getVectorKind());
10835 
10836   // For _BitInt, return a signed _BitInt with same width.
10837   if (const auto *EITy = T->getAs<BitIntType>())
10838     return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
10839 
10840   // For enums, get the underlying integer type of the enum, and let the general
10841   // integer type signchanging code handle it.
10842   if (const auto *ETy = T->getAs<EnumType>())
10843     T = ETy->getDecl()->getIntegerType();
10844 
10845   switch (T->castAs<BuiltinType>()->getKind()) {
10846   case BuiltinType::Char_U:
10847   case BuiltinType::UChar:
10848     return SignedCharTy;
10849   case BuiltinType::UShort:
10850     return ShortTy;
10851   case BuiltinType::UInt:
10852     return IntTy;
10853   case BuiltinType::ULong:
10854     return LongTy;
10855   case BuiltinType::ULongLong:
10856     return LongLongTy;
10857   case BuiltinType::UInt128:
10858     return Int128Ty;
10859   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
10860   // there's no matching "signed wchar_t". Therefore we return the signed
10861   // version of it's underlying type instead.
10862   case BuiltinType::WChar_U:
10863     return getSignedWCharType();
10864 
10865   case BuiltinType::UShortAccum:
10866     return ShortAccumTy;
10867   case BuiltinType::UAccum:
10868     return AccumTy;
10869   case BuiltinType::ULongAccum:
10870     return LongAccumTy;
10871   case BuiltinType::SatUShortAccum:
10872     return SatShortAccumTy;
10873   case BuiltinType::SatUAccum:
10874     return SatAccumTy;
10875   case BuiltinType::SatULongAccum:
10876     return SatLongAccumTy;
10877   case BuiltinType::UShortFract:
10878     return ShortFractTy;
10879   case BuiltinType::UFract:
10880     return FractTy;
10881   case BuiltinType::ULongFract:
10882     return LongFractTy;
10883   case BuiltinType::SatUShortFract:
10884     return SatShortFractTy;
10885   case BuiltinType::SatUFract:
10886     return SatFractTy;
10887   case BuiltinType::SatULongFract:
10888     return SatLongFractTy;
10889   default:
10890     llvm_unreachable("Unexpected unsigned integer or fixed point type");
10891   }
10892 }
10893 
10894 ASTMutationListener::~ASTMutationListener() = default;
10895 
10896 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10897                                             QualType ReturnType) {}
10898 
10899 //===----------------------------------------------------------------------===//
10900 //                          Builtin Type Computation
10901 //===----------------------------------------------------------------------===//
10902 
10903 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10904 /// pointer over the consumed characters.  This returns the resultant type.  If
10905 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10906 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10907 /// a vector of "i*".
10908 ///
10909 /// RequiresICE is filled in on return to indicate whether the value is required
10910 /// to be an Integer Constant Expression.
10911 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10912                                   ASTContext::GetBuiltinTypeError &Error,
10913                                   bool &RequiresICE,
10914                                   bool AllowTypeModifiers) {
10915   // Modifiers.
10916   int HowLong = 0;
10917   bool Signed = false, Unsigned = false;
10918   RequiresICE = false;
10919 
10920   // Read the prefixed modifiers first.
10921   bool Done = false;
10922   #ifndef NDEBUG
10923   bool IsSpecial = false;
10924   #endif
10925   while (!Done) {
10926     switch (*Str++) {
10927     default: Done = true; --Str; break;
10928     case 'I':
10929       RequiresICE = true;
10930       break;
10931     case 'S':
10932       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10933       assert(!Signed && "Can't use 'S' modifier multiple times!");
10934       Signed = true;
10935       break;
10936     case 'U':
10937       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10938       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10939       Unsigned = true;
10940       break;
10941     case 'L':
10942       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10943       assert(HowLong <= 2 && "Can't have LLLL modifier");
10944       ++HowLong;
10945       break;
10946     case 'N':
10947       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10948       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10949       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10950       #ifndef NDEBUG
10951       IsSpecial = true;
10952       #endif
10953       if (Context.getTargetInfo().getLongWidth() == 32)
10954         ++HowLong;
10955       break;
10956     case 'W':
10957       // This modifier represents int64 type.
10958       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10959       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10960       #ifndef NDEBUG
10961       IsSpecial = true;
10962       #endif
10963       switch (Context.getTargetInfo().getInt64Type()) {
10964       default:
10965         llvm_unreachable("Unexpected integer type");
10966       case TargetInfo::SignedLong:
10967         HowLong = 1;
10968         break;
10969       case TargetInfo::SignedLongLong:
10970         HowLong = 2;
10971         break;
10972       }
10973       break;
10974     case 'Z':
10975       // This modifier represents int32 type.
10976       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10977       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10978       #ifndef NDEBUG
10979       IsSpecial = true;
10980       #endif
10981       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10982       default:
10983         llvm_unreachable("Unexpected integer type");
10984       case TargetInfo::SignedInt:
10985         HowLong = 0;
10986         break;
10987       case TargetInfo::SignedLong:
10988         HowLong = 1;
10989         break;
10990       case TargetInfo::SignedLongLong:
10991         HowLong = 2;
10992         break;
10993       }
10994       break;
10995     case 'O':
10996       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10997       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10998       #ifndef NDEBUG
10999       IsSpecial = true;
11000       #endif
11001       if (Context.getLangOpts().OpenCL)
11002         HowLong = 1;
11003       else
11004         HowLong = 2;
11005       break;
11006     }
11007   }
11008 
11009   QualType Type;
11010 
11011   // Read the base type.
11012   switch (*Str++) {
11013   default: llvm_unreachable("Unknown builtin type letter!");
11014   case 'x':
11015     assert(HowLong == 0 && !Signed && !Unsigned &&
11016            "Bad modifiers used with 'x'!");
11017     Type = Context.Float16Ty;
11018     break;
11019   case 'y':
11020     assert(HowLong == 0 && !Signed && !Unsigned &&
11021            "Bad modifiers used with 'y'!");
11022     Type = Context.BFloat16Ty;
11023     break;
11024   case 'v':
11025     assert(HowLong == 0 && !Signed && !Unsigned &&
11026            "Bad modifiers used with 'v'!");
11027     Type = Context.VoidTy;
11028     break;
11029   case 'h':
11030     assert(HowLong == 0 && !Signed && !Unsigned &&
11031            "Bad modifiers used with 'h'!");
11032     Type = Context.HalfTy;
11033     break;
11034   case 'f':
11035     assert(HowLong == 0 && !Signed && !Unsigned &&
11036            "Bad modifiers used with 'f'!");
11037     Type = Context.FloatTy;
11038     break;
11039   case 'd':
11040     assert(HowLong < 3 && !Signed && !Unsigned &&
11041            "Bad modifiers used with 'd'!");
11042     if (HowLong == 1)
11043       Type = Context.LongDoubleTy;
11044     else if (HowLong == 2)
11045       Type = Context.Float128Ty;
11046     else
11047       Type = Context.DoubleTy;
11048     break;
11049   case 's':
11050     assert(HowLong == 0 && "Bad modifiers used with 's'!");
11051     if (Unsigned)
11052       Type = Context.UnsignedShortTy;
11053     else
11054       Type = Context.ShortTy;
11055     break;
11056   case 'i':
11057     if (HowLong == 3)
11058       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11059     else if (HowLong == 2)
11060       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11061     else if (HowLong == 1)
11062       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11063     else
11064       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11065     break;
11066   case 'c':
11067     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11068     if (Signed)
11069       Type = Context.SignedCharTy;
11070     else if (Unsigned)
11071       Type = Context.UnsignedCharTy;
11072     else
11073       Type = Context.CharTy;
11074     break;
11075   case 'b': // boolean
11076     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11077     Type = Context.BoolTy;
11078     break;
11079   case 'z':  // size_t.
11080     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11081     Type = Context.getSizeType();
11082     break;
11083   case 'w':  // wchar_t.
11084     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11085     Type = Context.getWideCharType();
11086     break;
11087   case 'F':
11088     Type = Context.getCFConstantStringType();
11089     break;
11090   case 'G':
11091     Type = Context.getObjCIdType();
11092     break;
11093   case 'H':
11094     Type = Context.getObjCSelType();
11095     break;
11096   case 'M':
11097     Type = Context.getObjCSuperType();
11098     break;
11099   case 'a':
11100     Type = Context.getBuiltinVaListType();
11101     assert(!Type.isNull() && "builtin va list type not initialized!");
11102     break;
11103   case 'A':
11104     // This is a "reference" to a va_list; however, what exactly
11105     // this means depends on how va_list is defined. There are two
11106     // different kinds of va_list: ones passed by value, and ones
11107     // passed by reference.  An example of a by-value va_list is
11108     // x86, where va_list is a char*. An example of by-ref va_list
11109     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11110     // we want this argument to be a char*&; for x86-64, we want
11111     // it to be a __va_list_tag*.
11112     Type = Context.getBuiltinVaListType();
11113     assert(!Type.isNull() && "builtin va list type not initialized!");
11114     if (Type->isArrayType())
11115       Type = Context.getArrayDecayedType(Type);
11116     else
11117       Type = Context.getLValueReferenceType(Type);
11118     break;
11119   case 'q': {
11120     char *End;
11121     unsigned NumElements = strtoul(Str, &End, 10);
11122     assert(End != Str && "Missing vector size");
11123     Str = End;
11124 
11125     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11126                                              RequiresICE, false);
11127     assert(!RequiresICE && "Can't require vector ICE");
11128 
11129     Type = Context.getScalableVectorType(ElementType, NumElements);
11130     break;
11131   }
11132   case 'V': {
11133     char *End;
11134     unsigned NumElements = strtoul(Str, &End, 10);
11135     assert(End != Str && "Missing vector size");
11136     Str = End;
11137 
11138     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11139                                              RequiresICE, false);
11140     assert(!RequiresICE && "Can't require vector ICE");
11141 
11142     // TODO: No way to make AltiVec vectors in builtins yet.
11143     Type = Context.getVectorType(ElementType, NumElements,
11144                                  VectorType::GenericVector);
11145     break;
11146   }
11147   case 'E': {
11148     char *End;
11149 
11150     unsigned NumElements = strtoul(Str, &End, 10);
11151     assert(End != Str && "Missing vector size");
11152 
11153     Str = End;
11154 
11155     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11156                                              false);
11157     Type = Context.getExtVectorType(ElementType, NumElements);
11158     break;
11159   }
11160   case 'X': {
11161     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11162                                              false);
11163     assert(!RequiresICE && "Can't require complex ICE");
11164     Type = Context.getComplexType(ElementType);
11165     break;
11166   }
11167   case 'Y':
11168     Type = Context.getPointerDiffType();
11169     break;
11170   case 'P':
11171     Type = Context.getFILEType();
11172     if (Type.isNull()) {
11173       Error = ASTContext::GE_Missing_stdio;
11174       return {};
11175     }
11176     break;
11177   case 'J':
11178     if (Signed)
11179       Type = Context.getsigjmp_bufType();
11180     else
11181       Type = Context.getjmp_bufType();
11182 
11183     if (Type.isNull()) {
11184       Error = ASTContext::GE_Missing_setjmp;
11185       return {};
11186     }
11187     break;
11188   case 'K':
11189     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11190     Type = Context.getucontext_tType();
11191 
11192     if (Type.isNull()) {
11193       Error = ASTContext::GE_Missing_ucontext;
11194       return {};
11195     }
11196     break;
11197   case 'p':
11198     Type = Context.getProcessIDType();
11199     break;
11200   }
11201 
11202   // If there are modifiers and if we're allowed to parse them, go for it.
11203   Done = !AllowTypeModifiers;
11204   while (!Done) {
11205     switch (char c = *Str++) {
11206     default: Done = true; --Str; break;
11207     case '*':
11208     case '&': {
11209       // Both pointers and references can have their pointee types
11210       // qualified with an address space.
11211       char *End;
11212       unsigned AddrSpace = strtoul(Str, &End, 10);
11213       if (End != Str) {
11214         // Note AddrSpace == 0 is not the same as an unspecified address space.
11215         Type = Context.getAddrSpaceQualType(
11216           Type,
11217           Context.getLangASForBuiltinAddressSpace(AddrSpace));
11218         Str = End;
11219       }
11220       if (c == '*')
11221         Type = Context.getPointerType(Type);
11222       else
11223         Type = Context.getLValueReferenceType(Type);
11224       break;
11225     }
11226     // FIXME: There's no way to have a built-in with an rvalue ref arg.
11227     case 'C':
11228       Type = Type.withConst();
11229       break;
11230     case 'D':
11231       Type = Context.getVolatileType(Type);
11232       break;
11233     case 'R':
11234       Type = Type.withRestrict();
11235       break;
11236     }
11237   }
11238 
11239   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11240          "Integer constant 'I' type must be an integer");
11241 
11242   return Type;
11243 }
11244 
11245 // On some targets such as PowerPC, some of the builtins are defined with custom
11246 // type descriptors for target-dependent types. These descriptors are decoded in
11247 // other functions, but it may be useful to be able to fall back to default
11248 // descriptor decoding to define builtins mixing target-dependent and target-
11249 // independent types. This function allows decoding one type descriptor with
11250 // default decoding.
11251 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11252                                    GetBuiltinTypeError &Error, bool &RequireICE,
11253                                    bool AllowTypeModifiers) const {
11254   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11255 }
11256 
11257 /// GetBuiltinType - Return the type for the specified builtin.
11258 QualType ASTContext::GetBuiltinType(unsigned Id,
11259                                     GetBuiltinTypeError &Error,
11260                                     unsigned *IntegerConstantArgs) const {
11261   const char *TypeStr = BuiltinInfo.getTypeString(Id);
11262   if (TypeStr[0] == '\0') {
11263     Error = GE_Missing_type;
11264     return {};
11265   }
11266 
11267   SmallVector<QualType, 8> ArgTypes;
11268 
11269   bool RequiresICE = false;
11270   Error = GE_None;
11271   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11272                                        RequiresICE, true);
11273   if (Error != GE_None)
11274     return {};
11275 
11276   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11277 
11278   while (TypeStr[0] && TypeStr[0] != '.') {
11279     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11280     if (Error != GE_None)
11281       return {};
11282 
11283     // If this argument is required to be an IntegerConstantExpression and the
11284     // caller cares, fill in the bitmask we return.
11285     if (RequiresICE && IntegerConstantArgs)
11286       *IntegerConstantArgs |= 1 << ArgTypes.size();
11287 
11288     // Do array -> pointer decay.  The builtin should use the decayed type.
11289     if (Ty->isArrayType())
11290       Ty = getArrayDecayedType(Ty);
11291 
11292     ArgTypes.push_back(Ty);
11293   }
11294 
11295   if (Id == Builtin::BI__GetExceptionInfo)
11296     return {};
11297 
11298   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11299          "'.' should only occur at end of builtin type list!");
11300 
11301   bool Variadic = (TypeStr[0] == '.');
11302 
11303   FunctionType::ExtInfo EI(getDefaultCallingConvention(
11304       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11305   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11306 
11307 
11308   // We really shouldn't be making a no-proto type here.
11309   if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
11310     return getFunctionNoProtoType(ResType, EI);
11311 
11312   FunctionProtoType::ExtProtoInfo EPI;
11313   EPI.ExtInfo = EI;
11314   EPI.Variadic = Variadic;
11315   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
11316     EPI.ExceptionSpec.Type =
11317         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
11318 
11319   return getFunctionType(ResType, ArgTypes, EPI);
11320 }
11321 
11322 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
11323                                              const FunctionDecl *FD) {
11324   if (!FD->isExternallyVisible())
11325     return GVA_Internal;
11326 
11327   // Non-user-provided functions get emitted as weak definitions with every
11328   // use, no matter whether they've been explicitly instantiated etc.
11329   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
11330     if (!MD->isUserProvided())
11331       return GVA_DiscardableODR;
11332 
11333   GVALinkage External;
11334   switch (FD->getTemplateSpecializationKind()) {
11335   case TSK_Undeclared:
11336   case TSK_ExplicitSpecialization:
11337     External = GVA_StrongExternal;
11338     break;
11339 
11340   case TSK_ExplicitInstantiationDefinition:
11341     return GVA_StrongODR;
11342 
11343   // C++11 [temp.explicit]p10:
11344   //   [ Note: The intent is that an inline function that is the subject of
11345   //   an explicit instantiation declaration will still be implicitly
11346   //   instantiated when used so that the body can be considered for
11347   //   inlining, but that no out-of-line copy of the inline function would be
11348   //   generated in the translation unit. -- end note ]
11349   case TSK_ExplicitInstantiationDeclaration:
11350     return GVA_AvailableExternally;
11351 
11352   case TSK_ImplicitInstantiation:
11353     External = GVA_DiscardableODR;
11354     break;
11355   }
11356 
11357   if (!FD->isInlined())
11358     return External;
11359 
11360   if ((!Context.getLangOpts().CPlusPlus &&
11361        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11362        !FD->hasAttr<DLLExportAttr>()) ||
11363       FD->hasAttr<GNUInlineAttr>()) {
11364     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11365 
11366     // GNU or C99 inline semantics. Determine whether this symbol should be
11367     // externally visible.
11368     if (FD->isInlineDefinitionExternallyVisible())
11369       return External;
11370 
11371     // C99 inline semantics, where the symbol is not externally visible.
11372     return GVA_AvailableExternally;
11373   }
11374 
11375   // Functions specified with extern and inline in -fms-compatibility mode
11376   // forcibly get emitted.  While the body of the function cannot be later
11377   // replaced, the function definition cannot be discarded.
11378   if (FD->isMSExternInline())
11379     return GVA_StrongODR;
11380 
11381   return GVA_DiscardableODR;
11382 }
11383 
11384 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
11385                                                 const Decl *D, GVALinkage L) {
11386   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11387   // dllexport/dllimport on inline functions.
11388   if (D->hasAttr<DLLImportAttr>()) {
11389     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11390       return GVA_AvailableExternally;
11391   } else if (D->hasAttr<DLLExportAttr>()) {
11392     if (L == GVA_DiscardableODR)
11393       return GVA_StrongODR;
11394   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11395     // Device-side functions with __global__ attribute must always be
11396     // visible externally so they can be launched from host.
11397     if (D->hasAttr<CUDAGlobalAttr>() &&
11398         (L == GVA_DiscardableODR || L == GVA_Internal))
11399       return GVA_StrongODR;
11400     // Single source offloading languages like CUDA/HIP need to be able to
11401     // access static device variables from host code of the same compilation
11402     // unit. This is done by externalizing the static variable with a shared
11403     // name between the host and device compilation which is the same for the
11404     // same compilation unit whereas different among different compilation
11405     // units.
11406     if (Context.shouldExternalize(D))
11407       return GVA_StrongExternal;
11408   }
11409   return L;
11410 }
11411 
11412 /// Adjust the GVALinkage for a declaration based on what an external AST source
11413 /// knows about whether there can be other definitions of this declaration.
11414 static GVALinkage
11415 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
11416                                           GVALinkage L) {
11417   ExternalASTSource *Source = Ctx.getExternalSource();
11418   if (!Source)
11419     return L;
11420 
11421   switch (Source->hasExternalDefinitions(D)) {
11422   case ExternalASTSource::EK_Never:
11423     // Other translation units rely on us to provide the definition.
11424     if (L == GVA_DiscardableODR)
11425       return GVA_StrongODR;
11426     break;
11427 
11428   case ExternalASTSource::EK_Always:
11429     return GVA_AvailableExternally;
11430 
11431   case ExternalASTSource::EK_ReplyHazy:
11432     break;
11433   }
11434   return L;
11435 }
11436 
11437 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
11438   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
11439            adjustGVALinkageForAttributes(*this, FD,
11440              basicGVALinkageForFunction(*this, FD)));
11441 }
11442 
11443 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
11444                                              const VarDecl *VD) {
11445   if (!VD->isExternallyVisible())
11446     return GVA_Internal;
11447 
11448   if (VD->isStaticLocal()) {
11449     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11450     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11451       LexicalContext = LexicalContext->getLexicalParent();
11452 
11453     // ObjC Blocks can create local variables that don't have a FunctionDecl
11454     // LexicalContext.
11455     if (!LexicalContext)
11456       return GVA_DiscardableODR;
11457 
11458     // Otherwise, let the static local variable inherit its linkage from the
11459     // nearest enclosing function.
11460     auto StaticLocalLinkage =
11461         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11462 
11463     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11464     // be emitted in any object with references to the symbol for the object it
11465     // contains, whether inline or out-of-line."
11466     // Similar behavior is observed with MSVC. An alternative ABI could use
11467     // StrongODR/AvailableExternally to match the function, but none are
11468     // known/supported currently.
11469     if (StaticLocalLinkage == GVA_StrongODR ||
11470         StaticLocalLinkage == GVA_AvailableExternally)
11471       return GVA_DiscardableODR;
11472     return StaticLocalLinkage;
11473   }
11474 
11475   // MSVC treats in-class initialized static data members as definitions.
11476   // By giving them non-strong linkage, out-of-line definitions won't
11477   // cause link errors.
11478   if (Context.isMSStaticDataMemberInlineDefinition(VD))
11479     return GVA_DiscardableODR;
11480 
11481   // Most non-template variables have strong linkage; inline variables are
11482   // linkonce_odr or (occasionally, for compatibility) weak_odr.
11483   GVALinkage StrongLinkage;
11484   switch (Context.getInlineVariableDefinitionKind(VD)) {
11485   case ASTContext::InlineVariableDefinitionKind::None:
11486     StrongLinkage = GVA_StrongExternal;
11487     break;
11488   case ASTContext::InlineVariableDefinitionKind::Weak:
11489   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
11490     StrongLinkage = GVA_DiscardableODR;
11491     break;
11492   case ASTContext::InlineVariableDefinitionKind::Strong:
11493     StrongLinkage = GVA_StrongODR;
11494     break;
11495   }
11496 
11497   switch (VD->getTemplateSpecializationKind()) {
11498   case TSK_Undeclared:
11499     return StrongLinkage;
11500 
11501   case TSK_ExplicitSpecialization:
11502     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11503                    VD->isStaticDataMember()
11504                ? GVA_StrongODR
11505                : StrongLinkage;
11506 
11507   case TSK_ExplicitInstantiationDefinition:
11508     return GVA_StrongODR;
11509 
11510   case TSK_ExplicitInstantiationDeclaration:
11511     return GVA_AvailableExternally;
11512 
11513   case TSK_ImplicitInstantiation:
11514     return GVA_DiscardableODR;
11515   }
11516 
11517   llvm_unreachable("Invalid Linkage!");
11518 }
11519 
11520 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
11521   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
11522            adjustGVALinkageForAttributes(*this, VD,
11523              basicGVALinkageForVariable(*this, VD)));
11524 }
11525 
11526 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
11527   if (const auto *VD = dyn_cast<VarDecl>(D)) {
11528     if (!VD->isFileVarDecl())
11529       return false;
11530     // Global named register variables (GNU extension) are never emitted.
11531     if (VD->getStorageClass() == SC_Register)
11532       return false;
11533     if (VD->getDescribedVarTemplate() ||
11534         isa<VarTemplatePartialSpecializationDecl>(VD))
11535       return false;
11536   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11537     // We never need to emit an uninstantiated function template.
11538     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11539       return false;
11540   } else if (isa<PragmaCommentDecl>(D))
11541     return true;
11542   else if (isa<PragmaDetectMismatchDecl>(D))
11543     return true;
11544   else if (isa<OMPRequiresDecl>(D))
11545     return true;
11546   else if (isa<OMPThreadPrivateDecl>(D))
11547     return !D->getDeclContext()->isDependentContext();
11548   else if (isa<OMPAllocateDecl>(D))
11549     return !D->getDeclContext()->isDependentContext();
11550   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11551     return !D->getDeclContext()->isDependentContext();
11552   else if (isa<ImportDecl>(D))
11553     return true;
11554   else
11555     return false;
11556 
11557   // If this is a member of a class template, we do not need to emit it.
11558   if (D->getDeclContext()->isDependentContext())
11559     return false;
11560 
11561   // Weak references don't produce any output by themselves.
11562   if (D->hasAttr<WeakRefAttr>())
11563     return false;
11564 
11565   // Aliases and used decls are required.
11566   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11567     return true;
11568 
11569   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11570     // Forward declarations aren't required.
11571     if (!FD->doesThisDeclarationHaveABody())
11572       return FD->doesDeclarationForceExternallyVisibleDefinition();
11573 
11574     // Constructors and destructors are required.
11575     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11576       return true;
11577 
11578     // The key function for a class is required.  This rule only comes
11579     // into play when inline functions can be key functions, though.
11580     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11581       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11582         const CXXRecordDecl *RD = MD->getParent();
11583         if (MD->isOutOfLine() && RD->isDynamicClass()) {
11584           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11585           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11586             return true;
11587         }
11588       }
11589     }
11590 
11591     GVALinkage Linkage = GetGVALinkageForFunction(FD);
11592 
11593     // static, static inline, always_inline, and extern inline functions can
11594     // always be deferred.  Normal inline functions can be deferred in C99/C++.
11595     // Implicit template instantiations can also be deferred in C++.
11596     return !isDiscardableGVALinkage(Linkage);
11597   }
11598 
11599   const auto *VD = cast<VarDecl>(D);
11600   assert(VD->isFileVarDecl() && "Expected file scoped var");
11601 
11602   // If the decl is marked as `declare target to`, it should be emitted for the
11603   // host and for the device.
11604   if (LangOpts.OpenMP &&
11605       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11606     return true;
11607 
11608   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11609       !isMSStaticDataMemberInlineDefinition(VD))
11610     return false;
11611 
11612   // Variables that can be needed in other TUs are required.
11613   auto Linkage = GetGVALinkageForVariable(VD);
11614   if (!isDiscardableGVALinkage(Linkage))
11615     return true;
11616 
11617   // We never need to emit a variable that is available in another TU.
11618   if (Linkage == GVA_AvailableExternally)
11619     return false;
11620 
11621   // Variables that have destruction with side-effects are required.
11622   if (VD->needsDestruction(*this))
11623     return true;
11624 
11625   // Variables that have initialization with side-effects are required.
11626   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11627       // We can get a value-dependent initializer during error recovery.
11628       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11629     return true;
11630 
11631   // Likewise, variables with tuple-like bindings are required if their
11632   // bindings have side-effects.
11633   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11634     for (const auto *BD : DD->bindings())
11635       if (const auto *BindingVD = BD->getHoldingVar())
11636         if (DeclMustBeEmitted(BindingVD))
11637           return true;
11638 
11639   return false;
11640 }
11641 
11642 void ASTContext::forEachMultiversionedFunctionVersion(
11643     const FunctionDecl *FD,
11644     llvm::function_ref<void(FunctionDecl *)> Pred) const {
11645   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11646   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11647   FD = FD->getMostRecentDecl();
11648   // FIXME: The order of traversal here matters and depends on the order of
11649   // lookup results, which happens to be (mostly) oldest-to-newest, but we
11650   // shouldn't rely on that.
11651   for (auto *CurDecl :
11652        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
11653     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
11654     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
11655         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
11656       SeenDecls.insert(CurFD);
11657       Pred(CurFD);
11658     }
11659   }
11660 }
11661 
11662 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
11663                                                     bool IsCXXMethod,
11664                                                     bool IsBuiltin) const {
11665   // Pass through to the C++ ABI object
11666   if (IsCXXMethod)
11667     return ABI->getDefaultMethodCallConv(IsVariadic);
11668 
11669   // Builtins ignore user-specified default calling convention and remain the
11670   // Target's default calling convention.
11671   if (!IsBuiltin) {
11672     switch (LangOpts.getDefaultCallingConv()) {
11673     case LangOptions::DCC_None:
11674       break;
11675     case LangOptions::DCC_CDecl:
11676       return CC_C;
11677     case LangOptions::DCC_FastCall:
11678       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11679         return CC_X86FastCall;
11680       break;
11681     case LangOptions::DCC_StdCall:
11682       if (!IsVariadic)
11683         return CC_X86StdCall;
11684       break;
11685     case LangOptions::DCC_VectorCall:
11686       // __vectorcall cannot be applied to variadic functions.
11687       if (!IsVariadic)
11688         return CC_X86VectorCall;
11689       break;
11690     case LangOptions::DCC_RegCall:
11691       // __regcall cannot be applied to variadic functions.
11692       if (!IsVariadic)
11693         return CC_X86RegCall;
11694       break;
11695     }
11696   }
11697   return Target->getDefaultCallingConv();
11698 }
11699 
11700 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11701   // Pass through to the C++ ABI object
11702   return ABI->isNearlyEmpty(RD);
11703 }
11704 
11705 VTableContextBase *ASTContext::getVTableContext() {
11706   if (!VTContext.get()) {
11707     auto ABI = Target->getCXXABI();
11708     if (ABI.isMicrosoft())
11709       VTContext.reset(new MicrosoftVTableContext(*this));
11710     else {
11711       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11712                                  ? ItaniumVTableContext::Relative
11713                                  : ItaniumVTableContext::Pointer;
11714       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
11715     }
11716   }
11717   return VTContext.get();
11718 }
11719 
11720 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
11721   if (!T)
11722     T = Target;
11723   switch (T->getCXXABI().getKind()) {
11724   case TargetCXXABI::AppleARM64:
11725   case TargetCXXABI::Fuchsia:
11726   case TargetCXXABI::GenericAArch64:
11727   case TargetCXXABI::GenericItanium:
11728   case TargetCXXABI::GenericARM:
11729   case TargetCXXABI::GenericMIPS:
11730   case TargetCXXABI::iOS:
11731   case TargetCXXABI::WebAssembly:
11732   case TargetCXXABI::WatchOS:
11733   case TargetCXXABI::XL:
11734     return ItaniumMangleContext::create(*this, getDiagnostics());
11735   case TargetCXXABI::Microsoft:
11736     return MicrosoftMangleContext::create(*this, getDiagnostics());
11737   }
11738   llvm_unreachable("Unsupported ABI");
11739 }
11740 
11741 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
11742   assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
11743          "Device mangle context does not support Microsoft mangling.");
11744   switch (T.getCXXABI().getKind()) {
11745   case TargetCXXABI::AppleARM64:
11746   case TargetCXXABI::Fuchsia:
11747   case TargetCXXABI::GenericAArch64:
11748   case TargetCXXABI::GenericItanium:
11749   case TargetCXXABI::GenericARM:
11750   case TargetCXXABI::GenericMIPS:
11751   case TargetCXXABI::iOS:
11752   case TargetCXXABI::WebAssembly:
11753   case TargetCXXABI::WatchOS:
11754   case TargetCXXABI::XL:
11755     return ItaniumMangleContext::create(
11756         *this, getDiagnostics(),
11757         [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> {
11758           if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
11759             return RD->getDeviceLambdaManglingNumber();
11760           return llvm::None;
11761         },
11762         /*IsAux=*/true);
11763   case TargetCXXABI::Microsoft:
11764     return MicrosoftMangleContext::create(*this, getDiagnostics(),
11765                                           /*IsAux=*/true);
11766   }
11767   llvm_unreachable("Unsupported ABI");
11768 }
11769 
11770 CXXABI::~CXXABI() = default;
11771 
11772 size_t ASTContext::getSideTableAllocatedMemory() const {
11773   return ASTRecordLayouts.getMemorySize() +
11774          llvm::capacity_in_bytes(ObjCLayouts) +
11775          llvm::capacity_in_bytes(KeyFunctions) +
11776          llvm::capacity_in_bytes(ObjCImpls) +
11777          llvm::capacity_in_bytes(BlockVarCopyInits) +
11778          llvm::capacity_in_bytes(DeclAttrs) +
11779          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11780          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11781          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11782          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11783          llvm::capacity_in_bytes(OverriddenMethods) +
11784          llvm::capacity_in_bytes(Types) +
11785          llvm::capacity_in_bytes(VariableArrayTypes);
11786 }
11787 
11788 /// getIntTypeForBitwidth -
11789 /// sets integer QualTy according to specified details:
11790 /// bitwidth, signed/unsigned.
11791 /// Returns empty type if there is no appropriate target types.
11792 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11793                                            unsigned Signed) const {
11794   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11795   CanQualType QualTy = getFromTargetType(Ty);
11796   if (!QualTy && DestWidth == 128)
11797     return Signed ? Int128Ty : UnsignedInt128Ty;
11798   return QualTy;
11799 }
11800 
11801 /// getRealTypeForBitwidth -
11802 /// sets floating point QualTy according to specified bitwidth.
11803 /// Returns empty type if there is no appropriate target types.
11804 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11805                                             FloatModeKind ExplicitType) const {
11806   FloatModeKind Ty =
11807       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
11808   switch (Ty) {
11809   case FloatModeKind::Half:
11810     return HalfTy;
11811   case FloatModeKind::Float:
11812     return FloatTy;
11813   case FloatModeKind::Double:
11814     return DoubleTy;
11815   case FloatModeKind::LongDouble:
11816     return LongDoubleTy;
11817   case FloatModeKind::Float128:
11818     return Float128Ty;
11819   case FloatModeKind::Ibm128:
11820     return Ibm128Ty;
11821   case FloatModeKind::NoFloat:
11822     return {};
11823   }
11824 
11825   llvm_unreachable("Unhandled TargetInfo::RealType value");
11826 }
11827 
11828 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11829   if (Number > 1)
11830     MangleNumbers[ND] = Number;
11831 }
11832 
11833 unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
11834                                        bool ForAuxTarget) const {
11835   auto I = MangleNumbers.find(ND);
11836   unsigned Res = I != MangleNumbers.end() ? I->second : 1;
11837   // CUDA/HIP host compilation encodes host and device mangling numbers
11838   // as lower and upper half of 32 bit integer.
11839   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
11840     Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
11841   } else {
11842     assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
11843                             "number for aux target");
11844   }
11845   return Res > 1 ? Res : 1;
11846 }
11847 
11848 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11849   if (Number > 1)
11850     StaticLocalNumbers[VD] = Number;
11851 }
11852 
11853 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11854   auto I = StaticLocalNumbers.find(VD);
11855   return I != StaticLocalNumbers.end() ? I->second : 1;
11856 }
11857 
11858 MangleNumberingContext &
11859 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11860   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11861   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11862   if (!MCtx)
11863     MCtx = createMangleNumberingContext();
11864   return *MCtx;
11865 }
11866 
11867 MangleNumberingContext &
11868 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11869   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11870   std::unique_ptr<MangleNumberingContext> &MCtx =
11871       ExtraMangleNumberingContexts[D];
11872   if (!MCtx)
11873     MCtx = createMangleNumberingContext();
11874   return *MCtx;
11875 }
11876 
11877 std::unique_ptr<MangleNumberingContext>
11878 ASTContext::createMangleNumberingContext() const {
11879   return ABI->createMangleNumberingContext();
11880 }
11881 
11882 const CXXConstructorDecl *
11883 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11884   return ABI->getCopyConstructorForExceptionObject(
11885       cast<CXXRecordDecl>(RD->getFirstDecl()));
11886 }
11887 
11888 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11889                                                       CXXConstructorDecl *CD) {
11890   return ABI->addCopyConstructorForExceptionObject(
11891       cast<CXXRecordDecl>(RD->getFirstDecl()),
11892       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11893 }
11894 
11895 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11896                                                  TypedefNameDecl *DD) {
11897   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11898 }
11899 
11900 TypedefNameDecl *
11901 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11902   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11903 }
11904 
11905 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11906                                                 DeclaratorDecl *DD) {
11907   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11908 }
11909 
11910 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11911   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11912 }
11913 
11914 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11915   ParamIndices[D] = index;
11916 }
11917 
11918 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11919   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11920   assert(I != ParamIndices.end() &&
11921          "ParmIndices lacks entry set by ParmVarDecl");
11922   return I->second;
11923 }
11924 
11925 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11926                                                unsigned Length) const {
11927   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11928   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11929     EltTy = EltTy.withConst();
11930 
11931   EltTy = adjustStringLiteralBaseType(EltTy);
11932 
11933   // Get an array type for the string, according to C99 6.4.5. This includes
11934   // the null terminator character.
11935   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11936                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11937 }
11938 
11939 StringLiteral *
11940 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11941   StringLiteral *&Result = StringLiteralCache[Key];
11942   if (!Result)
11943     Result = StringLiteral::Create(
11944         *this, Key, StringLiteral::Ordinary,
11945         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11946         SourceLocation());
11947   return Result;
11948 }
11949 
11950 MSGuidDecl *
11951 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11952   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11953 
11954   llvm::FoldingSetNodeID ID;
11955   MSGuidDecl::Profile(ID, Parts);
11956 
11957   void *InsertPos;
11958   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11959     return Existing;
11960 
11961   QualType GUIDType = getMSGuidType().withConst();
11962   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11963   MSGuidDecls.InsertNode(New, InsertPos);
11964   return New;
11965 }
11966 
11967 UnnamedGlobalConstantDecl *
11968 ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
11969                                          const APValue &APVal) const {
11970   llvm::FoldingSetNodeID ID;
11971   UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
11972 
11973   void *InsertPos;
11974   if (UnnamedGlobalConstantDecl *Existing =
11975           UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
11976     return Existing;
11977 
11978   UnnamedGlobalConstantDecl *New =
11979       UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
11980   UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
11981   return New;
11982 }
11983 
11984 TemplateParamObjectDecl *
11985 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11986   assert(T->isRecordType() && "template param object of unexpected type");
11987 
11988   // C++ [temp.param]p8:
11989   //   [...] a static storage duration object of type 'const T' [...]
11990   T.addConst();
11991 
11992   llvm::FoldingSetNodeID ID;
11993   TemplateParamObjectDecl::Profile(ID, T, V);
11994 
11995   void *InsertPos;
11996   if (TemplateParamObjectDecl *Existing =
11997           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11998     return Existing;
11999 
12000   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12001   TemplateParamObjectDecls.InsertNode(New, InsertPos);
12002   return New;
12003 }
12004 
12005 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
12006   const llvm::Triple &T = getTargetInfo().getTriple();
12007   if (!T.isOSDarwin())
12008     return false;
12009 
12010   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12011       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12012     return false;
12013 
12014   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12015   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12016   uint64_t Size = sizeChars.getQuantity();
12017   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12018   unsigned Align = alignChars.getQuantity();
12019   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12020   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12021 }
12022 
12023 bool
12024 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
12025                                 const ObjCMethodDecl *MethodImpl) {
12026   // No point trying to match an unavailable/deprecated mothod.
12027   if (MethodDecl->hasAttr<UnavailableAttr>()
12028       || MethodDecl->hasAttr<DeprecatedAttr>())
12029     return false;
12030   if (MethodDecl->getObjCDeclQualifier() !=
12031       MethodImpl->getObjCDeclQualifier())
12032     return false;
12033   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12034     return false;
12035 
12036   if (MethodDecl->param_size() != MethodImpl->param_size())
12037     return false;
12038 
12039   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12040        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12041        EF = MethodDecl->param_end();
12042        IM != EM && IF != EF; ++IM, ++IF) {
12043     const ParmVarDecl *DeclVar = (*IF);
12044     const ParmVarDecl *ImplVar = (*IM);
12045     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12046       return false;
12047     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12048       return false;
12049   }
12050 
12051   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12052 }
12053 
12054 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
12055   LangAS AS;
12056   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
12057     AS = LangAS::Default;
12058   else
12059     AS = QT->getPointeeType().getAddressSpace();
12060 
12061   return getTargetInfo().getNullPointerValue(AS);
12062 }
12063 
12064 unsigned ASTContext::getTargetAddressSpace(QualType T) const {
12065   // Return the address space for the type. If the type is a
12066   // function type without an address space qualifier, the
12067   // program address space is used. Otherwise, the target picks
12068   // the best address space based on the type information
12069   return T->isFunctionType() && !T.hasAddressSpace()
12070              ? getTargetInfo().getProgramAddressSpace()
12071              : getTargetAddressSpace(T.getQualifiers());
12072 }
12073 
12074 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
12075   return getTargetAddressSpace(Q.getAddressSpace());
12076 }
12077 
12078 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
12079   if (isTargetAddressSpace(AS))
12080     return toTargetAddressSpace(AS);
12081   else
12082     return (*AddrSpaceMap)[(unsigned)AS];
12083 }
12084 
12085 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
12086   assert(Ty->isFixedPointType());
12087 
12088   if (Ty->isSaturatedFixedPointType()) return Ty;
12089 
12090   switch (Ty->castAs<BuiltinType>()->getKind()) {
12091     default:
12092       llvm_unreachable("Not a fixed point type!");
12093     case BuiltinType::ShortAccum:
12094       return SatShortAccumTy;
12095     case BuiltinType::Accum:
12096       return SatAccumTy;
12097     case BuiltinType::LongAccum:
12098       return SatLongAccumTy;
12099     case BuiltinType::UShortAccum:
12100       return SatUnsignedShortAccumTy;
12101     case BuiltinType::UAccum:
12102       return SatUnsignedAccumTy;
12103     case BuiltinType::ULongAccum:
12104       return SatUnsignedLongAccumTy;
12105     case BuiltinType::ShortFract:
12106       return SatShortFractTy;
12107     case BuiltinType::Fract:
12108       return SatFractTy;
12109     case BuiltinType::LongFract:
12110       return SatLongFractTy;
12111     case BuiltinType::UShortFract:
12112       return SatUnsignedShortFractTy;
12113     case BuiltinType::UFract:
12114       return SatUnsignedFractTy;
12115     case BuiltinType::ULongFract:
12116       return SatUnsignedLongFractTy;
12117   }
12118 }
12119 
12120 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
12121   if (LangOpts.OpenCL)
12122     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
12123 
12124   if (LangOpts.CUDA)
12125     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
12126 
12127   return getLangASFromTargetAS(AS);
12128 }
12129 
12130 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
12131 // doesn't include ASTContext.h
12132 template
12133 clang::LazyGenerationalUpdatePtr<
12134     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
12135 clang::LazyGenerationalUpdatePtr<
12136     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
12137         const clang::ASTContext &Ctx, Decl *Value);
12138 
12139 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
12140   assert(Ty->isFixedPointType());
12141 
12142   const TargetInfo &Target = getTargetInfo();
12143   switch (Ty->castAs<BuiltinType>()->getKind()) {
12144     default:
12145       llvm_unreachable("Not a fixed point type!");
12146     case BuiltinType::ShortAccum:
12147     case BuiltinType::SatShortAccum:
12148       return Target.getShortAccumScale();
12149     case BuiltinType::Accum:
12150     case BuiltinType::SatAccum:
12151       return Target.getAccumScale();
12152     case BuiltinType::LongAccum:
12153     case BuiltinType::SatLongAccum:
12154       return Target.getLongAccumScale();
12155     case BuiltinType::UShortAccum:
12156     case BuiltinType::SatUShortAccum:
12157       return Target.getUnsignedShortAccumScale();
12158     case BuiltinType::UAccum:
12159     case BuiltinType::SatUAccum:
12160       return Target.getUnsignedAccumScale();
12161     case BuiltinType::ULongAccum:
12162     case BuiltinType::SatULongAccum:
12163       return Target.getUnsignedLongAccumScale();
12164     case BuiltinType::ShortFract:
12165     case BuiltinType::SatShortFract:
12166       return Target.getShortFractScale();
12167     case BuiltinType::Fract:
12168     case BuiltinType::SatFract:
12169       return Target.getFractScale();
12170     case BuiltinType::LongFract:
12171     case BuiltinType::SatLongFract:
12172       return Target.getLongFractScale();
12173     case BuiltinType::UShortFract:
12174     case BuiltinType::SatUShortFract:
12175       return Target.getUnsignedShortFractScale();
12176     case BuiltinType::UFract:
12177     case BuiltinType::SatUFract:
12178       return Target.getUnsignedFractScale();
12179     case BuiltinType::ULongFract:
12180     case BuiltinType::SatULongFract:
12181       return Target.getUnsignedLongFractScale();
12182   }
12183 }
12184 
12185 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
12186   assert(Ty->isFixedPointType());
12187 
12188   const TargetInfo &Target = getTargetInfo();
12189   switch (Ty->castAs<BuiltinType>()->getKind()) {
12190     default:
12191       llvm_unreachable("Not a fixed point type!");
12192     case BuiltinType::ShortAccum:
12193     case BuiltinType::SatShortAccum:
12194       return Target.getShortAccumIBits();
12195     case BuiltinType::Accum:
12196     case BuiltinType::SatAccum:
12197       return Target.getAccumIBits();
12198     case BuiltinType::LongAccum:
12199     case BuiltinType::SatLongAccum:
12200       return Target.getLongAccumIBits();
12201     case BuiltinType::UShortAccum:
12202     case BuiltinType::SatUShortAccum:
12203       return Target.getUnsignedShortAccumIBits();
12204     case BuiltinType::UAccum:
12205     case BuiltinType::SatUAccum:
12206       return Target.getUnsignedAccumIBits();
12207     case BuiltinType::ULongAccum:
12208     case BuiltinType::SatULongAccum:
12209       return Target.getUnsignedLongAccumIBits();
12210     case BuiltinType::ShortFract:
12211     case BuiltinType::SatShortFract:
12212     case BuiltinType::Fract:
12213     case BuiltinType::SatFract:
12214     case BuiltinType::LongFract:
12215     case BuiltinType::SatLongFract:
12216     case BuiltinType::UShortFract:
12217     case BuiltinType::SatUShortFract:
12218     case BuiltinType::UFract:
12219     case BuiltinType::SatUFract:
12220     case BuiltinType::ULongFract:
12221     case BuiltinType::SatULongFract:
12222       return 0;
12223   }
12224 }
12225 
12226 llvm::FixedPointSemantics
12227 ASTContext::getFixedPointSemantics(QualType Ty) const {
12228   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
12229          "Can only get the fixed point semantics for a "
12230          "fixed point or integer type.");
12231   if (Ty->isIntegerType())
12232     return llvm::FixedPointSemantics::GetIntegerSemantics(
12233         getIntWidth(Ty), Ty->isSignedIntegerType());
12234 
12235   bool isSigned = Ty->isSignedFixedPointType();
12236   return llvm::FixedPointSemantics(
12237       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
12238       Ty->isSaturatedFixedPointType(),
12239       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
12240 }
12241 
12242 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
12243   assert(Ty->isFixedPointType());
12244   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
12245 }
12246 
12247 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
12248   assert(Ty->isFixedPointType());
12249   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
12250 }
12251 
12252 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
12253   assert(Ty->isUnsignedFixedPointType() &&
12254          "Expected unsigned fixed point type");
12255 
12256   switch (Ty->castAs<BuiltinType>()->getKind()) {
12257   case BuiltinType::UShortAccum:
12258     return ShortAccumTy;
12259   case BuiltinType::UAccum:
12260     return AccumTy;
12261   case BuiltinType::ULongAccum:
12262     return LongAccumTy;
12263   case BuiltinType::SatUShortAccum:
12264     return SatShortAccumTy;
12265   case BuiltinType::SatUAccum:
12266     return SatAccumTy;
12267   case BuiltinType::SatULongAccum:
12268     return SatLongAccumTy;
12269   case BuiltinType::UShortFract:
12270     return ShortFractTy;
12271   case BuiltinType::UFract:
12272     return FractTy;
12273   case BuiltinType::ULongFract:
12274     return LongFractTy;
12275   case BuiltinType::SatUShortFract:
12276     return SatShortFractTy;
12277   case BuiltinType::SatUFract:
12278     return SatFractTy;
12279   case BuiltinType::SatULongFract:
12280     return SatLongFractTy;
12281   default:
12282     llvm_unreachable("Unexpected unsigned fixed point type");
12283   }
12284 }
12285 
12286 ParsedTargetAttr
12287 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
12288   assert(TD != nullptr);
12289   ParsedTargetAttr ParsedAttr = TD->parse();
12290 
12291   llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
12292     return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
12293   });
12294   return ParsedAttr;
12295 }
12296 
12297 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12298                                        const FunctionDecl *FD) const {
12299   if (FD)
12300     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
12301   else
12302     Target->initFeatureMap(FeatureMap, getDiagnostics(),
12303                            Target->getTargetOpts().CPU,
12304                            Target->getTargetOpts().Features);
12305 }
12306 
12307 // Fills in the supplied string map with the set of target features for the
12308 // passed in function.
12309 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12310                                        GlobalDecl GD) const {
12311   StringRef TargetCPU = Target->getTargetOpts().CPU;
12312   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
12313   if (const auto *TD = FD->getAttr<TargetAttr>()) {
12314     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
12315 
12316     // Make a copy of the features as passed on the command line into the
12317     // beginning of the additional features from the function to override.
12318     ParsedAttr.Features.insert(
12319         ParsedAttr.Features.begin(),
12320         Target->getTargetOpts().FeaturesAsWritten.begin(),
12321         Target->getTargetOpts().FeaturesAsWritten.end());
12322 
12323     if (ParsedAttr.Architecture != "" &&
12324         Target->isValidCPUName(ParsedAttr.Architecture))
12325       TargetCPU = ParsedAttr.Architecture;
12326 
12327     // Now populate the feature map, first with the TargetCPU which is either
12328     // the default or a new one from the target attribute string. Then we'll use
12329     // the passed in features (FeaturesAsWritten) along with the new ones from
12330     // the attribute.
12331     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
12332                            ParsedAttr.Features);
12333   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
12334     llvm::SmallVector<StringRef, 32> FeaturesTmp;
12335     Target->getCPUSpecificCPUDispatchFeatures(
12336         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
12337     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
12338     Features.insert(Features.begin(),
12339                     Target->getTargetOpts().FeaturesAsWritten.begin(),
12340                     Target->getTargetOpts().FeaturesAsWritten.end());
12341     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12342   } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
12343     std::vector<std::string> Features;
12344     StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
12345     if (VersionStr.startswith("arch="))
12346       TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
12347     else if (VersionStr != "default")
12348       Features.push_back((StringRef{"+"} + VersionStr).str());
12349 
12350     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12351   } else {
12352     FeatureMap = Target->getTargetOpts().FeatureMap;
12353   }
12354 }
12355 
12356 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
12357   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
12358   return *OMPTraitInfoVector.back();
12359 }
12360 
12361 const StreamingDiagnostic &clang::
12362 operator<<(const StreamingDiagnostic &DB,
12363            const ASTContext::SectionInfo &Section) {
12364   if (Section.Decl)
12365     return DB << Section.Decl;
12366   return DB << "a prior #pragma section";
12367 }
12368 
12369 bool ASTContext::mayExternalize(const Decl *D) const {
12370   bool IsStaticVar =
12371       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
12372   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
12373                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
12374                              (D->hasAttr<CUDAConstantAttr>() &&
12375                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
12376   // CUDA/HIP: static managed variables need to be externalized since it is
12377   // a declaration in IR, therefore cannot have internal linkage. Kernels in
12378   // anonymous name space needs to be externalized to avoid duplicate symbols.
12379   return (IsStaticVar &&
12380           (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
12381          (D->hasAttr<CUDAGlobalAttr>() &&
12382           basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
12383               GVA_Internal);
12384 }
12385 
12386 bool ASTContext::shouldExternalize(const Decl *D) const {
12387   return mayExternalize(D) &&
12388          (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
12389           CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
12390 }
12391 
12392 StringRef ASTContext::getCUIDHash() const {
12393   if (!CUIDHash.empty())
12394     return CUIDHash;
12395   if (LangOpts.CUID.empty())
12396     return StringRef();
12397   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
12398   return CUIDHash;
12399 }
12400