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     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
743       NewConverted.push_back(Arg);
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     for (auto &Arg : OldConverted.drop_front(1))
756       NewConverted.push_back(Arg);
757   }
758   Expr *NewIDC = ConceptSpecializationExpr::Create(
759       C, CSE->getNamedConcept(), NewConverted, nullptr,
760       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
761 
762   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
763     NewIDC = new (C) CXXFoldExpr(
764         OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
765         BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
766         SourceLocation(), /*NumExpansions=*/None);
767   return NewIDC;
768 }
769 
770 TemplateTemplateParmDecl *
771 ASTContext::getCanonicalTemplateTemplateParmDecl(
772                                           TemplateTemplateParmDecl *TTP) const {
773   // Check if we already have a canonical template template parameter.
774   llvm::FoldingSetNodeID ID;
775   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
776   void *InsertPos = nullptr;
777   CanonicalTemplateTemplateParm *Canonical
778     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
779   if (Canonical)
780     return Canonical->getParam();
781 
782   // Build a canonical template parameter list.
783   TemplateParameterList *Params = TTP->getTemplateParameters();
784   SmallVector<NamedDecl *, 4> CanonParams;
785   CanonParams.reserve(Params->size());
786   for (TemplateParameterList::const_iterator P = Params->begin(),
787                                           PEnd = Params->end();
788        P != PEnd; ++P) {
789     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
790       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
791           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
792           TTP->getDepth(), TTP->getIndex(), nullptr, false,
793           TTP->isParameterPack(), TTP->hasTypeConstraint(),
794           TTP->isExpandedParameterPack() ?
795           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
796       if (const auto *TC = TTP->getTypeConstraint()) {
797         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
798         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
799                 *this, TC->getImmediatelyDeclaredConstraint(),
800                 ParamAsArgument);
801         TemplateArgumentListInfo CanonArgsAsWritten;
802         if (auto *Args = TC->getTemplateArgsAsWritten())
803           for (const auto &ArgLoc : Args->arguments())
804             CanonArgsAsWritten.addArgument(
805                 TemplateArgumentLoc(ArgLoc.getArgument(),
806                                     TemplateArgumentLocInfo()));
807         NewTTP->setTypeConstraint(
808             NestedNameSpecifierLoc(),
809             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
810                                 SourceLocation()), /*FoundDecl=*/nullptr,
811             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
812             // simply omit the ArgsAsWritten
813             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
814       }
815       CanonParams.push_back(NewTTP);
816     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
817       QualType T = getCanonicalType(NTTP->getType());
818       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
819       NonTypeTemplateParmDecl *Param;
820       if (NTTP->isExpandedParameterPack()) {
821         SmallVector<QualType, 2> ExpandedTypes;
822         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
823         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
824           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
825           ExpandedTInfos.push_back(
826                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
827         }
828 
829         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
830                                                 SourceLocation(),
831                                                 SourceLocation(),
832                                                 NTTP->getDepth(),
833                                                 NTTP->getPosition(), nullptr,
834                                                 T,
835                                                 TInfo,
836                                                 ExpandedTypes,
837                                                 ExpandedTInfos);
838       } else {
839         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
840                                                 SourceLocation(),
841                                                 SourceLocation(),
842                                                 NTTP->getDepth(),
843                                                 NTTP->getPosition(), nullptr,
844                                                 T,
845                                                 NTTP->isParameterPack(),
846                                                 TInfo);
847       }
848       if (AutoType *AT = T->getContainedAutoType()) {
849         if (AT->isConstrained()) {
850           Param->setPlaceholderTypeConstraint(
851               canonicalizeImmediatelyDeclaredConstraint(
852                   *this, NTTP->getPlaceholderTypeConstraint(), T));
853         }
854       }
855       CanonParams.push_back(Param);
856 
857     } else
858       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
859                                            cast<TemplateTemplateParmDecl>(*P)));
860   }
861 
862   Expr *CanonRequiresClause = nullptr;
863   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
864     CanonRequiresClause = RequiresClause;
865 
866   TemplateTemplateParmDecl *CanonTTP
867     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
868                                        SourceLocation(), TTP->getDepth(),
869                                        TTP->getPosition(),
870                                        TTP->isParameterPack(),
871                                        nullptr,
872                          TemplateParameterList::Create(*this, SourceLocation(),
873                                                        SourceLocation(),
874                                                        CanonParams,
875                                                        SourceLocation(),
876                                                        CanonRequiresClause));
877 
878   // Get the new insert position for the node we care about.
879   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
880   assert(!Canonical && "Shouldn't be in the map!");
881   (void)Canonical;
882 
883   // Create the canonical template template parameter entry.
884   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
885   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
886   return CanonTTP;
887 }
888 
889 TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
890   auto Kind = getTargetInfo().getCXXABI().getKind();
891   return getLangOpts().CXXABI.getValueOr(Kind);
892 }
893 
894 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
895   if (!LangOpts.CPlusPlus) return nullptr;
896 
897   switch (getCXXABIKind()) {
898   case TargetCXXABI::AppleARM64:
899   case TargetCXXABI::Fuchsia:
900   case TargetCXXABI::GenericARM: // Same as Itanium at this level
901   case TargetCXXABI::iOS:
902   case TargetCXXABI::WatchOS:
903   case TargetCXXABI::GenericAArch64:
904   case TargetCXXABI::GenericMIPS:
905   case TargetCXXABI::GenericItanium:
906   case TargetCXXABI::WebAssembly:
907   case TargetCXXABI::XL:
908     return CreateItaniumCXXABI(*this);
909   case TargetCXXABI::Microsoft:
910     return CreateMicrosoftCXXABI(*this);
911   }
912   llvm_unreachable("Invalid CXXABI type!");
913 }
914 
915 interp::Context &ASTContext::getInterpContext() {
916   if (!InterpContext) {
917     InterpContext.reset(new interp::Context(*this));
918   }
919   return *InterpContext.get();
920 }
921 
922 ParentMapContext &ASTContext::getParentMapContext() {
923   if (!ParentMapCtx)
924     ParentMapCtx.reset(new ParentMapContext(*this));
925   return *ParentMapCtx.get();
926 }
927 
928 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
929                                            const LangOptions &LOpts) {
930   if (LOpts.FakeAddressSpaceMap) {
931     // The fake address space map must have a distinct entry for each
932     // language-specific address space.
933     static const unsigned FakeAddrSpaceMap[] = {
934         0,  // Default
935         1,  // opencl_global
936         3,  // opencl_local
937         2,  // opencl_constant
938         0,  // opencl_private
939         4,  // opencl_generic
940         5,  // opencl_global_device
941         6,  // opencl_global_host
942         7,  // cuda_device
943         8,  // cuda_constant
944         9,  // cuda_shared
945         1,  // sycl_global
946         5,  // sycl_global_device
947         6,  // sycl_global_host
948         3,  // sycl_local
949         0,  // sycl_private
950         10, // ptr32_sptr
951         11, // ptr32_uptr
952         12  // ptr64
953     };
954     return &FakeAddrSpaceMap;
955   } else {
956     return &T.getAddressSpaceMap();
957   }
958 }
959 
960 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
961                                           const LangOptions &LangOpts) {
962   switch (LangOpts.getAddressSpaceMapMangling()) {
963   case LangOptions::ASMM_Target:
964     return TI.useAddressSpaceMapMangling();
965   case LangOptions::ASMM_On:
966     return true;
967   case LangOptions::ASMM_Off:
968     return false;
969   }
970   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
971 }
972 
973 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
974                        IdentifierTable &idents, SelectorTable &sels,
975                        Builtin::Context &builtins, TranslationUnitKind TUKind)
976     : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
977       FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
978       TemplateSpecializationTypes(this_()),
979       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
980       SubstTemplateTemplateParmPacks(this_()),
981       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
982       NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
983       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
984                                         LangOpts.XRayNeverInstrumentFiles,
985                                         LangOpts.XRayAttrListFiles, SM)),
986       ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
987       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
988       BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
989       Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
990       CompCategories(this_()), LastSDM(nullptr, 0) {
991   addTranslationUnitDecl();
992 }
993 
994 void ASTContext::cleanup() {
995   // Release the DenseMaps associated with DeclContext objects.
996   // FIXME: Is this the ideal solution?
997   ReleaseDeclContextMaps();
998 
999   // Call all of the deallocation functions on all of their targets.
1000   for (auto &Pair : Deallocations)
1001     (Pair.first)(Pair.second);
1002   Deallocations.clear();
1003 
1004   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
1005   // because they can contain DenseMaps.
1006   for (llvm::DenseMap<const ObjCContainerDecl*,
1007        const ASTRecordLayout*>::iterator
1008        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
1009     // Increment in loop to prevent using deallocated memory.
1010     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1011       R->Destroy(*this);
1012   ObjCLayouts.clear();
1013 
1014   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1015        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1016     // Increment in loop to prevent using deallocated memory.
1017     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1018       R->Destroy(*this);
1019   }
1020   ASTRecordLayouts.clear();
1021 
1022   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1023                                                     AEnd = DeclAttrs.end();
1024        A != AEnd; ++A)
1025     A->second->~AttrVec();
1026   DeclAttrs.clear();
1027 
1028   for (const auto &Value : ModuleInitializers)
1029     Value.second->~PerModuleInitializers();
1030   ModuleInitializers.clear();
1031 }
1032 
1033 ASTContext::~ASTContext() { cleanup(); }
1034 
1035 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1036   TraversalScope = TopLevelDecls;
1037   getParentMapContext().clear();
1038 }
1039 
1040 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1041   Deallocations.push_back({Callback, Data});
1042 }
1043 
1044 void
1045 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1046   ExternalSource = std::move(Source);
1047 }
1048 
1049 void ASTContext::PrintStats() const {
1050   llvm::errs() << "\n*** AST Context Stats:\n";
1051   llvm::errs() << "  " << Types.size() << " types total.\n";
1052 
1053   unsigned counts[] = {
1054 #define TYPE(Name, Parent) 0,
1055 #define ABSTRACT_TYPE(Name, Parent)
1056 #include "clang/AST/TypeNodes.inc"
1057     0 // Extra
1058   };
1059 
1060   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1061     Type *T = Types[i];
1062     counts[(unsigned)T->getTypeClass()]++;
1063   }
1064 
1065   unsigned Idx = 0;
1066   unsigned TotalBytes = 0;
1067 #define TYPE(Name, Parent)                                              \
1068   if (counts[Idx])                                                      \
1069     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1070                  << " types, " << sizeof(Name##Type) << " each "        \
1071                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1072                  << " bytes)\n";                                        \
1073   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1074   ++Idx;
1075 #define ABSTRACT_TYPE(Name, Parent)
1076 #include "clang/AST/TypeNodes.inc"
1077 
1078   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1079 
1080   // Implicit special member functions.
1081   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1082                << NumImplicitDefaultConstructors
1083                << " implicit default constructors created\n";
1084   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1085                << NumImplicitCopyConstructors
1086                << " implicit copy constructors created\n";
1087   if (getLangOpts().CPlusPlus)
1088     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1089                  << NumImplicitMoveConstructors
1090                  << " implicit move constructors created\n";
1091   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1092                << NumImplicitCopyAssignmentOperators
1093                << " implicit copy assignment operators created\n";
1094   if (getLangOpts().CPlusPlus)
1095     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1096                  << NumImplicitMoveAssignmentOperators
1097                  << " implicit move assignment operators created\n";
1098   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1099                << NumImplicitDestructors
1100                << " implicit destructors created\n";
1101 
1102   if (ExternalSource) {
1103     llvm::errs() << "\n";
1104     ExternalSource->PrintStats();
1105   }
1106 
1107   BumpAlloc.PrintStats();
1108 }
1109 
1110 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1111                                            bool NotifyListeners) {
1112   if (NotifyListeners)
1113     if (auto *Listener = getASTMutationListener())
1114       Listener->RedefinedHiddenDefinition(ND, M);
1115 
1116   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1117 }
1118 
1119 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1120   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1121   if (It == MergedDefModules.end())
1122     return;
1123 
1124   auto &Merged = It->second;
1125   llvm::DenseSet<Module*> Found;
1126   for (Module *&M : Merged)
1127     if (!Found.insert(M).second)
1128       M = nullptr;
1129   llvm::erase_value(Merged, nullptr);
1130 }
1131 
1132 ArrayRef<Module *>
1133 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1134   auto MergedIt =
1135       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1136   if (MergedIt == MergedDefModules.end())
1137     return None;
1138   return MergedIt->second;
1139 }
1140 
1141 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1142   if (LazyInitializers.empty())
1143     return;
1144 
1145   auto *Source = Ctx.getExternalSource();
1146   assert(Source && "lazy initializers but no external source");
1147 
1148   auto LazyInits = std::move(LazyInitializers);
1149   LazyInitializers.clear();
1150 
1151   for (auto ID : LazyInits)
1152     Initializers.push_back(Source->GetExternalDecl(ID));
1153 
1154   assert(LazyInitializers.empty() &&
1155          "GetExternalDecl for lazy module initializer added more inits");
1156 }
1157 
1158 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1159   // One special case: if we add a module initializer that imports another
1160   // module, and that module's only initializer is an ImportDecl, simplify.
1161   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1162     auto It = ModuleInitializers.find(ID->getImportedModule());
1163 
1164     // Maybe the ImportDecl does nothing at all. (Common case.)
1165     if (It == ModuleInitializers.end())
1166       return;
1167 
1168     // Maybe the ImportDecl only imports another ImportDecl.
1169     auto &Imported = *It->second;
1170     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1171       Imported.resolve(*this);
1172       auto *OnlyDecl = Imported.Initializers.front();
1173       if (isa<ImportDecl>(OnlyDecl))
1174         D = OnlyDecl;
1175     }
1176   }
1177 
1178   auto *&Inits = ModuleInitializers[M];
1179   if (!Inits)
1180     Inits = new (*this) PerModuleInitializers;
1181   Inits->Initializers.push_back(D);
1182 }
1183 
1184 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1185   auto *&Inits = ModuleInitializers[M];
1186   if (!Inits)
1187     Inits = new (*this) PerModuleInitializers;
1188   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1189                                  IDs.begin(), IDs.end());
1190 }
1191 
1192 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1193   auto It = ModuleInitializers.find(M);
1194   if (It == ModuleInitializers.end())
1195     return None;
1196 
1197   auto *Inits = It->second;
1198   Inits->resolve(*this);
1199   return Inits->Initializers;
1200 }
1201 
1202 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1203   if (!ExternCContext)
1204     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1205 
1206   return ExternCContext;
1207 }
1208 
1209 BuiltinTemplateDecl *
1210 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1211                                      const IdentifierInfo *II) const {
1212   auto *BuiltinTemplate =
1213       BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1214   BuiltinTemplate->setImplicit();
1215   getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1216 
1217   return BuiltinTemplate;
1218 }
1219 
1220 BuiltinTemplateDecl *
1221 ASTContext::getMakeIntegerSeqDecl() const {
1222   if (!MakeIntegerSeqDecl)
1223     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1224                                                   getMakeIntegerSeqName());
1225   return MakeIntegerSeqDecl;
1226 }
1227 
1228 BuiltinTemplateDecl *
1229 ASTContext::getTypePackElementDecl() const {
1230   if (!TypePackElementDecl)
1231     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1232                                                    getTypePackElementName());
1233   return TypePackElementDecl;
1234 }
1235 
1236 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1237                                             RecordDecl::TagKind TK) const {
1238   SourceLocation Loc;
1239   RecordDecl *NewDecl;
1240   if (getLangOpts().CPlusPlus)
1241     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1242                                     Loc, &Idents.get(Name));
1243   else
1244     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1245                                  &Idents.get(Name));
1246   NewDecl->setImplicit();
1247   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1248       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1249   return NewDecl;
1250 }
1251 
1252 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1253                                               StringRef Name) const {
1254   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1255   TypedefDecl *NewDecl = TypedefDecl::Create(
1256       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1257       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1258   NewDecl->setImplicit();
1259   return NewDecl;
1260 }
1261 
1262 TypedefDecl *ASTContext::getInt128Decl() const {
1263   if (!Int128Decl)
1264     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1265   return Int128Decl;
1266 }
1267 
1268 TypedefDecl *ASTContext::getUInt128Decl() const {
1269   if (!UInt128Decl)
1270     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1271   return UInt128Decl;
1272 }
1273 
1274 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1275   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1276   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1277   Types.push_back(Ty);
1278 }
1279 
1280 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1281                                   const TargetInfo *AuxTarget) {
1282   assert((!this->Target || this->Target == &Target) &&
1283          "Incorrect target reinitialization");
1284   assert(VoidTy.isNull() && "Context reinitialized?");
1285 
1286   this->Target = &Target;
1287   this->AuxTarget = AuxTarget;
1288 
1289   ABI.reset(createCXXABI(Target));
1290   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1291   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1292 
1293   // C99 6.2.5p19.
1294   InitBuiltinType(VoidTy,              BuiltinType::Void);
1295 
1296   // C99 6.2.5p2.
1297   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1298   // C99 6.2.5p3.
1299   if (LangOpts.CharIsSigned)
1300     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1301   else
1302     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1303   // C99 6.2.5p4.
1304   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1305   InitBuiltinType(ShortTy,             BuiltinType::Short);
1306   InitBuiltinType(IntTy,               BuiltinType::Int);
1307   InitBuiltinType(LongTy,              BuiltinType::Long);
1308   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1309 
1310   // C99 6.2.5p6.
1311   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1312   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1313   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1314   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1315   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1316 
1317   // C99 6.2.5p10.
1318   InitBuiltinType(FloatTy,             BuiltinType::Float);
1319   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1320   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1321 
1322   // GNU extension, __float128 for IEEE quadruple precision
1323   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1324 
1325   // __ibm128 for IBM extended precision
1326   InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1327 
1328   // C11 extension ISO/IEC TS 18661-3
1329   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1330 
1331   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1332   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1333   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1334   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1335   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1336   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1337   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1338   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1339   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1340   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1341   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1342   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1343   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1344   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1345   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1346   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1347   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1348   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1349   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1350   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1351   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1352   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1353   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1354   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1355   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1356 
1357   // GNU extension, 128-bit integers.
1358   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1359   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1360 
1361   // C++ 3.9.1p5
1362   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1363     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1364   else  // -fshort-wchar makes wchar_t be unsigned.
1365     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1366   if (LangOpts.CPlusPlus && LangOpts.WChar)
1367     WideCharTy = WCharTy;
1368   else {
1369     // C99 (or C++ using -fno-wchar).
1370     WideCharTy = getFromTargetType(Target.getWCharType());
1371   }
1372 
1373   WIntTy = getFromTargetType(Target.getWIntType());
1374 
1375   // C++20 (proposed)
1376   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1377 
1378   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1379     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1380   else // C99
1381     Char16Ty = getFromTargetType(Target.getChar16Type());
1382 
1383   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1384     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1385   else // C99
1386     Char32Ty = getFromTargetType(Target.getChar32Type());
1387 
1388   // Placeholder type for type-dependent expressions whose type is
1389   // completely unknown. No code should ever check a type against
1390   // DependentTy and users should never see it; however, it is here to
1391   // help diagnose failures to properly check for type-dependent
1392   // expressions.
1393   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1394 
1395   // Placeholder type for functions.
1396   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1397 
1398   // Placeholder type for bound members.
1399   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1400 
1401   // Placeholder type for pseudo-objects.
1402   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1403 
1404   // "any" type; useful for debugger-like clients.
1405   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1406 
1407   // Placeholder type for unbridged ARC casts.
1408   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1409 
1410   // Placeholder type for builtin functions.
1411   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1412 
1413   // Placeholder type for OMP array sections.
1414   if (LangOpts.OpenMP) {
1415     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1416     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1417     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1418   }
1419   if (LangOpts.MatrixTypes)
1420     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1421 
1422   // Builtin types for 'id', 'Class', and 'SEL'.
1423   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1424   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1425   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1426 
1427   if (LangOpts.OpenCL) {
1428 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1429     InitBuiltinType(SingletonId, BuiltinType::Id);
1430 #include "clang/Basic/OpenCLImageTypes.def"
1431 
1432     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1433     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1434     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1435     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1436     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1437 
1438 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1439     InitBuiltinType(Id##Ty, BuiltinType::Id);
1440 #include "clang/Basic/OpenCLExtensionTypes.def"
1441   }
1442 
1443   if (Target.hasAArch64SVETypes()) {
1444 #define SVE_TYPE(Name, Id, SingletonId) \
1445     InitBuiltinType(SingletonId, BuiltinType::Id);
1446 #include "clang/Basic/AArch64SVEACLETypes.def"
1447   }
1448 
1449   if (Target.getTriple().isPPC64()) {
1450 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1451       InitBuiltinType(Id##Ty, BuiltinType::Id);
1452 #include "clang/Basic/PPCTypes.def"
1453 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1454     InitBuiltinType(Id##Ty, BuiltinType::Id);
1455 #include "clang/Basic/PPCTypes.def"
1456   }
1457 
1458   if (Target.hasRISCVVTypes()) {
1459 #define RVV_TYPE(Name, Id, SingletonId)                                        \
1460   InitBuiltinType(SingletonId, BuiltinType::Id);
1461 #include "clang/Basic/RISCVVTypes.def"
1462   }
1463 
1464   // Builtin type for __objc_yes and __objc_no
1465   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1466                        SignedCharTy : BoolTy);
1467 
1468   ObjCConstantStringType = QualType();
1469 
1470   ObjCSuperType = QualType();
1471 
1472   // void * type
1473   if (LangOpts.OpenCLGenericAddressSpace) {
1474     auto Q = VoidTy.getQualifiers();
1475     Q.setAddressSpace(LangAS::opencl_generic);
1476     VoidPtrTy = getPointerType(getCanonicalType(
1477         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1478   } else {
1479     VoidPtrTy = getPointerType(VoidTy);
1480   }
1481 
1482   // nullptr type (C++0x 2.14.7)
1483   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1484 
1485   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1486   InitBuiltinType(HalfTy, BuiltinType::Half);
1487 
1488   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1489 
1490   // Builtin type used to help define __builtin_va_list.
1491   VaListTagDecl = nullptr;
1492 
1493   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1494   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1495     MSGuidTagDecl = buildImplicitRecord("_GUID");
1496     getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1497   }
1498 }
1499 
1500 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1501   return SourceMgr.getDiagnostics();
1502 }
1503 
1504 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1505   AttrVec *&Result = DeclAttrs[D];
1506   if (!Result) {
1507     void *Mem = Allocate(sizeof(AttrVec));
1508     Result = new (Mem) AttrVec;
1509   }
1510 
1511   return *Result;
1512 }
1513 
1514 /// Erase the attributes corresponding to the given declaration.
1515 void ASTContext::eraseDeclAttrs(const Decl *D) {
1516   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1517   if (Pos != DeclAttrs.end()) {
1518     Pos->second->~AttrVec();
1519     DeclAttrs.erase(Pos);
1520   }
1521 }
1522 
1523 // FIXME: Remove ?
1524 MemberSpecializationInfo *
1525 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1526   assert(Var->isStaticDataMember() && "Not a static data member");
1527   return getTemplateOrSpecializationInfo(Var)
1528       .dyn_cast<MemberSpecializationInfo *>();
1529 }
1530 
1531 ASTContext::TemplateOrSpecializationInfo
1532 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1533   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1534       TemplateOrInstantiation.find(Var);
1535   if (Pos == TemplateOrInstantiation.end())
1536     return {};
1537 
1538   return Pos->second;
1539 }
1540 
1541 void
1542 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1543                                                 TemplateSpecializationKind TSK,
1544                                           SourceLocation PointOfInstantiation) {
1545   assert(Inst->isStaticDataMember() && "Not a static data member");
1546   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1547   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1548                                             Tmpl, TSK, PointOfInstantiation));
1549 }
1550 
1551 void
1552 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1553                                             TemplateOrSpecializationInfo TSI) {
1554   assert(!TemplateOrInstantiation[Inst] &&
1555          "Already noted what the variable was instantiated from");
1556   TemplateOrInstantiation[Inst] = TSI;
1557 }
1558 
1559 NamedDecl *
1560 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1561   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1562   if (Pos == InstantiatedFromUsingDecl.end())
1563     return nullptr;
1564 
1565   return Pos->second;
1566 }
1567 
1568 void
1569 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1570   assert((isa<UsingDecl>(Pattern) ||
1571           isa<UnresolvedUsingValueDecl>(Pattern) ||
1572           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1573          "pattern decl is not a using decl");
1574   assert((isa<UsingDecl>(Inst) ||
1575           isa<UnresolvedUsingValueDecl>(Inst) ||
1576           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1577          "instantiation did not produce a using decl");
1578   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1579   InstantiatedFromUsingDecl[Inst] = Pattern;
1580 }
1581 
1582 UsingEnumDecl *
1583 ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1584   auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
1585   if (Pos == InstantiatedFromUsingEnumDecl.end())
1586     return nullptr;
1587 
1588   return Pos->second;
1589 }
1590 
1591 void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1592                                                   UsingEnumDecl *Pattern) {
1593   assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1594   InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1595 }
1596 
1597 UsingShadowDecl *
1598 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1599   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1600     = InstantiatedFromUsingShadowDecl.find(Inst);
1601   if (Pos == InstantiatedFromUsingShadowDecl.end())
1602     return nullptr;
1603 
1604   return Pos->second;
1605 }
1606 
1607 void
1608 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1609                                                UsingShadowDecl *Pattern) {
1610   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1611   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1612 }
1613 
1614 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1615   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1616     = InstantiatedFromUnnamedFieldDecl.find(Field);
1617   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1618     return nullptr;
1619 
1620   return Pos->second;
1621 }
1622 
1623 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1624                                                      FieldDecl *Tmpl) {
1625   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1626   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1627   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1628          "Already noted what unnamed field was instantiated from");
1629 
1630   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1631 }
1632 
1633 ASTContext::overridden_cxx_method_iterator
1634 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1635   return overridden_methods(Method).begin();
1636 }
1637 
1638 ASTContext::overridden_cxx_method_iterator
1639 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1640   return overridden_methods(Method).end();
1641 }
1642 
1643 unsigned
1644 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1645   auto Range = overridden_methods(Method);
1646   return Range.end() - Range.begin();
1647 }
1648 
1649 ASTContext::overridden_method_range
1650 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1651   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1652       OverriddenMethods.find(Method->getCanonicalDecl());
1653   if (Pos == OverriddenMethods.end())
1654     return overridden_method_range(nullptr, nullptr);
1655   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1656 }
1657 
1658 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1659                                      const CXXMethodDecl *Overridden) {
1660   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1661   OverriddenMethods[Method].push_back(Overridden);
1662 }
1663 
1664 void ASTContext::getOverriddenMethods(
1665                       const NamedDecl *D,
1666                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1667   assert(D);
1668 
1669   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1670     Overridden.append(overridden_methods_begin(CXXMethod),
1671                       overridden_methods_end(CXXMethod));
1672     return;
1673   }
1674 
1675   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1676   if (!Method)
1677     return;
1678 
1679   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1680   Method->getOverriddenMethods(OverDecls);
1681   Overridden.append(OverDecls.begin(), OverDecls.end());
1682 }
1683 
1684 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1685   assert(!Import->getNextLocalImport() &&
1686          "Import declaration already in the chain");
1687   assert(!Import->isFromASTFile() && "Non-local import declaration");
1688   if (!FirstLocalImport) {
1689     FirstLocalImport = Import;
1690     LastLocalImport = Import;
1691     return;
1692   }
1693 
1694   LastLocalImport->setNextLocalImport(Import);
1695   LastLocalImport = Import;
1696 }
1697 
1698 //===----------------------------------------------------------------------===//
1699 //                         Type Sizing and Analysis
1700 //===----------------------------------------------------------------------===//
1701 
1702 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1703 /// scalar floating point type.
1704 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1705   switch (T->castAs<BuiltinType>()->getKind()) {
1706   default:
1707     llvm_unreachable("Not a floating point type!");
1708   case BuiltinType::BFloat16:
1709     return Target->getBFloat16Format();
1710   case BuiltinType::Float16:
1711   case BuiltinType::Half:
1712     return Target->getHalfFormat();
1713   case BuiltinType::Float:      return Target->getFloatFormat();
1714   case BuiltinType::Double:     return Target->getDoubleFormat();
1715   case BuiltinType::Ibm128:
1716     return Target->getIbm128Format();
1717   case BuiltinType::LongDouble:
1718     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1719       return AuxTarget->getLongDoubleFormat();
1720     return Target->getLongDoubleFormat();
1721   case BuiltinType::Float128:
1722     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1723       return AuxTarget->getFloat128Format();
1724     return Target->getFloat128Format();
1725   }
1726 }
1727 
1728 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1729   unsigned Align = Target->getCharWidth();
1730 
1731   bool UseAlignAttrOnly = false;
1732   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1733     Align = AlignFromAttr;
1734 
1735     // __attribute__((aligned)) can increase or decrease alignment
1736     // *except* on a struct or struct member, where it only increases
1737     // alignment unless 'packed' is also specified.
1738     //
1739     // It is an error for alignas to decrease alignment, so we can
1740     // ignore that possibility;  Sema should diagnose it.
1741     if (isa<FieldDecl>(D)) {
1742       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1743         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1744     } else {
1745       UseAlignAttrOnly = true;
1746     }
1747   }
1748   else if (isa<FieldDecl>(D))
1749       UseAlignAttrOnly =
1750         D->hasAttr<PackedAttr>() ||
1751         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1752 
1753   // If we're using the align attribute only, just ignore everything
1754   // else about the declaration and its type.
1755   if (UseAlignAttrOnly) {
1756     // do nothing
1757   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1758     QualType T = VD->getType();
1759     if (const auto *RT = T->getAs<ReferenceType>()) {
1760       if (ForAlignof)
1761         T = RT->getPointeeType();
1762       else
1763         T = getPointerType(RT->getPointeeType());
1764     }
1765     QualType BaseT = getBaseElementType(T);
1766     if (T->isFunctionType())
1767       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1768     else if (!BaseT->isIncompleteType()) {
1769       // Adjust alignments of declarations with array type by the
1770       // large-array alignment on the target.
1771       if (const ArrayType *arrayType = getAsArrayType(T)) {
1772         unsigned MinWidth = Target->getLargeArrayMinWidth();
1773         if (!ForAlignof && MinWidth) {
1774           if (isa<VariableArrayType>(arrayType))
1775             Align = std::max(Align, Target->getLargeArrayAlign());
1776           else if (isa<ConstantArrayType>(arrayType) &&
1777                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1778             Align = std::max(Align, Target->getLargeArrayAlign());
1779         }
1780       }
1781       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1782       if (BaseT.getQualifiers().hasUnaligned())
1783         Align = Target->getCharWidth();
1784       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1785         if (VD->hasGlobalStorage() && !ForAlignof) {
1786           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1787           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1788         }
1789       }
1790     }
1791 
1792     // Fields can be subject to extra alignment constraints, like if
1793     // the field is packed, the struct is packed, or the struct has a
1794     // a max-field-alignment constraint (#pragma pack).  So calculate
1795     // the actual alignment of the field within the struct, and then
1796     // (as we're expected to) constrain that by the alignment of the type.
1797     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1798       const RecordDecl *Parent = Field->getParent();
1799       // We can only produce a sensible answer if the record is valid.
1800       if (!Parent->isInvalidDecl()) {
1801         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1802 
1803         // Start with the record's overall alignment.
1804         unsigned FieldAlign = toBits(Layout.getAlignment());
1805 
1806         // Use the GCD of that and the offset within the record.
1807         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1808         if (Offset > 0) {
1809           // Alignment is always a power of 2, so the GCD will be a power of 2,
1810           // which means we get to do this crazy thing instead of Euclid's.
1811           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1812           if (LowBitOfOffset < FieldAlign)
1813             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1814         }
1815 
1816         Align = std::min(Align, FieldAlign);
1817       }
1818     }
1819   }
1820 
1821   // Some targets have hard limitation on the maximum requestable alignment in
1822   // aligned attribute for static variables.
1823   const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1824   const auto *VD = dyn_cast<VarDecl>(D);
1825   if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1826     Align = std::min(Align, MaxAlignedAttr);
1827 
1828   return toCharUnitsFromBits(Align);
1829 }
1830 
1831 CharUnits ASTContext::getExnObjectAlignment() const {
1832   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1833 }
1834 
1835 // getTypeInfoDataSizeInChars - Return the size of a type, in
1836 // chars. If the type is a record, its data size is returned.  This is
1837 // the size of the memcpy that's performed when assigning this type
1838 // using a trivial copy/move assignment operator.
1839 TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1840   TypeInfoChars Info = getTypeInfoInChars(T);
1841 
1842   // In C++, objects can sometimes be allocated into the tail padding
1843   // of a base-class subobject.  We decide whether that's possible
1844   // during class layout, so here we can just trust the layout results.
1845   if (getLangOpts().CPlusPlus) {
1846     if (const auto *RT = T->getAs<RecordType>()) {
1847       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1848       Info.Width = layout.getDataSize();
1849     }
1850   }
1851 
1852   return Info;
1853 }
1854 
1855 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1856 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1857 TypeInfoChars
1858 static getConstantArrayInfoInChars(const ASTContext &Context,
1859                                    const ConstantArrayType *CAT) {
1860   TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1861   uint64_t Size = CAT->getSize().getZExtValue();
1862   assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1863               (uint64_t)(-1)/Size) &&
1864          "Overflow in array type char size evaluation");
1865   uint64_t Width = EltInfo.Width.getQuantity() * Size;
1866   unsigned Align = EltInfo.Align.getQuantity();
1867   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1868       Context.getTargetInfo().getPointerWidth(0) == 64)
1869     Width = llvm::alignTo(Width, Align);
1870   return TypeInfoChars(CharUnits::fromQuantity(Width),
1871                        CharUnits::fromQuantity(Align),
1872                        EltInfo.AlignRequirement);
1873 }
1874 
1875 TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1876   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1877     return getConstantArrayInfoInChars(*this, CAT);
1878   TypeInfo Info = getTypeInfo(T);
1879   return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1880                        toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1881 }
1882 
1883 TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1884   return getTypeInfoInChars(T.getTypePtr());
1885 }
1886 
1887 bool ASTContext::isAlignmentRequired(const Type *T) const {
1888   return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1889 }
1890 
1891 bool ASTContext::isAlignmentRequired(QualType T) const {
1892   return isAlignmentRequired(T.getTypePtr());
1893 }
1894 
1895 unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1896                                          bool NeedsPreferredAlignment) const {
1897   // An alignment on a typedef overrides anything else.
1898   if (const auto *TT = T->getAs<TypedefType>())
1899     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1900       return Align;
1901 
1902   // If we have an (array of) complete type, we're done.
1903   T = getBaseElementType(T);
1904   if (!T->isIncompleteType())
1905     return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1906 
1907   // If we had an array type, its element type might be a typedef
1908   // type with an alignment attribute.
1909   if (const auto *TT = T->getAs<TypedefType>())
1910     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1911       return Align;
1912 
1913   // Otherwise, see if the declaration of the type had an attribute.
1914   if (const auto *TT = T->getAs<TagType>())
1915     return TT->getDecl()->getMaxAlignment();
1916 
1917   return 0;
1918 }
1919 
1920 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1921   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1922   if (I != MemoizedTypeInfo.end())
1923     return I->second;
1924 
1925   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1926   TypeInfo TI = getTypeInfoImpl(T);
1927   MemoizedTypeInfo[T] = TI;
1928   return TI;
1929 }
1930 
1931 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1932 /// method does not work on incomplete types.
1933 ///
1934 /// FIXME: Pointers into different addr spaces could have different sizes and
1935 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1936 /// should take a QualType, &c.
1937 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1938   uint64_t Width = 0;
1939   unsigned Align = 8;
1940   AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1941   unsigned AS = 0;
1942   switch (T->getTypeClass()) {
1943 #define TYPE(Class, Base)
1944 #define ABSTRACT_TYPE(Class, Base)
1945 #define NON_CANONICAL_TYPE(Class, Base)
1946 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1947 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1948   case Type::Class:                                                            \
1949   assert(!T->isDependentType() && "should not see dependent types here");      \
1950   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1951 #include "clang/AST/TypeNodes.inc"
1952     llvm_unreachable("Should not see dependent types");
1953 
1954   case Type::FunctionNoProto:
1955   case Type::FunctionProto:
1956     // GCC extension: alignof(function) = 32 bits
1957     Width = 0;
1958     Align = 32;
1959     break;
1960 
1961   case Type::IncompleteArray:
1962   case Type::VariableArray:
1963   case Type::ConstantArray: {
1964     // Model non-constant sized arrays as size zero, but track the alignment.
1965     uint64_t Size = 0;
1966     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1967       Size = CAT->getSize().getZExtValue();
1968 
1969     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1970     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1971            "Overflow in array type bit size evaluation");
1972     Width = EltInfo.Width * Size;
1973     Align = EltInfo.Align;
1974     AlignRequirement = EltInfo.AlignRequirement;
1975     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1976         getTargetInfo().getPointerWidth(0) == 64)
1977       Width = llvm::alignTo(Width, Align);
1978     break;
1979   }
1980 
1981   case Type::ExtVector:
1982   case Type::Vector: {
1983     const auto *VT = cast<VectorType>(T);
1984     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1985     Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1986                                       : EltInfo.Width * VT->getNumElements();
1987     // Enforce at least byte alignment.
1988     Align = std::max<unsigned>(8, Width);
1989 
1990     // If the alignment is not a power of 2, round up to the next power of 2.
1991     // This happens for non-power-of-2 length vectors.
1992     if (Align & (Align-1)) {
1993       Align = llvm::NextPowerOf2(Align);
1994       Width = llvm::alignTo(Width, Align);
1995     }
1996     // Adjust the alignment based on the target max.
1997     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1998     if (TargetVectorAlign && TargetVectorAlign < Align)
1999       Align = TargetVectorAlign;
2000     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
2001       // Adjust the alignment for fixed-length SVE vectors. This is important
2002       // for non-power-of-2 vector lengths.
2003       Align = 128;
2004     else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
2005       // Adjust the alignment for fixed-length SVE predicates.
2006       Align = 16;
2007     break;
2008   }
2009 
2010   case Type::ConstantMatrix: {
2011     const auto *MT = cast<ConstantMatrixType>(T);
2012     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2013     // The internal layout of a matrix value is implementation defined.
2014     // Initially be ABI compatible with arrays with respect to alignment and
2015     // size.
2016     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2017     Align = ElementInfo.Align;
2018     break;
2019   }
2020 
2021   case Type::Builtin:
2022     switch (cast<BuiltinType>(T)->getKind()) {
2023     default: llvm_unreachable("Unknown builtin type!");
2024     case BuiltinType::Void:
2025       // GCC extension: alignof(void) = 8 bits.
2026       Width = 0;
2027       Align = 8;
2028       break;
2029     case BuiltinType::Bool:
2030       Width = Target->getBoolWidth();
2031       Align = Target->getBoolAlign();
2032       break;
2033     case BuiltinType::Char_S:
2034     case BuiltinType::Char_U:
2035     case BuiltinType::UChar:
2036     case BuiltinType::SChar:
2037     case BuiltinType::Char8:
2038       Width = Target->getCharWidth();
2039       Align = Target->getCharAlign();
2040       break;
2041     case BuiltinType::WChar_S:
2042     case BuiltinType::WChar_U:
2043       Width = Target->getWCharWidth();
2044       Align = Target->getWCharAlign();
2045       break;
2046     case BuiltinType::Char16:
2047       Width = Target->getChar16Width();
2048       Align = Target->getChar16Align();
2049       break;
2050     case BuiltinType::Char32:
2051       Width = Target->getChar32Width();
2052       Align = Target->getChar32Align();
2053       break;
2054     case BuiltinType::UShort:
2055     case BuiltinType::Short:
2056       Width = Target->getShortWidth();
2057       Align = Target->getShortAlign();
2058       break;
2059     case BuiltinType::UInt:
2060     case BuiltinType::Int:
2061       Width = Target->getIntWidth();
2062       Align = Target->getIntAlign();
2063       break;
2064     case BuiltinType::ULong:
2065     case BuiltinType::Long:
2066       Width = Target->getLongWidth();
2067       Align = Target->getLongAlign();
2068       break;
2069     case BuiltinType::ULongLong:
2070     case BuiltinType::LongLong:
2071       Width = Target->getLongLongWidth();
2072       Align = Target->getLongLongAlign();
2073       break;
2074     case BuiltinType::Int128:
2075     case BuiltinType::UInt128:
2076       Width = 128;
2077       Align = 128; // int128_t is 128-bit aligned on all targets.
2078       break;
2079     case BuiltinType::ShortAccum:
2080     case BuiltinType::UShortAccum:
2081     case BuiltinType::SatShortAccum:
2082     case BuiltinType::SatUShortAccum:
2083       Width = Target->getShortAccumWidth();
2084       Align = Target->getShortAccumAlign();
2085       break;
2086     case BuiltinType::Accum:
2087     case BuiltinType::UAccum:
2088     case BuiltinType::SatAccum:
2089     case BuiltinType::SatUAccum:
2090       Width = Target->getAccumWidth();
2091       Align = Target->getAccumAlign();
2092       break;
2093     case BuiltinType::LongAccum:
2094     case BuiltinType::ULongAccum:
2095     case BuiltinType::SatLongAccum:
2096     case BuiltinType::SatULongAccum:
2097       Width = Target->getLongAccumWidth();
2098       Align = Target->getLongAccumAlign();
2099       break;
2100     case BuiltinType::ShortFract:
2101     case BuiltinType::UShortFract:
2102     case BuiltinType::SatShortFract:
2103     case BuiltinType::SatUShortFract:
2104       Width = Target->getShortFractWidth();
2105       Align = Target->getShortFractAlign();
2106       break;
2107     case BuiltinType::Fract:
2108     case BuiltinType::UFract:
2109     case BuiltinType::SatFract:
2110     case BuiltinType::SatUFract:
2111       Width = Target->getFractWidth();
2112       Align = Target->getFractAlign();
2113       break;
2114     case BuiltinType::LongFract:
2115     case BuiltinType::ULongFract:
2116     case BuiltinType::SatLongFract:
2117     case BuiltinType::SatULongFract:
2118       Width = Target->getLongFractWidth();
2119       Align = Target->getLongFractAlign();
2120       break;
2121     case BuiltinType::BFloat16:
2122       Width = Target->getBFloat16Width();
2123       Align = Target->getBFloat16Align();
2124       break;
2125     case BuiltinType::Float16:
2126     case BuiltinType::Half:
2127       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2128           !getLangOpts().OpenMPIsDevice) {
2129         Width = Target->getHalfWidth();
2130         Align = Target->getHalfAlign();
2131       } else {
2132         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2133                "Expected OpenMP device compilation.");
2134         Width = AuxTarget->getHalfWidth();
2135         Align = AuxTarget->getHalfAlign();
2136       }
2137       break;
2138     case BuiltinType::Float:
2139       Width = Target->getFloatWidth();
2140       Align = Target->getFloatAlign();
2141       break;
2142     case BuiltinType::Double:
2143       Width = Target->getDoubleWidth();
2144       Align = Target->getDoubleAlign();
2145       break;
2146     case BuiltinType::Ibm128:
2147       Width = Target->getIbm128Width();
2148       Align = Target->getIbm128Align();
2149       break;
2150     case BuiltinType::LongDouble:
2151       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2152           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2153            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2154         Width = AuxTarget->getLongDoubleWidth();
2155         Align = AuxTarget->getLongDoubleAlign();
2156       } else {
2157         Width = Target->getLongDoubleWidth();
2158         Align = Target->getLongDoubleAlign();
2159       }
2160       break;
2161     case BuiltinType::Float128:
2162       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2163           !getLangOpts().OpenMPIsDevice) {
2164         Width = Target->getFloat128Width();
2165         Align = Target->getFloat128Align();
2166       } else {
2167         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2168                "Expected OpenMP device compilation.");
2169         Width = AuxTarget->getFloat128Width();
2170         Align = AuxTarget->getFloat128Align();
2171       }
2172       break;
2173     case BuiltinType::NullPtr:
2174       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2175       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2176       break;
2177     case BuiltinType::ObjCId:
2178     case BuiltinType::ObjCClass:
2179     case BuiltinType::ObjCSel:
2180       Width = Target->getPointerWidth(0);
2181       Align = Target->getPointerAlign(0);
2182       break;
2183     case BuiltinType::OCLSampler:
2184     case BuiltinType::OCLEvent:
2185     case BuiltinType::OCLClkEvent:
2186     case BuiltinType::OCLQueue:
2187     case BuiltinType::OCLReserveID:
2188 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2189     case BuiltinType::Id:
2190 #include "clang/Basic/OpenCLImageTypes.def"
2191 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2192   case BuiltinType::Id:
2193 #include "clang/Basic/OpenCLExtensionTypes.def"
2194       AS = getTargetAddressSpace(
2195           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2196       Width = Target->getPointerWidth(AS);
2197       Align = Target->getPointerAlign(AS);
2198       break;
2199     // The SVE types are effectively target-specific.  The length of an
2200     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2201     // of 128 bits.  There is one predicate bit for each vector byte, so the
2202     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2203     //
2204     // Because the length is only known at runtime, we use a dummy value
2205     // of 0 for the static length.  The alignment values are those defined
2206     // by the Procedure Call Standard for the Arm Architecture.
2207 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2208                         IsSigned, IsFP, IsBF)                                  \
2209   case BuiltinType::Id:                                                        \
2210     Width = 0;                                                                 \
2211     Align = 128;                                                               \
2212     break;
2213 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2214   case BuiltinType::Id:                                                        \
2215     Width = 0;                                                                 \
2216     Align = 16;                                                                \
2217     break;
2218 #include "clang/Basic/AArch64SVEACLETypes.def"
2219 #define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2220   case BuiltinType::Id:                                                        \
2221     Width = Size;                                                              \
2222     Align = Size;                                                              \
2223     break;
2224 #include "clang/Basic/PPCTypes.def"
2225 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2226                         IsFP)                                                  \
2227   case BuiltinType::Id:                                                        \
2228     Width = 0;                                                                 \
2229     Align = ElBits;                                                            \
2230     break;
2231 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2232   case BuiltinType::Id:                                                        \
2233     Width = 0;                                                                 \
2234     Align = 8;                                                                 \
2235     break;
2236 #include "clang/Basic/RISCVVTypes.def"
2237     }
2238     break;
2239   case Type::ObjCObjectPointer:
2240     Width = Target->getPointerWidth(0);
2241     Align = Target->getPointerAlign(0);
2242     break;
2243   case Type::BlockPointer:
2244     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2245     Width = Target->getPointerWidth(AS);
2246     Align = Target->getPointerAlign(AS);
2247     break;
2248   case Type::LValueReference:
2249   case Type::RValueReference:
2250     // alignof and sizeof should never enter this code path here, so we go
2251     // the pointer route.
2252     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2253     Width = Target->getPointerWidth(AS);
2254     Align = Target->getPointerAlign(AS);
2255     break;
2256   case Type::Pointer:
2257     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2258     Width = Target->getPointerWidth(AS);
2259     Align = Target->getPointerAlign(AS);
2260     break;
2261   case Type::MemberPointer: {
2262     const auto *MPT = cast<MemberPointerType>(T);
2263     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2264     Width = MPI.Width;
2265     Align = MPI.Align;
2266     break;
2267   }
2268   case Type::Complex: {
2269     // Complex types have the same alignment as their elements, but twice the
2270     // size.
2271     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2272     Width = EltInfo.Width * 2;
2273     Align = EltInfo.Align;
2274     break;
2275   }
2276   case Type::ObjCObject:
2277     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2278   case Type::Adjusted:
2279   case Type::Decayed:
2280     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2281   case Type::ObjCInterface: {
2282     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2283     if (ObjCI->getDecl()->isInvalidDecl()) {
2284       Width = 8;
2285       Align = 8;
2286       break;
2287     }
2288     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2289     Width = toBits(Layout.getSize());
2290     Align = toBits(Layout.getAlignment());
2291     break;
2292   }
2293   case Type::BitInt: {
2294     const auto *EIT = cast<BitIntType>(T);
2295     Align =
2296         std::min(static_cast<unsigned>(std::max(
2297                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2298                  Target->getLongLongAlign());
2299     Width = llvm::alignTo(EIT->getNumBits(), Align);
2300     break;
2301   }
2302   case Type::Record:
2303   case Type::Enum: {
2304     const auto *TT = cast<TagType>(T);
2305 
2306     if (TT->getDecl()->isInvalidDecl()) {
2307       Width = 8;
2308       Align = 8;
2309       break;
2310     }
2311 
2312     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2313       const EnumDecl *ED = ET->getDecl();
2314       TypeInfo Info =
2315           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2316       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2317         Info.Align = AttrAlign;
2318         Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2319       }
2320       return Info;
2321     }
2322 
2323     const auto *RT = cast<RecordType>(TT);
2324     const RecordDecl *RD = RT->getDecl();
2325     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2326     Width = toBits(Layout.getSize());
2327     Align = toBits(Layout.getAlignment());
2328     AlignRequirement = RD->hasAttr<AlignedAttr>()
2329                            ? AlignRequirementKind::RequiredByRecord
2330                            : AlignRequirementKind::None;
2331     break;
2332   }
2333 
2334   case Type::SubstTemplateTypeParm:
2335     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2336                        getReplacementType().getTypePtr());
2337 
2338   case Type::Auto:
2339   case Type::DeducedTemplateSpecialization: {
2340     const auto *A = cast<DeducedType>(T);
2341     assert(!A->getDeducedType().isNull() &&
2342            "cannot request the size of an undeduced or dependent auto type");
2343     return getTypeInfo(A->getDeducedType().getTypePtr());
2344   }
2345 
2346   case Type::Paren:
2347     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2348 
2349   case Type::MacroQualified:
2350     return getTypeInfo(
2351         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2352 
2353   case Type::ObjCTypeParam:
2354     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2355 
2356   case Type::Using:
2357     return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2358 
2359   case Type::Typedef: {
2360     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2361     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2362     // If the typedef has an aligned attribute on it, it overrides any computed
2363     // alignment we have.  This violates the GCC documentation (which says that
2364     // attribute(aligned) can only round up) but matches its implementation.
2365     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2366       Align = AttrAlign;
2367       AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2368     } else {
2369       Align = Info.Align;
2370       AlignRequirement = Info.AlignRequirement;
2371     }
2372     Width = Info.Width;
2373     break;
2374   }
2375 
2376   case Type::Elaborated:
2377     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2378 
2379   case Type::Attributed:
2380     return getTypeInfo(
2381                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2382 
2383   case Type::BTFTagAttributed:
2384     return getTypeInfo(
2385         cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2386 
2387   case Type::Atomic: {
2388     // Start with the base type information.
2389     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2390     Width = Info.Width;
2391     Align = Info.Align;
2392 
2393     if (!Width) {
2394       // An otherwise zero-sized type should still generate an
2395       // atomic operation.
2396       Width = Target->getCharWidth();
2397       assert(Align);
2398     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2399       // If the size of the type doesn't exceed the platform's max
2400       // atomic promotion width, make the size and alignment more
2401       // favorable to atomic operations:
2402 
2403       // Round the size up to a power of 2.
2404       if (!llvm::isPowerOf2_64(Width))
2405         Width = llvm::NextPowerOf2(Width);
2406 
2407       // Set the alignment equal to the size.
2408       Align = static_cast<unsigned>(Width);
2409     }
2410   }
2411   break;
2412 
2413   case Type::Pipe:
2414     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2415     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2416     break;
2417   }
2418 
2419   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2420   return TypeInfo(Width, Align, AlignRequirement);
2421 }
2422 
2423 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2424   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2425   if (I != MemoizedUnadjustedAlign.end())
2426     return I->second;
2427 
2428   unsigned UnadjustedAlign;
2429   if (const auto *RT = T->getAs<RecordType>()) {
2430     const RecordDecl *RD = RT->getDecl();
2431     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2432     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2433   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2434     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2435     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2436   } else {
2437     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2438   }
2439 
2440   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2441   return UnadjustedAlign;
2442 }
2443 
2444 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2445   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2446   return SimdAlign;
2447 }
2448 
2449 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2450 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2451   return CharUnits::fromQuantity(BitSize / getCharWidth());
2452 }
2453 
2454 /// toBits - Convert a size in characters to a size in characters.
2455 int64_t ASTContext::toBits(CharUnits CharSize) const {
2456   return CharSize.getQuantity() * getCharWidth();
2457 }
2458 
2459 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2460 /// This method does not work on incomplete types.
2461 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2462   return getTypeInfoInChars(T).Width;
2463 }
2464 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2465   return getTypeInfoInChars(T).Width;
2466 }
2467 
2468 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2469 /// characters. This method does not work on incomplete types.
2470 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2471   return toCharUnitsFromBits(getTypeAlign(T));
2472 }
2473 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2474   return toCharUnitsFromBits(getTypeAlign(T));
2475 }
2476 
2477 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2478 /// type, in characters, before alignment adustments. This method does
2479 /// not work on incomplete types.
2480 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2481   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2482 }
2483 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2484   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2485 }
2486 
2487 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2488 /// type for the current target in bits.  This can be different than the ABI
2489 /// alignment in cases where it is beneficial for performance or backwards
2490 /// compatibility preserving to overalign a data type. (Note: despite the name,
2491 /// the preferred alignment is ABI-impacting, and not an optimization.)
2492 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2493   TypeInfo TI = getTypeInfo(T);
2494   unsigned ABIAlign = TI.Align;
2495 
2496   T = T->getBaseElementTypeUnsafe();
2497 
2498   // The preferred alignment of member pointers is that of a pointer.
2499   if (T->isMemberPointerType())
2500     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2501 
2502   if (!Target->allowsLargerPreferedTypeAlignment())
2503     return ABIAlign;
2504 
2505   if (const auto *RT = T->getAs<RecordType>()) {
2506     const RecordDecl *RD = RT->getDecl();
2507 
2508     // When used as part of a typedef, or together with a 'packed' attribute,
2509     // the 'aligned' attribute can be used to decrease alignment. Note that the
2510     // 'packed' case is already taken into consideration when computing the
2511     // alignment, we only need to handle the typedef case here.
2512     if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2513         RD->isInvalidDecl())
2514       return ABIAlign;
2515 
2516     unsigned PreferredAlign = static_cast<unsigned>(
2517         toBits(getASTRecordLayout(RD).PreferredAlignment));
2518     assert(PreferredAlign >= ABIAlign &&
2519            "PreferredAlign should be at least as large as ABIAlign.");
2520     return PreferredAlign;
2521   }
2522 
2523   // Double (and, for targets supporting AIX `power` alignment, long double) and
2524   // long long should be naturally aligned (despite requiring less alignment) if
2525   // possible.
2526   if (const auto *CT = T->getAs<ComplexType>())
2527     T = CT->getElementType().getTypePtr();
2528   if (const auto *ET = T->getAs<EnumType>())
2529     T = ET->getDecl()->getIntegerType().getTypePtr();
2530   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2531       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2532       T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2533       (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2534        Target->defaultsToAIXPowerAlignment()))
2535     // Don't increase the alignment if an alignment attribute was specified on a
2536     // typedef declaration.
2537     if (!TI.isAlignRequired())
2538       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2539 
2540   return ABIAlign;
2541 }
2542 
2543 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2544 /// for __attribute__((aligned)) on this target, to be used if no alignment
2545 /// value is specified.
2546 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2547   return getTargetInfo().getDefaultAlignForAttributeAligned();
2548 }
2549 
2550 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2551 /// to a global variable of the specified type.
2552 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2553   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2554   return std::max(getPreferredTypeAlign(T),
2555                   getTargetInfo().getMinGlobalAlign(TypeSize));
2556 }
2557 
2558 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2559 /// should be given to a global variable of the specified type.
2560 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2561   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2562 }
2563 
2564 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2565   CharUnits Offset = CharUnits::Zero();
2566   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2567   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2568     Offset += Layout->getBaseClassOffset(Base);
2569     Layout = &getASTRecordLayout(Base);
2570   }
2571   return Offset;
2572 }
2573 
2574 CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2575   const ValueDecl *MPD = MP.getMemberPointerDecl();
2576   CharUnits ThisAdjustment = CharUnits::Zero();
2577   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2578   bool DerivedMember = MP.isMemberPointerToDerivedMember();
2579   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2580   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2581     const CXXRecordDecl *Base = RD;
2582     const CXXRecordDecl *Derived = Path[I];
2583     if (DerivedMember)
2584       std::swap(Base, Derived);
2585     ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2586     RD = Path[I];
2587   }
2588   if (DerivedMember)
2589     ThisAdjustment = -ThisAdjustment;
2590   return ThisAdjustment;
2591 }
2592 
2593 /// DeepCollectObjCIvars -
2594 /// This routine first collects all declared, but not synthesized, ivars in
2595 /// super class and then collects all ivars, including those synthesized for
2596 /// current class. This routine is used for implementation of current class
2597 /// when all ivars, declared and synthesized are known.
2598 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2599                                       bool leafClass,
2600                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2601   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2602     DeepCollectObjCIvars(SuperClass, false, Ivars);
2603   if (!leafClass) {
2604     for (const auto *I : OI->ivars())
2605       Ivars.push_back(I);
2606   } else {
2607     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2608     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2609          Iv= Iv->getNextIvar())
2610       Ivars.push_back(Iv);
2611   }
2612 }
2613 
2614 /// CollectInheritedProtocols - Collect all protocols in current class and
2615 /// those inherited by it.
2616 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2617                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2618   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2619     // We can use protocol_iterator here instead of
2620     // all_referenced_protocol_iterator since we are walking all categories.
2621     for (auto *Proto : OI->all_referenced_protocols()) {
2622       CollectInheritedProtocols(Proto, Protocols);
2623     }
2624 
2625     // Categories of this Interface.
2626     for (const auto *Cat : OI->visible_categories())
2627       CollectInheritedProtocols(Cat, Protocols);
2628 
2629     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2630       while (SD) {
2631         CollectInheritedProtocols(SD, Protocols);
2632         SD = SD->getSuperClass();
2633       }
2634   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2635     for (auto *Proto : OC->protocols()) {
2636       CollectInheritedProtocols(Proto, Protocols);
2637     }
2638   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2639     // Insert the protocol.
2640     if (!Protocols.insert(
2641           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2642       return;
2643 
2644     for (auto *Proto : OP->protocols())
2645       CollectInheritedProtocols(Proto, Protocols);
2646   }
2647 }
2648 
2649 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2650                                                 const RecordDecl *RD) {
2651   assert(RD->isUnion() && "Must be union type");
2652   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2653 
2654   for (const auto *Field : RD->fields()) {
2655     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2656       return false;
2657     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2658     if (FieldSize != UnionSize)
2659       return false;
2660   }
2661   return !RD->field_empty();
2662 }
2663 
2664 static int64_t getSubobjectOffset(const FieldDecl *Field,
2665                                   const ASTContext &Context,
2666                                   const clang::ASTRecordLayout & /*Layout*/) {
2667   return Context.getFieldOffset(Field);
2668 }
2669 
2670 static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2671                                   const ASTContext &Context,
2672                                   const clang::ASTRecordLayout &Layout) {
2673   return Context.toBits(Layout.getBaseClassOffset(RD));
2674 }
2675 
2676 static llvm::Optional<int64_t>
2677 structHasUniqueObjectRepresentations(const ASTContext &Context,
2678                                      const RecordDecl *RD);
2679 
2680 static llvm::Optional<int64_t>
2681 getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
2682   if (Field->getType()->isRecordType()) {
2683     const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2684     if (!RD->isUnion())
2685       return structHasUniqueObjectRepresentations(Context, RD);
2686   }
2687   if (!Field->getType()->isReferenceType() &&
2688       !Context.hasUniqueObjectRepresentations(Field->getType()))
2689     return llvm::None;
2690 
2691   int64_t FieldSizeInBits =
2692       Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2693   if (Field->isBitField()) {
2694     int64_t BitfieldSize = Field->getBitWidthValue(Context);
2695     if (BitfieldSize > FieldSizeInBits)
2696       return llvm::None;
2697     FieldSizeInBits = BitfieldSize;
2698   }
2699   return FieldSizeInBits;
2700 }
2701 
2702 static llvm::Optional<int64_t>
2703 getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
2704   return structHasUniqueObjectRepresentations(Context, RD);
2705 }
2706 
2707 template <typename RangeT>
2708 static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2709     const RangeT &Subobjects, int64_t CurOffsetInBits,
2710     const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2711   for (const auto *Subobject : Subobjects) {
2712     llvm::Optional<int64_t> SizeInBits =
2713         getSubobjectSizeInBits(Subobject, Context);
2714     if (!SizeInBits)
2715       return llvm::None;
2716     if (*SizeInBits != 0) {
2717       int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718       if (Offset != CurOffsetInBits)
2719         return llvm::None;
2720       CurOffsetInBits += *SizeInBits;
2721     }
2722   }
2723   return CurOffsetInBits;
2724 }
2725 
2726 static llvm::Optional<int64_t>
2727 structHasUniqueObjectRepresentations(const ASTContext &Context,
2728                                      const RecordDecl *RD) {
2729   assert(!RD->isUnion() && "Must be struct/class type");
2730   const auto &Layout = Context.getASTRecordLayout(RD);
2731 
2732   int64_t CurOffsetInBits = 0;
2733   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2734     if (ClassDecl->isDynamicClass())
2735       return llvm::None;
2736 
2737     SmallVector<CXXRecordDecl *, 4> Bases;
2738     for (const auto &Base : ClassDecl->bases()) {
2739       // Empty types can be inherited from, and non-empty types can potentially
2740       // have tail padding, so just make sure there isn't an error.
2741       Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2742     }
2743 
2744     llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2745       return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2746     });
2747 
2748     llvm::Optional<int64_t> OffsetAfterBases =
2749         structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
2750                                                         Context, Layout);
2751     if (!OffsetAfterBases)
2752       return llvm::None;
2753     CurOffsetInBits = *OffsetAfterBases;
2754   }
2755 
2756   llvm::Optional<int64_t> OffsetAfterFields =
2757       structSubobjectsHaveUniqueObjectRepresentations(
2758           RD->fields(), CurOffsetInBits, Context, Layout);
2759   if (!OffsetAfterFields)
2760     return llvm::None;
2761   CurOffsetInBits = *OffsetAfterFields;
2762 
2763   return CurOffsetInBits;
2764 }
2765 
2766 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2767   // C++17 [meta.unary.prop]:
2768   //   The predicate condition for a template specialization
2769   //   has_unique_object_representations<T> shall be
2770   //   satisfied if and only if:
2771   //     (9.1) - T is trivially copyable, and
2772   //     (9.2) - any two objects of type T with the same value have the same
2773   //     object representation, where two objects
2774   //   of array or non-union class type are considered to have the same value
2775   //   if their respective sequences of
2776   //   direct subobjects have the same values, and two objects of union type
2777   //   are considered to have the same
2778   //   value if they have the same active member and the corresponding members
2779   //   have the same value.
2780   //   The set of scalar types for which this condition holds is
2781   //   implementation-defined. [ Note: If a type has padding
2782   //   bits, the condition does not hold; otherwise, the condition holds true
2783   //   for unsigned integral types. -- end note ]
2784   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2785 
2786   // Arrays are unique only if their element type is unique.
2787   if (Ty->isArrayType())
2788     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2789 
2790   // (9.1) - T is trivially copyable...
2791   if (!Ty.isTriviallyCopyableType(*this))
2792     return false;
2793 
2794   // All integrals and enums are unique.
2795   if (Ty->isIntegralOrEnumerationType())
2796     return true;
2797 
2798   // All other pointers are unique.
2799   if (Ty->isPointerType())
2800     return true;
2801 
2802   if (Ty->isMemberPointerType()) {
2803     const auto *MPT = Ty->getAs<MemberPointerType>();
2804     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2805   }
2806 
2807   if (Ty->isRecordType()) {
2808     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2809 
2810     if (Record->isInvalidDecl())
2811       return false;
2812 
2813     if (Record->isUnion())
2814       return unionHasUniqueObjectRepresentations(*this, Record);
2815 
2816     Optional<int64_t> StructSize =
2817         structHasUniqueObjectRepresentations(*this, Record);
2818 
2819     return StructSize &&
2820            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2821   }
2822 
2823   // FIXME: More cases to handle here (list by rsmith):
2824   // vectors (careful about, eg, vector of 3 foo)
2825   // _Complex int and friends
2826   // _Atomic T
2827   // Obj-C block pointers
2828   // Obj-C object pointers
2829   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2830   // clk_event_t, queue_t, reserve_id_t)
2831   // There're also Obj-C class types and the Obj-C selector type, but I think it
2832   // makes sense for those to return false here.
2833 
2834   return false;
2835 }
2836 
2837 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2838   unsigned count = 0;
2839   // Count ivars declared in class extension.
2840   for (const auto *Ext : OI->known_extensions())
2841     count += Ext->ivar_size();
2842 
2843   // Count ivar defined in this class's implementation.  This
2844   // includes synthesized ivars.
2845   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2846     count += ImplDecl->ivar_size();
2847 
2848   return count;
2849 }
2850 
2851 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2852   if (!E)
2853     return false;
2854 
2855   // nullptr_t is always treated as null.
2856   if (E->getType()->isNullPtrType()) return true;
2857 
2858   if (E->getType()->isAnyPointerType() &&
2859       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2860                                                 Expr::NPC_ValueDependentIsNull))
2861     return true;
2862 
2863   // Unfortunately, __null has type 'int'.
2864   if (isa<GNUNullExpr>(E)) return true;
2865 
2866   return false;
2867 }
2868 
2869 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2870 /// exists.
2871 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2872   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2873     I = ObjCImpls.find(D);
2874   if (I != ObjCImpls.end())
2875     return cast<ObjCImplementationDecl>(I->second);
2876   return nullptr;
2877 }
2878 
2879 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2880 /// exists.
2881 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2882   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2883     I = ObjCImpls.find(D);
2884   if (I != ObjCImpls.end())
2885     return cast<ObjCCategoryImplDecl>(I->second);
2886   return nullptr;
2887 }
2888 
2889 /// Set the implementation of ObjCInterfaceDecl.
2890 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2891                            ObjCImplementationDecl *ImplD) {
2892   assert(IFaceD && ImplD && "Passed null params");
2893   ObjCImpls[IFaceD] = ImplD;
2894 }
2895 
2896 /// Set the implementation of ObjCCategoryDecl.
2897 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2898                            ObjCCategoryImplDecl *ImplD) {
2899   assert(CatD && ImplD && "Passed null params");
2900   ObjCImpls[CatD] = ImplD;
2901 }
2902 
2903 const ObjCMethodDecl *
2904 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2905   return ObjCMethodRedecls.lookup(MD);
2906 }
2907 
2908 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2909                                             const ObjCMethodDecl *Redecl) {
2910   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2911   ObjCMethodRedecls[MD] = Redecl;
2912 }
2913 
2914 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2915                                               const NamedDecl *ND) const {
2916   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2917     return ID;
2918   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2919     return CD->getClassInterface();
2920   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2921     return IMD->getClassInterface();
2922 
2923   return nullptr;
2924 }
2925 
2926 /// Get the copy initialization expression of VarDecl, or nullptr if
2927 /// none exists.
2928 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2929   assert(VD && "Passed null params");
2930   assert(VD->hasAttr<BlocksAttr>() &&
2931          "getBlockVarCopyInits - not __block var");
2932   auto I = BlockVarCopyInits.find(VD);
2933   if (I != BlockVarCopyInits.end())
2934     return I->second;
2935   return {nullptr, false};
2936 }
2937 
2938 /// Set the copy initialization expression of a block var decl.
2939 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2940                                      bool CanThrow) {
2941   assert(VD && CopyExpr && "Passed null params");
2942   assert(VD->hasAttr<BlocksAttr>() &&
2943          "setBlockVarCopyInits - not __block var");
2944   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2945 }
2946 
2947 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2948                                                  unsigned DataSize) const {
2949   if (!DataSize)
2950     DataSize = TypeLoc::getFullDataSizeForType(T);
2951   else
2952     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2953            "incorrect data size provided to CreateTypeSourceInfo!");
2954 
2955   auto *TInfo =
2956     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2957   new (TInfo) TypeSourceInfo(T);
2958   return TInfo;
2959 }
2960 
2961 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2962                                                      SourceLocation L) const {
2963   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2964   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2965   return DI;
2966 }
2967 
2968 const ASTRecordLayout &
2969 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2970   return getObjCLayout(D, nullptr);
2971 }
2972 
2973 const ASTRecordLayout &
2974 ASTContext::getASTObjCImplementationLayout(
2975                                         const ObjCImplementationDecl *D) const {
2976   return getObjCLayout(D->getClassInterface(), D);
2977 }
2978 
2979 //===----------------------------------------------------------------------===//
2980 //                   Type creation/memoization methods
2981 //===----------------------------------------------------------------------===//
2982 
2983 QualType
2984 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2985   unsigned fastQuals = quals.getFastQualifiers();
2986   quals.removeFastQualifiers();
2987 
2988   // Check if we've already instantiated this type.
2989   llvm::FoldingSetNodeID ID;
2990   ExtQuals::Profile(ID, baseType, quals);
2991   void *insertPos = nullptr;
2992   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2993     assert(eq->getQualifiers() == quals);
2994     return QualType(eq, fastQuals);
2995   }
2996 
2997   // If the base type is not canonical, make the appropriate canonical type.
2998   QualType canon;
2999   if (!baseType->isCanonicalUnqualified()) {
3000     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3001     canonSplit.Quals.addConsistentQualifiers(quals);
3002     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3003 
3004     // Re-find the insert position.
3005     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3006   }
3007 
3008   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
3009   ExtQualNodes.InsertNode(eq, insertPos);
3010   return QualType(eq, fastQuals);
3011 }
3012 
3013 QualType ASTContext::getAddrSpaceQualType(QualType T,
3014                                           LangAS AddressSpace) const {
3015   QualType CanT = getCanonicalType(T);
3016   if (CanT.getAddressSpace() == AddressSpace)
3017     return T;
3018 
3019   // If we are composing extended qualifiers together, merge together
3020   // into one ExtQuals node.
3021   QualifierCollector Quals;
3022   const Type *TypeNode = Quals.strip(T);
3023 
3024   // If this type already has an address space specified, it cannot get
3025   // another one.
3026   assert(!Quals.hasAddressSpace() &&
3027          "Type cannot be in multiple addr spaces!");
3028   Quals.addAddressSpace(AddressSpace);
3029 
3030   return getExtQualType(TypeNode, Quals);
3031 }
3032 
3033 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3034   // If the type is not qualified with an address space, just return it
3035   // immediately.
3036   if (!T.hasAddressSpace())
3037     return T;
3038 
3039   // If we are composing extended qualifiers together, merge together
3040   // into one ExtQuals node.
3041   QualifierCollector Quals;
3042   const Type *TypeNode;
3043 
3044   while (T.hasAddressSpace()) {
3045     TypeNode = Quals.strip(T);
3046 
3047     // If the type no longer has an address space after stripping qualifiers,
3048     // jump out.
3049     if (!QualType(TypeNode, 0).hasAddressSpace())
3050       break;
3051 
3052     // There might be sugar in the way. Strip it and try again.
3053     T = T.getSingleStepDesugaredType(*this);
3054   }
3055 
3056   Quals.removeAddressSpace();
3057 
3058   // Removal of the address space can mean there are no longer any
3059   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3060   // or required.
3061   if (Quals.hasNonFastQualifiers())
3062     return getExtQualType(TypeNode, Quals);
3063   else
3064     return QualType(TypeNode, Quals.getFastQualifiers());
3065 }
3066 
3067 QualType ASTContext::getObjCGCQualType(QualType T,
3068                                        Qualifiers::GC GCAttr) const {
3069   QualType CanT = getCanonicalType(T);
3070   if (CanT.getObjCGCAttr() == GCAttr)
3071     return T;
3072 
3073   if (const auto *ptr = T->getAs<PointerType>()) {
3074     QualType Pointee = ptr->getPointeeType();
3075     if (Pointee->isAnyPointerType()) {
3076       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3077       return getPointerType(ResultType);
3078     }
3079   }
3080 
3081   // If we are composing extended qualifiers together, merge together
3082   // into one ExtQuals node.
3083   QualifierCollector Quals;
3084   const Type *TypeNode = Quals.strip(T);
3085 
3086   // If this type already has an ObjCGC specified, it cannot get
3087   // another one.
3088   assert(!Quals.hasObjCGCAttr() &&
3089          "Type cannot have multiple ObjCGCs!");
3090   Quals.addObjCGCAttr(GCAttr);
3091 
3092   return getExtQualType(TypeNode, Quals);
3093 }
3094 
3095 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3096   if (const PointerType *Ptr = T->getAs<PointerType>()) {
3097     QualType Pointee = Ptr->getPointeeType();
3098     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3099       return getPointerType(removeAddrSpaceQualType(Pointee));
3100     }
3101   }
3102   return T;
3103 }
3104 
3105 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3106                                                    FunctionType::ExtInfo Info) {
3107   if (T->getExtInfo() == Info)
3108     return T;
3109 
3110   QualType Result;
3111   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3112     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3113   } else {
3114     const auto *FPT = cast<FunctionProtoType>(T);
3115     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3116     EPI.ExtInfo = Info;
3117     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3118   }
3119 
3120   return cast<FunctionType>(Result.getTypePtr());
3121 }
3122 
3123 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3124                                                  QualType ResultType) {
3125   FD = FD->getMostRecentDecl();
3126   while (true) {
3127     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3128     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3129     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3130     if (FunctionDecl *Next = FD->getPreviousDecl())
3131       FD = Next;
3132     else
3133       break;
3134   }
3135   if (ASTMutationListener *L = getASTMutationListener())
3136     L->DeducedReturnType(FD, ResultType);
3137 }
3138 
3139 /// Get a function type and produce the equivalent function type with the
3140 /// specified exception specification. Type sugar that can be present on a
3141 /// declaration of a function with an exception specification is permitted
3142 /// and preserved. Other type sugar (for instance, typedefs) is not.
3143 QualType ASTContext::getFunctionTypeWithExceptionSpec(
3144     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3145   // Might have some parens.
3146   if (const auto *PT = dyn_cast<ParenType>(Orig))
3147     return getParenType(
3148         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3149 
3150   // Might be wrapped in a macro qualified type.
3151   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3152     return getMacroQualifiedType(
3153         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3154         MQT->getMacroIdentifier());
3155 
3156   // Might have a calling-convention attribute.
3157   if (const auto *AT = dyn_cast<AttributedType>(Orig))
3158     return getAttributedType(
3159         AT->getAttrKind(),
3160         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3161         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3162 
3163   // Anything else must be a function type. Rebuild it with the new exception
3164   // specification.
3165   const auto *Proto = Orig->castAs<FunctionProtoType>();
3166   return getFunctionType(
3167       Proto->getReturnType(), Proto->getParamTypes(),
3168       Proto->getExtProtoInfo().withExceptionSpec(ESI));
3169 }
3170 
3171 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3172                                                           QualType U) {
3173   return hasSameType(T, U) ||
3174          (getLangOpts().CPlusPlus17 &&
3175           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3176                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3177 }
3178 
3179 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3180   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3181     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3182     SmallVector<QualType, 16> Args(Proto->param_types());
3183     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3184       Args[i] = removePtrSizeAddrSpace(Args[i]);
3185     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3186   }
3187 
3188   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3189     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3190     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3191   }
3192 
3193   return T;
3194 }
3195 
3196 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3197   return hasSameType(T, U) ||
3198          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3199                      getFunctionTypeWithoutPtrSizes(U));
3200 }
3201 
3202 void ASTContext::adjustExceptionSpec(
3203     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3204     bool AsWritten) {
3205   // Update the type.
3206   QualType Updated =
3207       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3208   FD->setType(Updated);
3209 
3210   if (!AsWritten)
3211     return;
3212 
3213   // Update the type in the type source information too.
3214   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3215     // If the type and the type-as-written differ, we may need to update
3216     // the type-as-written too.
3217     if (TSInfo->getType() != FD->getType())
3218       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3219 
3220     // FIXME: When we get proper type location information for exceptions,
3221     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3222     // up the TypeSourceInfo;
3223     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3224                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3225            "TypeLoc size mismatch from updating exception specification");
3226     TSInfo->overrideType(Updated);
3227   }
3228 }
3229 
3230 /// getComplexType - Return the uniqued reference to the type for a complex
3231 /// number with the specified element type.
3232 QualType ASTContext::getComplexType(QualType T) const {
3233   // Unique pointers, to guarantee there is only one pointer of a particular
3234   // structure.
3235   llvm::FoldingSetNodeID ID;
3236   ComplexType::Profile(ID, T);
3237 
3238   void *InsertPos = nullptr;
3239   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3240     return QualType(CT, 0);
3241 
3242   // If the pointee type isn't canonical, this won't be a canonical type either,
3243   // so fill in the canonical type field.
3244   QualType Canonical;
3245   if (!T.isCanonical()) {
3246     Canonical = getComplexType(getCanonicalType(T));
3247 
3248     // Get the new insert position for the node we care about.
3249     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3250     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3251   }
3252   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3253   Types.push_back(New);
3254   ComplexTypes.InsertNode(New, InsertPos);
3255   return QualType(New, 0);
3256 }
3257 
3258 /// getPointerType - Return the uniqued reference to the type for a pointer to
3259 /// the specified type.
3260 QualType ASTContext::getPointerType(QualType T) const {
3261   // Unique pointers, to guarantee there is only one pointer of a particular
3262   // structure.
3263   llvm::FoldingSetNodeID ID;
3264   PointerType::Profile(ID, T);
3265 
3266   void *InsertPos = nullptr;
3267   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3268     return QualType(PT, 0);
3269 
3270   // If the pointee type isn't canonical, this won't be a canonical type either,
3271   // so fill in the canonical type field.
3272   QualType Canonical;
3273   if (!T.isCanonical()) {
3274     Canonical = getPointerType(getCanonicalType(T));
3275 
3276     // Get the new insert position for the node we care about.
3277     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3278     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3279   }
3280   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3281   Types.push_back(New);
3282   PointerTypes.InsertNode(New, InsertPos);
3283   return QualType(New, 0);
3284 }
3285 
3286 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3287   llvm::FoldingSetNodeID ID;
3288   AdjustedType::Profile(ID, Orig, New);
3289   void *InsertPos = nullptr;
3290   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3291   if (AT)
3292     return QualType(AT, 0);
3293 
3294   QualType Canonical = getCanonicalType(New);
3295 
3296   // Get the new insert position for the node we care about.
3297   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3298   assert(!AT && "Shouldn't be in the map!");
3299 
3300   AT = new (*this, TypeAlignment)
3301       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3302   Types.push_back(AT);
3303   AdjustedTypes.InsertNode(AT, InsertPos);
3304   return QualType(AT, 0);
3305 }
3306 
3307 QualType ASTContext::getDecayedType(QualType T) const {
3308   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3309 
3310   QualType Decayed;
3311 
3312   // C99 6.7.5.3p7:
3313   //   A declaration of a parameter as "array of type" shall be
3314   //   adjusted to "qualified pointer to type", where the type
3315   //   qualifiers (if any) are those specified within the [ and ] of
3316   //   the array type derivation.
3317   if (T->isArrayType())
3318     Decayed = getArrayDecayedType(T);
3319 
3320   // C99 6.7.5.3p8:
3321   //   A declaration of a parameter as "function returning type"
3322   //   shall be adjusted to "pointer to function returning type", as
3323   //   in 6.3.2.1.
3324   if (T->isFunctionType())
3325     Decayed = getPointerType(T);
3326 
3327   llvm::FoldingSetNodeID ID;
3328   AdjustedType::Profile(ID, T, Decayed);
3329   void *InsertPos = nullptr;
3330   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3331   if (AT)
3332     return QualType(AT, 0);
3333 
3334   QualType Canonical = getCanonicalType(Decayed);
3335 
3336   // Get the new insert position for the node we care about.
3337   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3338   assert(!AT && "Shouldn't be in the map!");
3339 
3340   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3341   Types.push_back(AT);
3342   AdjustedTypes.InsertNode(AT, InsertPos);
3343   return QualType(AT, 0);
3344 }
3345 
3346 /// getBlockPointerType - Return the uniqued reference to the type for
3347 /// a pointer to the specified block.
3348 QualType ASTContext::getBlockPointerType(QualType T) const {
3349   assert(T->isFunctionType() && "block of function types only");
3350   // Unique pointers, to guarantee there is only one block of a particular
3351   // structure.
3352   llvm::FoldingSetNodeID ID;
3353   BlockPointerType::Profile(ID, T);
3354 
3355   void *InsertPos = nullptr;
3356   if (BlockPointerType *PT =
3357         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3358     return QualType(PT, 0);
3359 
3360   // If the block pointee type isn't canonical, this won't be a canonical
3361   // type either so fill in the canonical type field.
3362   QualType Canonical;
3363   if (!T.isCanonical()) {
3364     Canonical = getBlockPointerType(getCanonicalType(T));
3365 
3366     // Get the new insert position for the node we care about.
3367     BlockPointerType *NewIP =
3368       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3369     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3370   }
3371   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3372   Types.push_back(New);
3373   BlockPointerTypes.InsertNode(New, InsertPos);
3374   return QualType(New, 0);
3375 }
3376 
3377 /// getLValueReferenceType - Return the uniqued reference to the type for an
3378 /// lvalue reference to the specified type.
3379 QualType
3380 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3381   assert((!T->isPlaceholderType() ||
3382           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3383          "Unresolved placeholder type");
3384 
3385   // Unique pointers, to guarantee there is only one pointer of a particular
3386   // structure.
3387   llvm::FoldingSetNodeID ID;
3388   ReferenceType::Profile(ID, T, SpelledAsLValue);
3389 
3390   void *InsertPos = nullptr;
3391   if (LValueReferenceType *RT =
3392         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3393     return QualType(RT, 0);
3394 
3395   const auto *InnerRef = T->getAs<ReferenceType>();
3396 
3397   // If the referencee type isn't canonical, this won't be a canonical type
3398   // either, so fill in the canonical type field.
3399   QualType Canonical;
3400   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3401     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3402     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3403 
3404     // Get the new insert position for the node we care about.
3405     LValueReferenceType *NewIP =
3406       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3407     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3408   }
3409 
3410   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3411                                                              SpelledAsLValue);
3412   Types.push_back(New);
3413   LValueReferenceTypes.InsertNode(New, InsertPos);
3414 
3415   return QualType(New, 0);
3416 }
3417 
3418 /// getRValueReferenceType - Return the uniqued reference to the type for an
3419 /// rvalue reference to the specified type.
3420 QualType ASTContext::getRValueReferenceType(QualType T) const {
3421   assert((!T->isPlaceholderType() ||
3422           T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3423          "Unresolved placeholder type");
3424 
3425   // Unique pointers, to guarantee there is only one pointer of a particular
3426   // structure.
3427   llvm::FoldingSetNodeID ID;
3428   ReferenceType::Profile(ID, T, false);
3429 
3430   void *InsertPos = nullptr;
3431   if (RValueReferenceType *RT =
3432         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3433     return QualType(RT, 0);
3434 
3435   const auto *InnerRef = T->getAs<ReferenceType>();
3436 
3437   // If the referencee type isn't canonical, this won't be a canonical type
3438   // either, so fill in the canonical type field.
3439   QualType Canonical;
3440   if (InnerRef || !T.isCanonical()) {
3441     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3442     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3443 
3444     // Get the new insert position for the node we care about.
3445     RValueReferenceType *NewIP =
3446       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3447     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3448   }
3449 
3450   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3451   Types.push_back(New);
3452   RValueReferenceTypes.InsertNode(New, InsertPos);
3453   return QualType(New, 0);
3454 }
3455 
3456 /// getMemberPointerType - Return the uniqued reference to the type for a
3457 /// member pointer to the specified type, in the specified class.
3458 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3459   // Unique pointers, to guarantee there is only one pointer of a particular
3460   // structure.
3461   llvm::FoldingSetNodeID ID;
3462   MemberPointerType::Profile(ID, T, Cls);
3463 
3464   void *InsertPos = nullptr;
3465   if (MemberPointerType *PT =
3466       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3467     return QualType(PT, 0);
3468 
3469   // If the pointee or class type isn't canonical, this won't be a canonical
3470   // type either, so fill in the canonical type field.
3471   QualType Canonical;
3472   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3473     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3474 
3475     // Get the new insert position for the node we care about.
3476     MemberPointerType *NewIP =
3477       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3478     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3479   }
3480   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3481   Types.push_back(New);
3482   MemberPointerTypes.InsertNode(New, InsertPos);
3483   return QualType(New, 0);
3484 }
3485 
3486 /// getConstantArrayType - Return the unique reference to the type for an
3487 /// array of the specified element type.
3488 QualType ASTContext::getConstantArrayType(QualType EltTy,
3489                                           const llvm::APInt &ArySizeIn,
3490                                           const Expr *SizeExpr,
3491                                           ArrayType::ArraySizeModifier ASM,
3492                                           unsigned IndexTypeQuals) const {
3493   assert((EltTy->isDependentType() ||
3494           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3495          "Constant array of VLAs is illegal!");
3496 
3497   // We only need the size as part of the type if it's instantiation-dependent.
3498   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3499     SizeExpr = nullptr;
3500 
3501   // Convert the array size into a canonical width matching the pointer size for
3502   // the target.
3503   llvm::APInt ArySize(ArySizeIn);
3504   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3505 
3506   llvm::FoldingSetNodeID ID;
3507   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3508                              IndexTypeQuals);
3509 
3510   void *InsertPos = nullptr;
3511   if (ConstantArrayType *ATP =
3512       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3513     return QualType(ATP, 0);
3514 
3515   // If the element type isn't canonical or has qualifiers, or the array bound
3516   // is instantiation-dependent, this won't be a canonical type either, so fill
3517   // in the canonical type field.
3518   QualType Canon;
3519   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3520     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3521     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3522                                  ASM, IndexTypeQuals);
3523     Canon = getQualifiedType(Canon, canonSplit.Quals);
3524 
3525     // Get the new insert position for the node we care about.
3526     ConstantArrayType *NewIP =
3527       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3528     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3529   }
3530 
3531   void *Mem = Allocate(
3532       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3533       TypeAlignment);
3534   auto *New = new (Mem)
3535     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3536   ConstantArrayTypes.InsertNode(New, InsertPos);
3537   Types.push_back(New);
3538   return QualType(New, 0);
3539 }
3540 
3541 /// getVariableArrayDecayedType - Turns the given type, which may be
3542 /// variably-modified, into the corresponding type with all the known
3543 /// sizes replaced with [*].
3544 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3545   // Vastly most common case.
3546   if (!type->isVariablyModifiedType()) return type;
3547 
3548   QualType result;
3549 
3550   SplitQualType split = type.getSplitDesugaredType();
3551   const Type *ty = split.Ty;
3552   switch (ty->getTypeClass()) {
3553 #define TYPE(Class, Base)
3554 #define ABSTRACT_TYPE(Class, Base)
3555 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3556 #include "clang/AST/TypeNodes.inc"
3557     llvm_unreachable("didn't desugar past all non-canonical types?");
3558 
3559   // These types should never be variably-modified.
3560   case Type::Builtin:
3561   case Type::Complex:
3562   case Type::Vector:
3563   case Type::DependentVector:
3564   case Type::ExtVector:
3565   case Type::DependentSizedExtVector:
3566   case Type::ConstantMatrix:
3567   case Type::DependentSizedMatrix:
3568   case Type::DependentAddressSpace:
3569   case Type::ObjCObject:
3570   case Type::ObjCInterface:
3571   case Type::ObjCObjectPointer:
3572   case Type::Record:
3573   case Type::Enum:
3574   case Type::UnresolvedUsing:
3575   case Type::TypeOfExpr:
3576   case Type::TypeOf:
3577   case Type::Decltype:
3578   case Type::UnaryTransform:
3579   case Type::DependentName:
3580   case Type::InjectedClassName:
3581   case Type::TemplateSpecialization:
3582   case Type::DependentTemplateSpecialization:
3583   case Type::TemplateTypeParm:
3584   case Type::SubstTemplateTypeParmPack:
3585   case Type::Auto:
3586   case Type::DeducedTemplateSpecialization:
3587   case Type::PackExpansion:
3588   case Type::BitInt:
3589   case Type::DependentBitInt:
3590     llvm_unreachable("type should never be variably-modified");
3591 
3592   // These types can be variably-modified but should never need to
3593   // further decay.
3594   case Type::FunctionNoProto:
3595   case Type::FunctionProto:
3596   case Type::BlockPointer:
3597   case Type::MemberPointer:
3598   case Type::Pipe:
3599     return type;
3600 
3601   // These types can be variably-modified.  All these modifications
3602   // preserve structure except as noted by comments.
3603   // TODO: if we ever care about optimizing VLAs, there are no-op
3604   // optimizations available here.
3605   case Type::Pointer:
3606     result = getPointerType(getVariableArrayDecayedType(
3607                               cast<PointerType>(ty)->getPointeeType()));
3608     break;
3609 
3610   case Type::LValueReference: {
3611     const auto *lv = cast<LValueReferenceType>(ty);
3612     result = getLValueReferenceType(
3613                  getVariableArrayDecayedType(lv->getPointeeType()),
3614                                     lv->isSpelledAsLValue());
3615     break;
3616   }
3617 
3618   case Type::RValueReference: {
3619     const auto *lv = cast<RValueReferenceType>(ty);
3620     result = getRValueReferenceType(
3621                  getVariableArrayDecayedType(lv->getPointeeType()));
3622     break;
3623   }
3624 
3625   case Type::Atomic: {
3626     const auto *at = cast<AtomicType>(ty);
3627     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3628     break;
3629   }
3630 
3631   case Type::ConstantArray: {
3632     const auto *cat = cast<ConstantArrayType>(ty);
3633     result = getConstantArrayType(
3634                  getVariableArrayDecayedType(cat->getElementType()),
3635                                   cat->getSize(),
3636                                   cat->getSizeExpr(),
3637                                   cat->getSizeModifier(),
3638                                   cat->getIndexTypeCVRQualifiers());
3639     break;
3640   }
3641 
3642   case Type::DependentSizedArray: {
3643     const auto *dat = cast<DependentSizedArrayType>(ty);
3644     result = getDependentSizedArrayType(
3645                  getVariableArrayDecayedType(dat->getElementType()),
3646                                         dat->getSizeExpr(),
3647                                         dat->getSizeModifier(),
3648                                         dat->getIndexTypeCVRQualifiers(),
3649                                         dat->getBracketsRange());
3650     break;
3651   }
3652 
3653   // Turn incomplete types into [*] types.
3654   case Type::IncompleteArray: {
3655     const auto *iat = cast<IncompleteArrayType>(ty);
3656     result = getVariableArrayType(
3657                  getVariableArrayDecayedType(iat->getElementType()),
3658                                   /*size*/ nullptr,
3659                                   ArrayType::Normal,
3660                                   iat->getIndexTypeCVRQualifiers(),
3661                                   SourceRange());
3662     break;
3663   }
3664 
3665   // Turn VLA types into [*] types.
3666   case Type::VariableArray: {
3667     const auto *vat = cast<VariableArrayType>(ty);
3668     result = getVariableArrayType(
3669                  getVariableArrayDecayedType(vat->getElementType()),
3670                                   /*size*/ nullptr,
3671                                   ArrayType::Star,
3672                                   vat->getIndexTypeCVRQualifiers(),
3673                                   vat->getBracketsRange());
3674     break;
3675   }
3676   }
3677 
3678   // Apply the top-level qualifiers from the original.
3679   return getQualifiedType(result, split.Quals);
3680 }
3681 
3682 /// getVariableArrayType - Returns a non-unique reference to the type for a
3683 /// variable array of the specified element type.
3684 QualType ASTContext::getVariableArrayType(QualType EltTy,
3685                                           Expr *NumElts,
3686                                           ArrayType::ArraySizeModifier ASM,
3687                                           unsigned IndexTypeQuals,
3688                                           SourceRange Brackets) const {
3689   // Since we don't unique expressions, it isn't possible to unique VLA's
3690   // that have an expression provided for their size.
3691   QualType Canon;
3692 
3693   // Be sure to pull qualifiers off the element type.
3694   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3695     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3696     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3697                                  IndexTypeQuals, Brackets);
3698     Canon = getQualifiedType(Canon, canonSplit.Quals);
3699   }
3700 
3701   auto *New = new (*this, TypeAlignment)
3702     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3703 
3704   VariableArrayTypes.push_back(New);
3705   Types.push_back(New);
3706   return QualType(New, 0);
3707 }
3708 
3709 /// getDependentSizedArrayType - Returns a non-unique reference to
3710 /// the type for a dependently-sized array of the specified element
3711 /// type.
3712 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3713                                                 Expr *numElements,
3714                                                 ArrayType::ArraySizeModifier ASM,
3715                                                 unsigned elementTypeQuals,
3716                                                 SourceRange brackets) const {
3717   assert((!numElements || numElements->isTypeDependent() ||
3718           numElements->isValueDependent()) &&
3719          "Size must be type- or value-dependent!");
3720 
3721   // Dependently-sized array types that do not have a specified number
3722   // of elements will have their sizes deduced from a dependent
3723   // initializer.  We do no canonicalization here at all, which is okay
3724   // because they can't be used in most locations.
3725   if (!numElements) {
3726     auto *newType
3727       = new (*this, TypeAlignment)
3728           DependentSizedArrayType(*this, elementType, QualType(),
3729                                   numElements, ASM, elementTypeQuals,
3730                                   brackets);
3731     Types.push_back(newType);
3732     return QualType(newType, 0);
3733   }
3734 
3735   // Otherwise, we actually build a new type every time, but we
3736   // also build a canonical type.
3737 
3738   SplitQualType canonElementType = getCanonicalType(elementType).split();
3739 
3740   void *insertPos = nullptr;
3741   llvm::FoldingSetNodeID ID;
3742   DependentSizedArrayType::Profile(ID, *this,
3743                                    QualType(canonElementType.Ty, 0),
3744                                    ASM, elementTypeQuals, numElements);
3745 
3746   // Look for an existing type with these properties.
3747   DependentSizedArrayType *canonTy =
3748     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3749 
3750   // If we don't have one, build one.
3751   if (!canonTy) {
3752     canonTy = new (*this, TypeAlignment)
3753       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3754                               QualType(), numElements, ASM, elementTypeQuals,
3755                               brackets);
3756     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3757     Types.push_back(canonTy);
3758   }
3759 
3760   // Apply qualifiers from the element type to the array.
3761   QualType canon = getQualifiedType(QualType(canonTy,0),
3762                                     canonElementType.Quals);
3763 
3764   // If we didn't need extra canonicalization for the element type or the size
3765   // expression, then just use that as our result.
3766   if (QualType(canonElementType.Ty, 0) == elementType &&
3767       canonTy->getSizeExpr() == numElements)
3768     return canon;
3769 
3770   // Otherwise, we need to build a type which follows the spelling
3771   // of the element type.
3772   auto *sugaredType
3773     = new (*this, TypeAlignment)
3774         DependentSizedArrayType(*this, elementType, canon, numElements,
3775                                 ASM, elementTypeQuals, brackets);
3776   Types.push_back(sugaredType);
3777   return QualType(sugaredType, 0);
3778 }
3779 
3780 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3781                                             ArrayType::ArraySizeModifier ASM,
3782                                             unsigned elementTypeQuals) const {
3783   llvm::FoldingSetNodeID ID;
3784   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3785 
3786   void *insertPos = nullptr;
3787   if (IncompleteArrayType *iat =
3788        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3789     return QualType(iat, 0);
3790 
3791   // If the element type isn't canonical, this won't be a canonical type
3792   // either, so fill in the canonical type field.  We also have to pull
3793   // qualifiers off the element type.
3794   QualType canon;
3795 
3796   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3797     SplitQualType canonSplit = getCanonicalType(elementType).split();
3798     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3799                                    ASM, elementTypeQuals);
3800     canon = getQualifiedType(canon, canonSplit.Quals);
3801 
3802     // Get the new insert position for the node we care about.
3803     IncompleteArrayType *existing =
3804       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3805     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3806   }
3807 
3808   auto *newType = new (*this, TypeAlignment)
3809     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3810 
3811   IncompleteArrayTypes.InsertNode(newType, insertPos);
3812   Types.push_back(newType);
3813   return QualType(newType, 0);
3814 }
3815 
3816 ASTContext::BuiltinVectorTypeInfo
3817 ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3818 #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3819   {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3820    NUMVECTORS};
3821 
3822 #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3823   {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3824 
3825   switch (Ty->getKind()) {
3826   default:
3827     llvm_unreachable("Unsupported builtin vector type");
3828   case BuiltinType::SveInt8:
3829     return SVE_INT_ELTTY(8, 16, true, 1);
3830   case BuiltinType::SveUint8:
3831     return SVE_INT_ELTTY(8, 16, false, 1);
3832   case BuiltinType::SveInt8x2:
3833     return SVE_INT_ELTTY(8, 16, true, 2);
3834   case BuiltinType::SveUint8x2:
3835     return SVE_INT_ELTTY(8, 16, false, 2);
3836   case BuiltinType::SveInt8x3:
3837     return SVE_INT_ELTTY(8, 16, true, 3);
3838   case BuiltinType::SveUint8x3:
3839     return SVE_INT_ELTTY(8, 16, false, 3);
3840   case BuiltinType::SveInt8x4:
3841     return SVE_INT_ELTTY(8, 16, true, 4);
3842   case BuiltinType::SveUint8x4:
3843     return SVE_INT_ELTTY(8, 16, false, 4);
3844   case BuiltinType::SveInt16:
3845     return SVE_INT_ELTTY(16, 8, true, 1);
3846   case BuiltinType::SveUint16:
3847     return SVE_INT_ELTTY(16, 8, false, 1);
3848   case BuiltinType::SveInt16x2:
3849     return SVE_INT_ELTTY(16, 8, true, 2);
3850   case BuiltinType::SveUint16x2:
3851     return SVE_INT_ELTTY(16, 8, false, 2);
3852   case BuiltinType::SveInt16x3:
3853     return SVE_INT_ELTTY(16, 8, true, 3);
3854   case BuiltinType::SveUint16x3:
3855     return SVE_INT_ELTTY(16, 8, false, 3);
3856   case BuiltinType::SveInt16x4:
3857     return SVE_INT_ELTTY(16, 8, true, 4);
3858   case BuiltinType::SveUint16x4:
3859     return SVE_INT_ELTTY(16, 8, false, 4);
3860   case BuiltinType::SveInt32:
3861     return SVE_INT_ELTTY(32, 4, true, 1);
3862   case BuiltinType::SveUint32:
3863     return SVE_INT_ELTTY(32, 4, false, 1);
3864   case BuiltinType::SveInt32x2:
3865     return SVE_INT_ELTTY(32, 4, true, 2);
3866   case BuiltinType::SveUint32x2:
3867     return SVE_INT_ELTTY(32, 4, false, 2);
3868   case BuiltinType::SveInt32x3:
3869     return SVE_INT_ELTTY(32, 4, true, 3);
3870   case BuiltinType::SveUint32x3:
3871     return SVE_INT_ELTTY(32, 4, false, 3);
3872   case BuiltinType::SveInt32x4:
3873     return SVE_INT_ELTTY(32, 4, true, 4);
3874   case BuiltinType::SveUint32x4:
3875     return SVE_INT_ELTTY(32, 4, false, 4);
3876   case BuiltinType::SveInt64:
3877     return SVE_INT_ELTTY(64, 2, true, 1);
3878   case BuiltinType::SveUint64:
3879     return SVE_INT_ELTTY(64, 2, false, 1);
3880   case BuiltinType::SveInt64x2:
3881     return SVE_INT_ELTTY(64, 2, true, 2);
3882   case BuiltinType::SveUint64x2:
3883     return SVE_INT_ELTTY(64, 2, false, 2);
3884   case BuiltinType::SveInt64x3:
3885     return SVE_INT_ELTTY(64, 2, true, 3);
3886   case BuiltinType::SveUint64x3:
3887     return SVE_INT_ELTTY(64, 2, false, 3);
3888   case BuiltinType::SveInt64x4:
3889     return SVE_INT_ELTTY(64, 2, true, 4);
3890   case BuiltinType::SveUint64x4:
3891     return SVE_INT_ELTTY(64, 2, false, 4);
3892   case BuiltinType::SveBool:
3893     return SVE_ELTTY(BoolTy, 16, 1);
3894   case BuiltinType::SveFloat16:
3895     return SVE_ELTTY(HalfTy, 8, 1);
3896   case BuiltinType::SveFloat16x2:
3897     return SVE_ELTTY(HalfTy, 8, 2);
3898   case BuiltinType::SveFloat16x3:
3899     return SVE_ELTTY(HalfTy, 8, 3);
3900   case BuiltinType::SveFloat16x4:
3901     return SVE_ELTTY(HalfTy, 8, 4);
3902   case BuiltinType::SveFloat32:
3903     return SVE_ELTTY(FloatTy, 4, 1);
3904   case BuiltinType::SveFloat32x2:
3905     return SVE_ELTTY(FloatTy, 4, 2);
3906   case BuiltinType::SveFloat32x3:
3907     return SVE_ELTTY(FloatTy, 4, 3);
3908   case BuiltinType::SveFloat32x4:
3909     return SVE_ELTTY(FloatTy, 4, 4);
3910   case BuiltinType::SveFloat64:
3911     return SVE_ELTTY(DoubleTy, 2, 1);
3912   case BuiltinType::SveFloat64x2:
3913     return SVE_ELTTY(DoubleTy, 2, 2);
3914   case BuiltinType::SveFloat64x3:
3915     return SVE_ELTTY(DoubleTy, 2, 3);
3916   case BuiltinType::SveFloat64x4:
3917     return SVE_ELTTY(DoubleTy, 2, 4);
3918   case BuiltinType::SveBFloat16:
3919     return SVE_ELTTY(BFloat16Ty, 8, 1);
3920   case BuiltinType::SveBFloat16x2:
3921     return SVE_ELTTY(BFloat16Ty, 8, 2);
3922   case BuiltinType::SveBFloat16x3:
3923     return SVE_ELTTY(BFloat16Ty, 8, 3);
3924   case BuiltinType::SveBFloat16x4:
3925     return SVE_ELTTY(BFloat16Ty, 8, 4);
3926 #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3927                             IsSigned)                                          \
3928   case BuiltinType::Id:                                                        \
3929     return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3930             llvm::ElementCount::getScalable(NumEls), NF};
3931 #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3932   case BuiltinType::Id:                                                        \
3933     return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy),    \
3934             llvm::ElementCount::getScalable(NumEls), NF};
3935 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3936   case BuiltinType::Id:                                                        \
3937     return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3938 #include "clang/Basic/RISCVVTypes.def"
3939   }
3940 }
3941 
3942 /// getScalableVectorType - Return the unique reference to a scalable vector
3943 /// type of the specified element type and size. VectorType must be a built-in
3944 /// type.
3945 QualType ASTContext::getScalableVectorType(QualType EltTy,
3946                                            unsigned NumElts) const {
3947   if (Target->hasAArch64SVETypes()) {
3948     uint64_t EltTySize = getTypeSize(EltTy);
3949 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3950                         IsSigned, IsFP, IsBF)                                  \
3951   if (!EltTy->isBooleanType() &&                                               \
3952       ((EltTy->hasIntegerRepresentation() &&                                   \
3953         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3954        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3955         IsFP && !IsBF) ||                                                      \
3956        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3957         IsBF && !IsFP)) &&                                                     \
3958       EltTySize == ElBits && NumElts == NumEls) {                              \
3959     return SingletonId;                                                        \
3960   }
3961 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3962   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3963     return SingletonId;
3964 #include "clang/Basic/AArch64SVEACLETypes.def"
3965   } else if (Target->hasRISCVVTypes()) {
3966     uint64_t EltTySize = getTypeSize(EltTy);
3967 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3968                         IsFP)                                                  \
3969     if (!EltTy->isBooleanType() &&                                             \
3970         ((EltTy->hasIntegerRepresentation() &&                                 \
3971           EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3972          (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3973         EltTySize == ElBits && NumElts == NumEls)                              \
3974       return SingletonId;
3975 #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3976     if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3977       return SingletonId;
3978 #include "clang/Basic/RISCVVTypes.def"
3979   }
3980   return QualType();
3981 }
3982 
3983 /// getVectorType - Return the unique reference to a vector type of
3984 /// the specified element type and size. VectorType must be a built-in type.
3985 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3986                                    VectorType::VectorKind VecKind) const {
3987   assert(vecType->isBuiltinType());
3988 
3989   // Check if we've already instantiated a vector of this type.
3990   llvm::FoldingSetNodeID ID;
3991   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3992 
3993   void *InsertPos = nullptr;
3994   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3995     return QualType(VTP, 0);
3996 
3997   // If the element type isn't canonical, this won't be a canonical type either,
3998   // so fill in the canonical type field.
3999   QualType Canonical;
4000   if (!vecType.isCanonical()) {
4001     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4002 
4003     // Get the new insert position for the node we care about.
4004     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4005     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4006   }
4007   auto *New = new (*this, TypeAlignment)
4008     VectorType(vecType, NumElts, Canonical, VecKind);
4009   VectorTypes.InsertNode(New, InsertPos);
4010   Types.push_back(New);
4011   return QualType(New, 0);
4012 }
4013 
4014 QualType
4015 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4016                                    SourceLocation AttrLoc,
4017                                    VectorType::VectorKind VecKind) const {
4018   llvm::FoldingSetNodeID ID;
4019   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4020                                VecKind);
4021   void *InsertPos = nullptr;
4022   DependentVectorType *Canon =
4023       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4024   DependentVectorType *New;
4025 
4026   if (Canon) {
4027     New = new (*this, TypeAlignment) DependentVectorType(
4028         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4029   } else {
4030     QualType CanonVecTy = getCanonicalType(VecType);
4031     if (CanonVecTy == VecType) {
4032       New = new (*this, TypeAlignment) DependentVectorType(
4033           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4034 
4035       DependentVectorType *CanonCheck =
4036           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4037       assert(!CanonCheck &&
4038              "Dependent-sized vector_size canonical type broken");
4039       (void)CanonCheck;
4040       DependentVectorTypes.InsertNode(New, InsertPos);
4041     } else {
4042       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4043                                                 SourceLocation(), VecKind);
4044       New = new (*this, TypeAlignment) DependentVectorType(
4045           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4046     }
4047   }
4048 
4049   Types.push_back(New);
4050   return QualType(New, 0);
4051 }
4052 
4053 /// getExtVectorType - Return the unique reference to an extended vector type of
4054 /// the specified element type and size. VectorType must be a built-in type.
4055 QualType
4056 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
4057   assert(vecType->isBuiltinType() || vecType->isDependentType());
4058 
4059   // Check if we've already instantiated a vector of this type.
4060   llvm::FoldingSetNodeID ID;
4061   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4062                       VectorType::GenericVector);
4063   void *InsertPos = nullptr;
4064   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4065     return QualType(VTP, 0);
4066 
4067   // If the element type isn't canonical, this won't be a canonical type either,
4068   // so fill in the canonical type field.
4069   QualType Canonical;
4070   if (!vecType.isCanonical()) {
4071     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4072 
4073     // Get the new insert position for the node we care about.
4074     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4075     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4076   }
4077   auto *New = new (*this, TypeAlignment)
4078     ExtVectorType(vecType, NumElts, Canonical);
4079   VectorTypes.InsertNode(New, InsertPos);
4080   Types.push_back(New);
4081   return QualType(New, 0);
4082 }
4083 
4084 QualType
4085 ASTContext::getDependentSizedExtVectorType(QualType vecType,
4086                                            Expr *SizeExpr,
4087                                            SourceLocation AttrLoc) const {
4088   llvm::FoldingSetNodeID ID;
4089   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4090                                        SizeExpr);
4091 
4092   void *InsertPos = nullptr;
4093   DependentSizedExtVectorType *Canon
4094     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4095   DependentSizedExtVectorType *New;
4096   if (Canon) {
4097     // We already have a canonical version of this array type; use it as
4098     // the canonical type for a newly-built type.
4099     New = new (*this, TypeAlignment)
4100       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4101                                   SizeExpr, AttrLoc);
4102   } else {
4103     QualType CanonVecTy = getCanonicalType(vecType);
4104     if (CanonVecTy == vecType) {
4105       New = new (*this, TypeAlignment)
4106         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4107                                     AttrLoc);
4108 
4109       DependentSizedExtVectorType *CanonCheck
4110         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4111       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4112       (void)CanonCheck;
4113       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4114     } else {
4115       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4116                                                            SourceLocation());
4117       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4118           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4119     }
4120   }
4121 
4122   Types.push_back(New);
4123   return QualType(New, 0);
4124 }
4125 
4126 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4127                                            unsigned NumColumns) const {
4128   llvm::FoldingSetNodeID ID;
4129   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4130                               Type::ConstantMatrix);
4131 
4132   assert(MatrixType::isValidElementType(ElementTy) &&
4133          "need a valid element type");
4134   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4135          ConstantMatrixType::isDimensionValid(NumColumns) &&
4136          "need valid matrix dimensions");
4137   void *InsertPos = nullptr;
4138   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4139     return QualType(MTP, 0);
4140 
4141   QualType Canonical;
4142   if (!ElementTy.isCanonical()) {
4143     Canonical =
4144         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4145 
4146     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4147     assert(!NewIP && "Matrix type shouldn't already exist in the map");
4148     (void)NewIP;
4149   }
4150 
4151   auto *New = new (*this, TypeAlignment)
4152       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4153   MatrixTypes.InsertNode(New, InsertPos);
4154   Types.push_back(New);
4155   return QualType(New, 0);
4156 }
4157 
4158 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4159                                                  Expr *RowExpr,
4160                                                  Expr *ColumnExpr,
4161                                                  SourceLocation AttrLoc) const {
4162   QualType CanonElementTy = getCanonicalType(ElementTy);
4163   llvm::FoldingSetNodeID ID;
4164   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4165                                     ColumnExpr);
4166 
4167   void *InsertPos = nullptr;
4168   DependentSizedMatrixType *Canon =
4169       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4170 
4171   if (!Canon) {
4172     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4173         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4174 #ifndef NDEBUG
4175     DependentSizedMatrixType *CanonCheck =
4176         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4177     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4178 #endif
4179     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4180     Types.push_back(Canon);
4181   }
4182 
4183   // Already have a canonical version of the matrix type
4184   //
4185   // If it exactly matches the requested type, use it directly.
4186   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4187       Canon->getRowExpr() == ColumnExpr)
4188     return QualType(Canon, 0);
4189 
4190   // Use Canon as the canonical type for newly-built type.
4191   DependentSizedMatrixType *New = new (*this, TypeAlignment)
4192       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4193                                ColumnExpr, AttrLoc);
4194   Types.push_back(New);
4195   return QualType(New, 0);
4196 }
4197 
4198 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4199                                                   Expr *AddrSpaceExpr,
4200                                                   SourceLocation AttrLoc) const {
4201   assert(AddrSpaceExpr->isInstantiationDependent());
4202 
4203   QualType canonPointeeType = getCanonicalType(PointeeType);
4204 
4205   void *insertPos = nullptr;
4206   llvm::FoldingSetNodeID ID;
4207   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4208                                      AddrSpaceExpr);
4209 
4210   DependentAddressSpaceType *canonTy =
4211     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4212 
4213   if (!canonTy) {
4214     canonTy = new (*this, TypeAlignment)
4215       DependentAddressSpaceType(*this, canonPointeeType,
4216                                 QualType(), AddrSpaceExpr, AttrLoc);
4217     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4218     Types.push_back(canonTy);
4219   }
4220 
4221   if (canonPointeeType == PointeeType &&
4222       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4223     return QualType(canonTy, 0);
4224 
4225   auto *sugaredType
4226     = new (*this, TypeAlignment)
4227         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4228                                   AddrSpaceExpr, AttrLoc);
4229   Types.push_back(sugaredType);
4230   return QualType(sugaredType, 0);
4231 }
4232 
4233 /// Determine whether \p T is canonical as the result type of a function.
4234 static bool isCanonicalResultType(QualType T) {
4235   return T.isCanonical() &&
4236          (T.getObjCLifetime() == Qualifiers::OCL_None ||
4237           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4238 }
4239 
4240 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4241 QualType
4242 ASTContext::getFunctionNoProtoType(QualType ResultTy,
4243                                    const FunctionType::ExtInfo &Info) const {
4244   // Unique functions, to guarantee there is only one function of a particular
4245   // structure.
4246   llvm::FoldingSetNodeID ID;
4247   FunctionNoProtoType::Profile(ID, ResultTy, Info);
4248 
4249   void *InsertPos = nullptr;
4250   if (FunctionNoProtoType *FT =
4251         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4252     return QualType(FT, 0);
4253 
4254   QualType Canonical;
4255   if (!isCanonicalResultType(ResultTy)) {
4256     Canonical =
4257       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4258 
4259     // Get the new insert position for the node we care about.
4260     FunctionNoProtoType *NewIP =
4261       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4262     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4263   }
4264 
4265   auto *New = new (*this, TypeAlignment)
4266     FunctionNoProtoType(ResultTy, Canonical, Info);
4267   Types.push_back(New);
4268   FunctionNoProtoTypes.InsertNode(New, InsertPos);
4269   return QualType(New, 0);
4270 }
4271 
4272 CanQualType
4273 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4274   CanQualType CanResultType = getCanonicalType(ResultType);
4275 
4276   // Canonical result types do not have ARC lifetime qualifiers.
4277   if (CanResultType.getQualifiers().hasObjCLifetime()) {
4278     Qualifiers Qs = CanResultType.getQualifiers();
4279     Qs.removeObjCLifetime();
4280     return CanQualType::CreateUnsafe(
4281              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4282   }
4283 
4284   return CanResultType;
4285 }
4286 
4287 static bool isCanonicalExceptionSpecification(
4288     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4289   if (ESI.Type == EST_None)
4290     return true;
4291   if (!NoexceptInType)
4292     return false;
4293 
4294   // C++17 onwards: exception specification is part of the type, as a simple
4295   // boolean "can this function type throw".
4296   if (ESI.Type == EST_BasicNoexcept)
4297     return true;
4298 
4299   // A noexcept(expr) specification is (possibly) canonical if expr is
4300   // value-dependent.
4301   if (ESI.Type == EST_DependentNoexcept)
4302     return true;
4303 
4304   // A dynamic exception specification is canonical if it only contains pack
4305   // expansions (so we can't tell whether it's non-throwing) and all its
4306   // contained types are canonical.
4307   if (ESI.Type == EST_Dynamic) {
4308     bool AnyPackExpansions = false;
4309     for (QualType ET : ESI.Exceptions) {
4310       if (!ET.isCanonical())
4311         return false;
4312       if (ET->getAs<PackExpansionType>())
4313         AnyPackExpansions = true;
4314     }
4315     return AnyPackExpansions;
4316   }
4317 
4318   return false;
4319 }
4320 
4321 QualType ASTContext::getFunctionTypeInternal(
4322     QualType ResultTy, ArrayRef<QualType> ArgArray,
4323     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4324   size_t NumArgs = ArgArray.size();
4325 
4326   // Unique functions, to guarantee there is only one function of a particular
4327   // structure.
4328   llvm::FoldingSetNodeID ID;
4329   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4330                              *this, true);
4331 
4332   QualType Canonical;
4333   bool Unique = false;
4334 
4335   void *InsertPos = nullptr;
4336   if (FunctionProtoType *FPT =
4337         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4338     QualType Existing = QualType(FPT, 0);
4339 
4340     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4341     // it so long as our exception specification doesn't contain a dependent
4342     // noexcept expression, or we're just looking for a canonical type.
4343     // Otherwise, we're going to need to create a type
4344     // sugar node to hold the concrete expression.
4345     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4346         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4347       return Existing;
4348 
4349     // We need a new type sugar node for this one, to hold the new noexcept
4350     // expression. We do no canonicalization here, but that's OK since we don't
4351     // expect to see the same noexcept expression much more than once.
4352     Canonical = getCanonicalType(Existing);
4353     Unique = true;
4354   }
4355 
4356   bool NoexceptInType = getLangOpts().CPlusPlus17;
4357   bool IsCanonicalExceptionSpec =
4358       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4359 
4360   // Determine whether the type being created is already canonical or not.
4361   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4362                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4363   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4364     if (!ArgArray[i].isCanonicalAsParam())
4365       isCanonical = false;
4366 
4367   if (OnlyWantCanonical)
4368     assert(isCanonical &&
4369            "given non-canonical parameters constructing canonical type");
4370 
4371   // If this type isn't canonical, get the canonical version of it if we don't
4372   // already have it. The exception spec is only partially part of the
4373   // canonical type, and only in C++17 onwards.
4374   if (!isCanonical && Canonical.isNull()) {
4375     SmallVector<QualType, 16> CanonicalArgs;
4376     CanonicalArgs.reserve(NumArgs);
4377     for (unsigned i = 0; i != NumArgs; ++i)
4378       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4379 
4380     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4381     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4382     CanonicalEPI.HasTrailingReturn = false;
4383 
4384     if (IsCanonicalExceptionSpec) {
4385       // Exception spec is already OK.
4386     } else if (NoexceptInType) {
4387       switch (EPI.ExceptionSpec.Type) {
4388       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4389         // We don't know yet. It shouldn't matter what we pick here; no-one
4390         // should ever look at this.
4391         LLVM_FALLTHROUGH;
4392       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4393         CanonicalEPI.ExceptionSpec.Type = EST_None;
4394         break;
4395 
4396         // A dynamic exception specification is almost always "not noexcept",
4397         // with the exception that a pack expansion might expand to no types.
4398       case EST_Dynamic: {
4399         bool AnyPacks = false;
4400         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4401           if (ET->getAs<PackExpansionType>())
4402             AnyPacks = true;
4403           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4404         }
4405         if (!AnyPacks)
4406           CanonicalEPI.ExceptionSpec.Type = EST_None;
4407         else {
4408           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4409           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4410         }
4411         break;
4412       }
4413 
4414       case EST_DynamicNone:
4415       case EST_BasicNoexcept:
4416       case EST_NoexceptTrue:
4417       case EST_NoThrow:
4418         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4419         break;
4420 
4421       case EST_DependentNoexcept:
4422         llvm_unreachable("dependent noexcept is already canonical");
4423       }
4424     } else {
4425       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4426     }
4427 
4428     // Adjust the canonical function result type.
4429     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4430     Canonical =
4431         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4432 
4433     // Get the new insert position for the node we care about.
4434     FunctionProtoType *NewIP =
4435       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4436     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4437   }
4438 
4439   // Compute the needed size to hold this FunctionProtoType and the
4440   // various trailing objects.
4441   auto ESH = FunctionProtoType::getExceptionSpecSize(
4442       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4443   size_t Size = FunctionProtoType::totalSizeToAlloc<
4444       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4445       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4446       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4447       NumArgs, EPI.Variadic,
4448       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4449       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4450       EPI.ExtParameterInfos ? NumArgs : 0,
4451       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4452 
4453   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4454   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4455   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4456   Types.push_back(FTP);
4457   if (!Unique)
4458     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4459   return QualType(FTP, 0);
4460 }
4461 
4462 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4463   llvm::FoldingSetNodeID ID;
4464   PipeType::Profile(ID, T, ReadOnly);
4465 
4466   void *InsertPos = nullptr;
4467   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4468     return QualType(PT, 0);
4469 
4470   // If the pipe element type isn't canonical, this won't be a canonical type
4471   // either, so fill in the canonical type field.
4472   QualType Canonical;
4473   if (!T.isCanonical()) {
4474     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4475 
4476     // Get the new insert position for the node we care about.
4477     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4478     assert(!NewIP && "Shouldn't be in the map!");
4479     (void)NewIP;
4480   }
4481   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4482   Types.push_back(New);
4483   PipeTypes.InsertNode(New, InsertPos);
4484   return QualType(New, 0);
4485 }
4486 
4487 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4488   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4489   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4490                          : Ty;
4491 }
4492 
4493 QualType ASTContext::getReadPipeType(QualType T) const {
4494   return getPipeType(T, true);
4495 }
4496 
4497 QualType ASTContext::getWritePipeType(QualType T) const {
4498   return getPipeType(T, false);
4499 }
4500 
4501 QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4502   llvm::FoldingSetNodeID ID;
4503   BitIntType::Profile(ID, IsUnsigned, NumBits);
4504 
4505   void *InsertPos = nullptr;
4506   if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4507     return QualType(EIT, 0);
4508 
4509   auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
4510   BitIntTypes.InsertNode(New, InsertPos);
4511   Types.push_back(New);
4512   return QualType(New, 0);
4513 }
4514 
4515 QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4516                                             Expr *NumBitsExpr) const {
4517   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4518   llvm::FoldingSetNodeID ID;
4519   DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4520 
4521   void *InsertPos = nullptr;
4522   if (DependentBitIntType *Existing =
4523           DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4524     return QualType(Existing, 0);
4525 
4526   auto *New = new (*this, TypeAlignment)
4527       DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
4528   DependentBitIntTypes.InsertNode(New, InsertPos);
4529 
4530   Types.push_back(New);
4531   return QualType(New, 0);
4532 }
4533 
4534 #ifndef NDEBUG
4535 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4536   if (!isa<CXXRecordDecl>(D)) return false;
4537   const auto *RD = cast<CXXRecordDecl>(D);
4538   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4539     return true;
4540   if (RD->getDescribedClassTemplate() &&
4541       !isa<ClassTemplateSpecializationDecl>(RD))
4542     return true;
4543   return false;
4544 }
4545 #endif
4546 
4547 /// getInjectedClassNameType - Return the unique reference to the
4548 /// injected class name type for the specified templated declaration.
4549 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4550                                               QualType TST) const {
4551   assert(NeedsInjectedClassNameType(Decl));
4552   if (Decl->TypeForDecl) {
4553     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4554   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4555     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4556     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4557     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4558   } else {
4559     Type *newType =
4560       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4561     Decl->TypeForDecl = newType;
4562     Types.push_back(newType);
4563   }
4564   return QualType(Decl->TypeForDecl, 0);
4565 }
4566 
4567 /// getTypeDeclType - Return the unique reference to the type for the
4568 /// specified type declaration.
4569 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4570   assert(Decl && "Passed null for Decl param");
4571   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4572 
4573   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4574     return getTypedefType(Typedef);
4575 
4576   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4577          "Template type parameter types are always available.");
4578 
4579   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4580     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4581     assert(!NeedsInjectedClassNameType(Record));
4582     return getRecordType(Record);
4583   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4584     assert(Enum->isFirstDecl() && "enum has previous declaration");
4585     return getEnumType(Enum);
4586   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4587     return getUnresolvedUsingType(Using);
4588   } else
4589     llvm_unreachable("TypeDecl without a type?");
4590 
4591   return QualType(Decl->TypeForDecl, 0);
4592 }
4593 
4594 /// getTypedefType - Return the unique reference to the type for the
4595 /// specified typedef name decl.
4596 QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4597                                     QualType Underlying) const {
4598   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4599 
4600   if (Underlying.isNull())
4601     Underlying = Decl->getUnderlyingType();
4602   QualType Canonical = getCanonicalType(Underlying);
4603   auto *newType = new (*this, TypeAlignment)
4604       TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4605   Decl->TypeForDecl = newType;
4606   Types.push_back(newType);
4607   return QualType(newType, 0);
4608 }
4609 
4610 QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4611                                   QualType Underlying) const {
4612   llvm::FoldingSetNodeID ID;
4613   UsingType::Profile(ID, Found);
4614 
4615   void *InsertPos = nullptr;
4616   UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos);
4617   if (T)
4618     return QualType(T, 0);
4619 
4620   assert(!Underlying.hasLocalQualifiers());
4621   assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl())));
4622   QualType Canon = Underlying.getCanonicalType();
4623 
4624   UsingType *NewType =
4625       new (*this, TypeAlignment) UsingType(Found, Underlying, Canon);
4626   Types.push_back(NewType);
4627   UsingTypes.InsertNode(NewType, InsertPos);
4628   return QualType(NewType, 0);
4629 }
4630 
4631 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4632   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4633 
4634   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4635     if (PrevDecl->TypeForDecl)
4636       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4637 
4638   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4639   Decl->TypeForDecl = newType;
4640   Types.push_back(newType);
4641   return QualType(newType, 0);
4642 }
4643 
4644 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4645   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4646 
4647   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4648     if (PrevDecl->TypeForDecl)
4649       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4650 
4651   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4652   Decl->TypeForDecl = newType;
4653   Types.push_back(newType);
4654   return QualType(newType, 0);
4655 }
4656 
4657 QualType ASTContext::getUnresolvedUsingType(
4658     const UnresolvedUsingTypenameDecl *Decl) const {
4659   if (Decl->TypeForDecl)
4660     return QualType(Decl->TypeForDecl, 0);
4661 
4662   if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4663           Decl->getCanonicalDecl())
4664     if (CanonicalDecl->TypeForDecl)
4665       return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4666 
4667   Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
4668   Decl->TypeForDecl = newType;
4669   Types.push_back(newType);
4670   return QualType(newType, 0);
4671 }
4672 
4673 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4674                                        QualType modifiedType,
4675                                        QualType equivalentType) {
4676   llvm::FoldingSetNodeID id;
4677   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4678 
4679   void *insertPos = nullptr;
4680   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4681   if (type) return QualType(type, 0);
4682 
4683   QualType canon = getCanonicalType(equivalentType);
4684   type = new (*this, TypeAlignment)
4685       AttributedType(canon, attrKind, modifiedType, equivalentType);
4686 
4687   Types.push_back(type);
4688   AttributedTypes.InsertNode(type, insertPos);
4689 
4690   return QualType(type, 0);
4691 }
4692 
4693 QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4694                                              QualType Wrapped) {
4695   llvm::FoldingSetNodeID ID;
4696   BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4697 
4698   void *InsertPos = nullptr;
4699   BTFTagAttributedType *Ty =
4700       BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4701   if (Ty)
4702     return QualType(Ty, 0);
4703 
4704   QualType Canon = getCanonicalType(Wrapped);
4705   Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4706 
4707   Types.push_back(Ty);
4708   BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4709 
4710   return QualType(Ty, 0);
4711 }
4712 
4713 /// Retrieve a substitution-result type.
4714 QualType
4715 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4716                                          QualType Replacement) const {
4717   assert(Replacement.isCanonical()
4718          && "replacement types must always be canonical");
4719 
4720   llvm::FoldingSetNodeID ID;
4721   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4722   void *InsertPos = nullptr;
4723   SubstTemplateTypeParmType *SubstParm
4724     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4725 
4726   if (!SubstParm) {
4727     SubstParm = new (*this, TypeAlignment)
4728       SubstTemplateTypeParmType(Parm, Replacement);
4729     Types.push_back(SubstParm);
4730     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4731   }
4732 
4733   return QualType(SubstParm, 0);
4734 }
4735 
4736 /// Retrieve a
4737 QualType ASTContext::getSubstTemplateTypeParmPackType(
4738                                           const TemplateTypeParmType *Parm,
4739                                               const TemplateArgument &ArgPack) {
4740 #ifndef NDEBUG
4741   for (const auto &P : ArgPack.pack_elements()) {
4742     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4743     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4744   }
4745 #endif
4746 
4747   llvm::FoldingSetNodeID ID;
4748   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4749   void *InsertPos = nullptr;
4750   if (SubstTemplateTypeParmPackType *SubstParm
4751         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4752     return QualType(SubstParm, 0);
4753 
4754   QualType Canon;
4755   if (!Parm->isCanonicalUnqualified()) {
4756     Canon = getCanonicalType(QualType(Parm, 0));
4757     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4758                                              ArgPack);
4759     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4760   }
4761 
4762   auto *SubstParm
4763     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4764                                                                ArgPack);
4765   Types.push_back(SubstParm);
4766   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4767   return QualType(SubstParm, 0);
4768 }
4769 
4770 /// Retrieve the template type parameter type for a template
4771 /// parameter or parameter pack with the given depth, index, and (optionally)
4772 /// name.
4773 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4774                                              bool ParameterPack,
4775                                              TemplateTypeParmDecl *TTPDecl) const {
4776   llvm::FoldingSetNodeID ID;
4777   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4778   void *InsertPos = nullptr;
4779   TemplateTypeParmType *TypeParm
4780     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4781 
4782   if (TypeParm)
4783     return QualType(TypeParm, 0);
4784 
4785   if (TTPDecl) {
4786     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4787     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4788 
4789     TemplateTypeParmType *TypeCheck
4790       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4791     assert(!TypeCheck && "Template type parameter canonical type broken");
4792     (void)TypeCheck;
4793   } else
4794     TypeParm = new (*this, TypeAlignment)
4795       TemplateTypeParmType(Depth, Index, ParameterPack);
4796 
4797   Types.push_back(TypeParm);
4798   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4799 
4800   return QualType(TypeParm, 0);
4801 }
4802 
4803 TypeSourceInfo *
4804 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4805                                               SourceLocation NameLoc,
4806                                         const TemplateArgumentListInfo &Args,
4807                                               QualType Underlying) const {
4808   assert(!Name.getAsDependentTemplateName() &&
4809          "No dependent template names here!");
4810   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4811 
4812   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4813   TemplateSpecializationTypeLoc TL =
4814       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4815   TL.setTemplateKeywordLoc(SourceLocation());
4816   TL.setTemplateNameLoc(NameLoc);
4817   TL.setLAngleLoc(Args.getLAngleLoc());
4818   TL.setRAngleLoc(Args.getRAngleLoc());
4819   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4820     TL.setArgLocInfo(i, Args[i].getLocInfo());
4821   return DI;
4822 }
4823 
4824 QualType
4825 ASTContext::getTemplateSpecializationType(TemplateName Template,
4826                                           const TemplateArgumentListInfo &Args,
4827                                           QualType Underlying) const {
4828   assert(!Template.getAsDependentTemplateName() &&
4829          "No dependent template names here!");
4830 
4831   SmallVector<TemplateArgument, 4> ArgVec;
4832   ArgVec.reserve(Args.size());
4833   for (const TemplateArgumentLoc &Arg : Args.arguments())
4834     ArgVec.push_back(Arg.getArgument());
4835 
4836   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4837 }
4838 
4839 #ifndef NDEBUG
4840 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4841   for (const TemplateArgument &Arg : Args)
4842     if (Arg.isPackExpansion())
4843       return true;
4844 
4845   return true;
4846 }
4847 #endif
4848 
4849 QualType
4850 ASTContext::getTemplateSpecializationType(TemplateName Template,
4851                                           ArrayRef<TemplateArgument> Args,
4852                                           QualType Underlying) const {
4853   assert(!Template.getAsDependentTemplateName() &&
4854          "No dependent template names here!");
4855   // Look through qualified template names.
4856   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4857     Template = TemplateName(QTN->getTemplateDecl());
4858 
4859   bool IsTypeAlias =
4860     Template.getAsTemplateDecl() &&
4861     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4862   QualType CanonType;
4863   if (!Underlying.isNull())
4864     CanonType = getCanonicalType(Underlying);
4865   else {
4866     // We can get here with an alias template when the specialization contains
4867     // a pack expansion that does not match up with a parameter pack.
4868     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4869            "Caller must compute aliased type");
4870     IsTypeAlias = false;
4871     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4872   }
4873 
4874   // Allocate the (non-canonical) template specialization type, but don't
4875   // try to unique it: these types typically have location information that
4876   // we don't unique and don't want to lose.
4877   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4878                        sizeof(TemplateArgument) * Args.size() +
4879                        (IsTypeAlias? sizeof(QualType) : 0),
4880                        TypeAlignment);
4881   auto *Spec
4882     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4883                                          IsTypeAlias ? Underlying : QualType());
4884 
4885   Types.push_back(Spec);
4886   return QualType(Spec, 0);
4887 }
4888 
4889 static bool
4890 getCanonicalTemplateArguments(const ASTContext &C,
4891                               ArrayRef<TemplateArgument> OrigArgs,
4892                               SmallVectorImpl<TemplateArgument> &CanonArgs) {
4893   bool AnyNonCanonArgs = false;
4894   unsigned NumArgs = OrigArgs.size();
4895   CanonArgs.resize(NumArgs);
4896   for (unsigned I = 0; I != NumArgs; ++I) {
4897     const TemplateArgument &OrigArg = OrigArgs[I];
4898     TemplateArgument &CanonArg = CanonArgs[I];
4899     CanonArg = C.getCanonicalTemplateArgument(OrigArg);
4900     if (!CanonArg.structurallyEquals(OrigArg))
4901       AnyNonCanonArgs = true;
4902   }
4903   return AnyNonCanonArgs;
4904 }
4905 
4906 QualType ASTContext::getCanonicalTemplateSpecializationType(
4907     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4908   assert(!Template.getAsDependentTemplateName() &&
4909          "No dependent template names here!");
4910 
4911   // Look through qualified template names.
4912   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4913     Template = TemplateName(QTN->getTemplateDecl());
4914 
4915   // Build the canonical template specialization type.
4916   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4917   SmallVector<TemplateArgument, 4> CanonArgs;
4918   ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
4919 
4920   // Determine whether this canonical template specialization type already
4921   // exists.
4922   llvm::FoldingSetNodeID ID;
4923   TemplateSpecializationType::Profile(ID, CanonTemplate,
4924                                       CanonArgs, *this);
4925 
4926   void *InsertPos = nullptr;
4927   TemplateSpecializationType *Spec
4928     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4929 
4930   if (!Spec) {
4931     // Allocate a new canonical template specialization type.
4932     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4933                           sizeof(TemplateArgument) * CanonArgs.size()),
4934                          TypeAlignment);
4935     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4936                                                 CanonArgs,
4937                                                 QualType(), QualType());
4938     Types.push_back(Spec);
4939     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4940   }
4941 
4942   assert(Spec->isDependentType() &&
4943          "Non-dependent template-id type must have a canonical type");
4944   return QualType(Spec, 0);
4945 }
4946 
4947 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4948                                        NestedNameSpecifier *NNS,
4949                                        QualType NamedType,
4950                                        TagDecl *OwnedTagDecl) const {
4951   llvm::FoldingSetNodeID ID;
4952   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4953 
4954   void *InsertPos = nullptr;
4955   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4956   if (T)
4957     return QualType(T, 0);
4958 
4959   QualType Canon = NamedType;
4960   if (!Canon.isCanonical()) {
4961     Canon = getCanonicalType(NamedType);
4962     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4963     assert(!CheckT && "Elaborated canonical type broken");
4964     (void)CheckT;
4965   }
4966 
4967   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4968                        TypeAlignment);
4969   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4970 
4971   Types.push_back(T);
4972   ElaboratedTypes.InsertNode(T, InsertPos);
4973   return QualType(T, 0);
4974 }
4975 
4976 QualType
4977 ASTContext::getParenType(QualType InnerType) const {
4978   llvm::FoldingSetNodeID ID;
4979   ParenType::Profile(ID, InnerType);
4980 
4981   void *InsertPos = nullptr;
4982   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4983   if (T)
4984     return QualType(T, 0);
4985 
4986   QualType Canon = InnerType;
4987   if (!Canon.isCanonical()) {
4988     Canon = getCanonicalType(InnerType);
4989     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4990     assert(!CheckT && "Paren canonical type broken");
4991     (void)CheckT;
4992   }
4993 
4994   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4995   Types.push_back(T);
4996   ParenTypes.InsertNode(T, InsertPos);
4997   return QualType(T, 0);
4998 }
4999 
5000 QualType
5001 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5002                                   const IdentifierInfo *MacroII) const {
5003   QualType Canon = UnderlyingTy;
5004   if (!Canon.isCanonical())
5005     Canon = getCanonicalType(UnderlyingTy);
5006 
5007   auto *newType = new (*this, TypeAlignment)
5008       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5009   Types.push_back(newType);
5010   return QualType(newType, 0);
5011 }
5012 
5013 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5014                                           NestedNameSpecifier *NNS,
5015                                           const IdentifierInfo *Name,
5016                                           QualType Canon) const {
5017   if (Canon.isNull()) {
5018     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5019     if (CanonNNS != NNS)
5020       Canon = getDependentNameType(Keyword, CanonNNS, Name);
5021   }
5022 
5023   llvm::FoldingSetNodeID ID;
5024   DependentNameType::Profile(ID, Keyword, NNS, Name);
5025 
5026   void *InsertPos = nullptr;
5027   DependentNameType *T
5028     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5029   if (T)
5030     return QualType(T, 0);
5031 
5032   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
5033   Types.push_back(T);
5034   DependentNameTypes.InsertNode(T, InsertPos);
5035   return QualType(T, 0);
5036 }
5037 
5038 QualType
5039 ASTContext::getDependentTemplateSpecializationType(
5040                                  ElaboratedTypeKeyword Keyword,
5041                                  NestedNameSpecifier *NNS,
5042                                  const IdentifierInfo *Name,
5043                                  const TemplateArgumentListInfo &Args) const {
5044   // TODO: avoid this copy
5045   SmallVector<TemplateArgument, 16> ArgCopy;
5046   for (unsigned I = 0, E = Args.size(); I != E; ++I)
5047     ArgCopy.push_back(Args[I].getArgument());
5048   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5049 }
5050 
5051 QualType
5052 ASTContext::getDependentTemplateSpecializationType(
5053                                  ElaboratedTypeKeyword Keyword,
5054                                  NestedNameSpecifier *NNS,
5055                                  const IdentifierInfo *Name,
5056                                  ArrayRef<TemplateArgument> Args) const {
5057   assert((!NNS || NNS->isDependent()) &&
5058          "nested-name-specifier must be dependent");
5059 
5060   llvm::FoldingSetNodeID ID;
5061   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5062                                                Name, Args);
5063 
5064   void *InsertPos = nullptr;
5065   DependentTemplateSpecializationType *T
5066     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5067   if (T)
5068     return QualType(T, 0);
5069 
5070   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5071 
5072   ElaboratedTypeKeyword CanonKeyword = Keyword;
5073   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
5074 
5075   SmallVector<TemplateArgument, 16> CanonArgs;
5076   bool AnyNonCanonArgs =
5077       ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
5078 
5079   QualType Canon;
5080   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5081     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5082                                                    Name,
5083                                                    CanonArgs);
5084 
5085     // Find the insert position again.
5086     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5087   }
5088 
5089   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5090                         sizeof(TemplateArgument) * Args.size()),
5091                        TypeAlignment);
5092   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5093                                                     Name, Args, Canon);
5094   Types.push_back(T);
5095   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5096   return QualType(T, 0);
5097 }
5098 
5099 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5100   TemplateArgument Arg;
5101   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5102     QualType ArgType = getTypeDeclType(TTP);
5103     if (TTP->isParameterPack())
5104       ArgType = getPackExpansionType(ArgType, None);
5105 
5106     Arg = TemplateArgument(ArgType);
5107   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5108     QualType T =
5109         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5110     // For class NTTPs, ensure we include the 'const' so the type matches that
5111     // of a real template argument.
5112     // FIXME: It would be more faithful to model this as something like an
5113     // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5114     if (T->isRecordType())
5115       T.addConst();
5116     Expr *E = new (*this) DeclRefExpr(
5117         *this, NTTP, /*enclosing*/ false, T,
5118         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5119 
5120     if (NTTP->isParameterPack())
5121       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
5122                                         None);
5123     Arg = TemplateArgument(E);
5124   } else {
5125     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5126     if (TTP->isParameterPack())
5127       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
5128     else
5129       Arg = TemplateArgument(TemplateName(TTP));
5130   }
5131 
5132   if (Param->isTemplateParameterPack())
5133     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5134 
5135   return Arg;
5136 }
5137 
5138 void
5139 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
5140                                     SmallVectorImpl<TemplateArgument> &Args) {
5141   Args.reserve(Args.size() + Params->size());
5142 
5143   for (NamedDecl *Param : *Params)
5144     Args.push_back(getInjectedTemplateArg(Param));
5145 }
5146 
5147 QualType ASTContext::getPackExpansionType(QualType Pattern,
5148                                           Optional<unsigned> NumExpansions,
5149                                           bool ExpectPackInType) {
5150   assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5151          "Pack expansions must expand one or more parameter packs");
5152 
5153   llvm::FoldingSetNodeID ID;
5154   PackExpansionType::Profile(ID, Pattern, NumExpansions);
5155 
5156   void *InsertPos = nullptr;
5157   PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5158   if (T)
5159     return QualType(T, 0);
5160 
5161   QualType Canon;
5162   if (!Pattern.isCanonical()) {
5163     Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5164                                  /*ExpectPackInType=*/false);
5165 
5166     // Find the insert position again, in case we inserted an element into
5167     // PackExpansionTypes and invalidated our insert position.
5168     PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5169   }
5170 
5171   T = new (*this, TypeAlignment)
5172       PackExpansionType(Pattern, Canon, NumExpansions);
5173   Types.push_back(T);
5174   PackExpansionTypes.InsertNode(T, InsertPos);
5175   return QualType(T, 0);
5176 }
5177 
5178 /// CmpProtocolNames - Comparison predicate for sorting protocols
5179 /// alphabetically.
5180 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5181                             ObjCProtocolDecl *const *RHS) {
5182   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5183 }
5184 
5185 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5186   if (Protocols.empty()) return true;
5187 
5188   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5189     return false;
5190 
5191   for (unsigned i = 1; i != Protocols.size(); ++i)
5192     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5193         Protocols[i]->getCanonicalDecl() != Protocols[i])
5194       return false;
5195   return true;
5196 }
5197 
5198 static void
5199 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5200   // Sort protocols, keyed by name.
5201   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5202 
5203   // Canonicalize.
5204   for (ObjCProtocolDecl *&P : Protocols)
5205     P = P->getCanonicalDecl();
5206 
5207   // Remove duplicates.
5208   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5209   Protocols.erase(ProtocolsEnd, Protocols.end());
5210 }
5211 
5212 QualType ASTContext::getObjCObjectType(QualType BaseType,
5213                                        ObjCProtocolDecl * const *Protocols,
5214                                        unsigned NumProtocols) const {
5215   return getObjCObjectType(BaseType, {},
5216                            llvm::makeArrayRef(Protocols, NumProtocols),
5217                            /*isKindOf=*/false);
5218 }
5219 
5220 QualType ASTContext::getObjCObjectType(
5221            QualType baseType,
5222            ArrayRef<QualType> typeArgs,
5223            ArrayRef<ObjCProtocolDecl *> protocols,
5224            bool isKindOf) const {
5225   // If the base type is an interface and there aren't any protocols or
5226   // type arguments to add, then the interface type will do just fine.
5227   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5228       isa<ObjCInterfaceType>(baseType))
5229     return baseType;
5230 
5231   // Look in the folding set for an existing type.
5232   llvm::FoldingSetNodeID ID;
5233   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5234   void *InsertPos = nullptr;
5235   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5236     return QualType(QT, 0);
5237 
5238   // Determine the type arguments to be used for canonicalization,
5239   // which may be explicitly specified here or written on the base
5240   // type.
5241   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5242   if (effectiveTypeArgs.empty()) {
5243     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5244       effectiveTypeArgs = baseObject->getTypeArgs();
5245   }
5246 
5247   // Build the canonical type, which has the canonical base type and a
5248   // sorted-and-uniqued list of protocols and the type arguments
5249   // canonicalized.
5250   QualType canonical;
5251   bool typeArgsAreCanonical = llvm::all_of(
5252       effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5253   bool protocolsSorted = areSortedAndUniqued(protocols);
5254   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5255     // Determine the canonical type arguments.
5256     ArrayRef<QualType> canonTypeArgs;
5257     SmallVector<QualType, 4> canonTypeArgsVec;
5258     if (!typeArgsAreCanonical) {
5259       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5260       for (auto typeArg : effectiveTypeArgs)
5261         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5262       canonTypeArgs = canonTypeArgsVec;
5263     } else {
5264       canonTypeArgs = effectiveTypeArgs;
5265     }
5266 
5267     ArrayRef<ObjCProtocolDecl *> canonProtocols;
5268     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5269     if (!protocolsSorted) {
5270       canonProtocolsVec.append(protocols.begin(), protocols.end());
5271       SortAndUniqueProtocols(canonProtocolsVec);
5272       canonProtocols = canonProtocolsVec;
5273     } else {
5274       canonProtocols = protocols;
5275     }
5276 
5277     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5278                                   canonProtocols, isKindOf);
5279 
5280     // Regenerate InsertPos.
5281     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5282   }
5283 
5284   unsigned size = sizeof(ObjCObjectTypeImpl);
5285   size += typeArgs.size() * sizeof(QualType);
5286   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5287   void *mem = Allocate(size, TypeAlignment);
5288   auto *T =
5289     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5290                                  isKindOf);
5291 
5292   Types.push_back(T);
5293   ObjCObjectTypes.InsertNode(T, InsertPos);
5294   return QualType(T, 0);
5295 }
5296 
5297 /// Apply Objective-C protocol qualifiers to the given type.
5298 /// If this is for the canonical type of a type parameter, we can apply
5299 /// protocol qualifiers on the ObjCObjectPointerType.
5300 QualType
5301 ASTContext::applyObjCProtocolQualifiers(QualType type,
5302                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5303                   bool allowOnPointerType) const {
5304   hasError = false;
5305 
5306   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5307     return getObjCTypeParamType(objT->getDecl(), protocols);
5308   }
5309 
5310   // Apply protocol qualifiers to ObjCObjectPointerType.
5311   if (allowOnPointerType) {
5312     if (const auto *objPtr =
5313             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5314       const ObjCObjectType *objT = objPtr->getObjectType();
5315       // Merge protocol lists and construct ObjCObjectType.
5316       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5317       protocolsVec.append(objT->qual_begin(),
5318                           objT->qual_end());
5319       protocolsVec.append(protocols.begin(), protocols.end());
5320       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5321       type = getObjCObjectType(
5322              objT->getBaseType(),
5323              objT->getTypeArgsAsWritten(),
5324              protocols,
5325              objT->isKindOfTypeAsWritten());
5326       return getObjCObjectPointerType(type);
5327     }
5328   }
5329 
5330   // Apply protocol qualifiers to ObjCObjectType.
5331   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5332     // FIXME: Check for protocols to which the class type is already
5333     // known to conform.
5334 
5335     return getObjCObjectType(objT->getBaseType(),
5336                              objT->getTypeArgsAsWritten(),
5337                              protocols,
5338                              objT->isKindOfTypeAsWritten());
5339   }
5340 
5341   // If the canonical type is ObjCObjectType, ...
5342   if (type->isObjCObjectType()) {
5343     // Silently overwrite any existing protocol qualifiers.
5344     // TODO: determine whether that's the right thing to do.
5345 
5346     // FIXME: Check for protocols to which the class type is already
5347     // known to conform.
5348     return getObjCObjectType(type, {}, protocols, false);
5349   }
5350 
5351   // id<protocol-list>
5352   if (type->isObjCIdType()) {
5353     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5354     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5355                                  objPtr->isKindOfType());
5356     return getObjCObjectPointerType(type);
5357   }
5358 
5359   // Class<protocol-list>
5360   if (type->isObjCClassType()) {
5361     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5362     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5363                                  objPtr->isKindOfType());
5364     return getObjCObjectPointerType(type);
5365   }
5366 
5367   hasError = true;
5368   return type;
5369 }
5370 
5371 QualType
5372 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5373                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
5374   // Look in the folding set for an existing type.
5375   llvm::FoldingSetNodeID ID;
5376   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5377   void *InsertPos = nullptr;
5378   if (ObjCTypeParamType *TypeParam =
5379       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5380     return QualType(TypeParam, 0);
5381 
5382   // We canonicalize to the underlying type.
5383   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5384   if (!protocols.empty()) {
5385     // Apply the protocol qualifers.
5386     bool hasError;
5387     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5388         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5389     assert(!hasError && "Error when apply protocol qualifier to bound type");
5390   }
5391 
5392   unsigned size = sizeof(ObjCTypeParamType);
5393   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5394   void *mem = Allocate(size, TypeAlignment);
5395   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5396 
5397   Types.push_back(newType);
5398   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5399   return QualType(newType, 0);
5400 }
5401 
5402 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5403                                               ObjCTypeParamDecl *New) const {
5404   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5405   // Update TypeForDecl after updating TypeSourceInfo.
5406   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5407   SmallVector<ObjCProtocolDecl *, 8> protocols;
5408   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5409   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5410   New->setTypeForDecl(UpdatedTy.getTypePtr());
5411 }
5412 
5413 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5414 /// protocol list adopt all protocols in QT's qualified-id protocol
5415 /// list.
5416 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5417                                                 ObjCInterfaceDecl *IC) {
5418   if (!QT->isObjCQualifiedIdType())
5419     return false;
5420 
5421   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5422     // If both the right and left sides have qualifiers.
5423     for (auto *Proto : OPT->quals()) {
5424       if (!IC->ClassImplementsProtocol(Proto, false))
5425         return false;
5426     }
5427     return true;
5428   }
5429   return false;
5430 }
5431 
5432 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5433 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5434 /// of protocols.
5435 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5436                                                 ObjCInterfaceDecl *IDecl) {
5437   if (!QT->isObjCQualifiedIdType())
5438     return false;
5439   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5440   if (!OPT)
5441     return false;
5442   if (!IDecl->hasDefinition())
5443     return false;
5444   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5445   CollectInheritedProtocols(IDecl, InheritedProtocols);
5446   if (InheritedProtocols.empty())
5447     return false;
5448   // Check that if every protocol in list of id<plist> conforms to a protocol
5449   // of IDecl's, then bridge casting is ok.
5450   bool Conforms = false;
5451   for (auto *Proto : OPT->quals()) {
5452     Conforms = false;
5453     for (auto *PI : InheritedProtocols) {
5454       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5455         Conforms = true;
5456         break;
5457       }
5458     }
5459     if (!Conforms)
5460       break;
5461   }
5462   if (Conforms)
5463     return true;
5464 
5465   for (auto *PI : InheritedProtocols) {
5466     // If both the right and left sides have qualifiers.
5467     bool Adopts = false;
5468     for (auto *Proto : OPT->quals()) {
5469       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5470       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5471         break;
5472     }
5473     if (!Adopts)
5474       return false;
5475   }
5476   return true;
5477 }
5478 
5479 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5480 /// the given object type.
5481 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5482   llvm::FoldingSetNodeID ID;
5483   ObjCObjectPointerType::Profile(ID, ObjectT);
5484 
5485   void *InsertPos = nullptr;
5486   if (ObjCObjectPointerType *QT =
5487               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5488     return QualType(QT, 0);
5489 
5490   // Find the canonical object type.
5491   QualType Canonical;
5492   if (!ObjectT.isCanonical()) {
5493     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5494 
5495     // Regenerate InsertPos.
5496     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5497   }
5498 
5499   // No match.
5500   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5501   auto *QType =
5502     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5503 
5504   Types.push_back(QType);
5505   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5506   return QualType(QType, 0);
5507 }
5508 
5509 /// getObjCInterfaceType - Return the unique reference to the type for the
5510 /// specified ObjC interface decl. The list of protocols is optional.
5511 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5512                                           ObjCInterfaceDecl *PrevDecl) const {
5513   if (Decl->TypeForDecl)
5514     return QualType(Decl->TypeForDecl, 0);
5515 
5516   if (PrevDecl) {
5517     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5518     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5519     return QualType(PrevDecl->TypeForDecl, 0);
5520   }
5521 
5522   // Prefer the definition, if there is one.
5523   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5524     Decl = Def;
5525 
5526   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5527   auto *T = new (Mem) ObjCInterfaceType(Decl);
5528   Decl->TypeForDecl = T;
5529   Types.push_back(T);
5530   return QualType(T, 0);
5531 }
5532 
5533 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5534 /// TypeOfExprType AST's (since expression's are never shared). For example,
5535 /// multiple declarations that refer to "typeof(x)" all contain different
5536 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5537 /// on canonical type's (which are always unique).
5538 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5539   TypeOfExprType *toe;
5540   if (tofExpr->isTypeDependent()) {
5541     llvm::FoldingSetNodeID ID;
5542     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5543 
5544     void *InsertPos = nullptr;
5545     DependentTypeOfExprType *Canon
5546       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5547     if (Canon) {
5548       // We already have a "canonical" version of an identical, dependent
5549       // typeof(expr) type. Use that as our canonical type.
5550       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5551                                           QualType((TypeOfExprType*)Canon, 0));
5552     } else {
5553       // Build a new, canonical typeof(expr) type.
5554       Canon
5555         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5556       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5557       toe = Canon;
5558     }
5559   } else {
5560     QualType Canonical = getCanonicalType(tofExpr->getType());
5561     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5562   }
5563   Types.push_back(toe);
5564   return QualType(toe, 0);
5565 }
5566 
5567 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5568 /// TypeOfType nodes. The only motivation to unique these nodes would be
5569 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5570 /// an issue. This doesn't affect the type checker, since it operates
5571 /// on canonical types (which are always unique).
5572 QualType ASTContext::getTypeOfType(QualType tofType) const {
5573   QualType Canonical = getCanonicalType(tofType);
5574   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5575   Types.push_back(tot);
5576   return QualType(tot, 0);
5577 }
5578 
5579 /// getReferenceQualifiedType - Given an expr, will return the type for
5580 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5581 /// and class member access into account.
5582 QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
5583   // C++11 [dcl.type.simple]p4:
5584   //   [...]
5585   QualType T = E->getType();
5586   switch (E->getValueKind()) {
5587   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5588   //       type of e;
5589   case VK_XValue:
5590     return getRValueReferenceType(T);
5591   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5592   //       type of e;
5593   case VK_LValue:
5594     return getLValueReferenceType(T);
5595   //  - otherwise, decltype(e) is the type of e.
5596   case VK_PRValue:
5597     return T;
5598   }
5599   llvm_unreachable("Unknown value kind");
5600 }
5601 
5602 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5603 /// nodes. This would never be helpful, since each such type has its own
5604 /// expression, and would not give a significant memory saving, since there
5605 /// is an Expr tree under each such type.
5606 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5607   DecltypeType *dt;
5608 
5609   // C++11 [temp.type]p2:
5610   //   If an expression e involves a template parameter, decltype(e) denotes a
5611   //   unique dependent type. Two such decltype-specifiers refer to the same
5612   //   type only if their expressions are equivalent (14.5.6.1).
5613   if (e->isInstantiationDependent()) {
5614     llvm::FoldingSetNodeID ID;
5615     DependentDecltypeType::Profile(ID, *this, e);
5616 
5617     void *InsertPos = nullptr;
5618     DependentDecltypeType *Canon
5619       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5620     if (!Canon) {
5621       // Build a new, canonical decltype(expr) type.
5622       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5623       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5624     }
5625     dt = new (*this, TypeAlignment)
5626         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5627   } else {
5628     dt = new (*this, TypeAlignment)
5629         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5630   }
5631   Types.push_back(dt);
5632   return QualType(dt, 0);
5633 }
5634 
5635 /// getUnaryTransformationType - We don't unique these, since the memory
5636 /// savings are minimal and these are rare.
5637 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5638                                            QualType UnderlyingType,
5639                                            UnaryTransformType::UTTKind Kind)
5640     const {
5641   UnaryTransformType *ut = nullptr;
5642 
5643   if (BaseType->isDependentType()) {
5644     // Look in the folding set for an existing type.
5645     llvm::FoldingSetNodeID ID;
5646     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5647 
5648     void *InsertPos = nullptr;
5649     DependentUnaryTransformType *Canon
5650       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5651 
5652     if (!Canon) {
5653       // Build a new, canonical __underlying_type(type) type.
5654       Canon = new (*this, TypeAlignment)
5655              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5656                                          Kind);
5657       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5658     }
5659     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5660                                                         QualType(), Kind,
5661                                                         QualType(Canon, 0));
5662   } else {
5663     QualType CanonType = getCanonicalType(UnderlyingType);
5664     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5665                                                         UnderlyingType, Kind,
5666                                                         CanonType);
5667   }
5668   Types.push_back(ut);
5669   return QualType(ut, 0);
5670 }
5671 
5672 QualType ASTContext::getAutoTypeInternal(
5673     QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5674     bool IsPack, ConceptDecl *TypeConstraintConcept,
5675     ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5676   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5677       !TypeConstraintConcept && !IsDependent)
5678     return getAutoDeductType();
5679 
5680   // Look in the folding set for an existing type.
5681   void *InsertPos = nullptr;
5682   llvm::FoldingSetNodeID ID;
5683   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5684                     TypeConstraintConcept, TypeConstraintArgs);
5685   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5686     return QualType(AT, 0);
5687 
5688   QualType Canon;
5689   if (!IsCanon) {
5690     if (DeducedType.isNull()) {
5691       SmallVector<TemplateArgument, 4> CanonArgs;
5692       bool AnyNonCanonArgs =
5693           ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs);
5694       if (AnyNonCanonArgs) {
5695         Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5696                                     TypeConstraintConcept, CanonArgs, true);
5697         // Find the insert position again.
5698         AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5699       }
5700     } else {
5701       Canon = DeducedType.getCanonicalType();
5702     }
5703   }
5704 
5705   void *Mem = Allocate(sizeof(AutoType) +
5706                            sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5707                        TypeAlignment);
5708   auto *AT = new (Mem) AutoType(
5709       DeducedType, Keyword,
5710       (IsDependent ? TypeDependence::DependentInstantiation
5711                    : TypeDependence::None) |
5712           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5713       Canon, TypeConstraintConcept, TypeConstraintArgs);
5714   Types.push_back(AT);
5715   AutoTypes.InsertNode(AT, InsertPos);
5716   return QualType(AT, 0);
5717 }
5718 
5719 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5720 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5721 /// canonical deduced-but-dependent 'auto' type.
5722 QualType
5723 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5724                         bool IsDependent, bool IsPack,
5725                         ConceptDecl *TypeConstraintConcept,
5726                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5727   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5728   assert((!IsDependent || DeducedType.isNull()) &&
5729          "A dependent auto should be undeduced");
5730   return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5731                              TypeConstraintConcept, TypeConstraintArgs);
5732 }
5733 
5734 /// Return the uniqued reference to the deduced template specialization type
5735 /// which has been deduced to the given type, or to the canonical undeduced
5736 /// such type, or the canonical deduced-but-dependent such type.
5737 QualType ASTContext::getDeducedTemplateSpecializationType(
5738     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5739   // Look in the folding set for an existing type.
5740   void *InsertPos = nullptr;
5741   llvm::FoldingSetNodeID ID;
5742   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5743                                              IsDependent);
5744   if (DeducedTemplateSpecializationType *DTST =
5745           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5746     return QualType(DTST, 0);
5747 
5748   auto *DTST = new (*this, TypeAlignment)
5749       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5750   llvm::FoldingSetNodeID TempID;
5751   DTST->Profile(TempID);
5752   assert(ID == TempID && "ID does not match");
5753   Types.push_back(DTST);
5754   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5755   return QualType(DTST, 0);
5756 }
5757 
5758 /// getAtomicType - Return the uniqued reference to the atomic type for
5759 /// the given value type.
5760 QualType ASTContext::getAtomicType(QualType T) const {
5761   // Unique pointers, to guarantee there is only one pointer of a particular
5762   // structure.
5763   llvm::FoldingSetNodeID ID;
5764   AtomicType::Profile(ID, T);
5765 
5766   void *InsertPos = nullptr;
5767   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5768     return QualType(AT, 0);
5769 
5770   // If the atomic value type isn't canonical, this won't be a canonical type
5771   // either, so fill in the canonical type field.
5772   QualType Canonical;
5773   if (!T.isCanonical()) {
5774     Canonical = getAtomicType(getCanonicalType(T));
5775 
5776     // Get the new insert position for the node we care about.
5777     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5778     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5779   }
5780   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5781   Types.push_back(New);
5782   AtomicTypes.InsertNode(New, InsertPos);
5783   return QualType(New, 0);
5784 }
5785 
5786 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5787 QualType ASTContext::getAutoDeductType() const {
5788   if (AutoDeductTy.isNull())
5789     AutoDeductTy = QualType(new (*this, TypeAlignment)
5790                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5791                                          TypeDependence::None, QualType(),
5792                                          /*concept*/ nullptr, /*args*/ {}),
5793                             0);
5794   return AutoDeductTy;
5795 }
5796 
5797 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5798 QualType ASTContext::getAutoRRefDeductType() const {
5799   if (AutoRRefDeductTy.isNull())
5800     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5801   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5802   return AutoRRefDeductTy;
5803 }
5804 
5805 /// getTagDeclType - Return the unique reference to the type for the
5806 /// specified TagDecl (struct/union/class/enum) decl.
5807 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5808   assert(Decl);
5809   // FIXME: What is the design on getTagDeclType when it requires casting
5810   // away const?  mutable?
5811   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5812 }
5813 
5814 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5815 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5816 /// needs to agree with the definition in <stddef.h>.
5817 CanQualType ASTContext::getSizeType() const {
5818   return getFromTargetType(Target->getSizeType());
5819 }
5820 
5821 /// Return the unique signed counterpart of the integer type
5822 /// corresponding to size_t.
5823 CanQualType ASTContext::getSignedSizeType() const {
5824   return getFromTargetType(Target->getSignedSizeType());
5825 }
5826 
5827 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5828 CanQualType ASTContext::getIntMaxType() const {
5829   return getFromTargetType(Target->getIntMaxType());
5830 }
5831 
5832 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5833 CanQualType ASTContext::getUIntMaxType() const {
5834   return getFromTargetType(Target->getUIntMaxType());
5835 }
5836 
5837 /// getSignedWCharType - Return the type of "signed wchar_t".
5838 /// Used when in C++, as a GCC extension.
5839 QualType ASTContext::getSignedWCharType() const {
5840   // FIXME: derive from "Target" ?
5841   return WCharTy;
5842 }
5843 
5844 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5845 /// Used when in C++, as a GCC extension.
5846 QualType ASTContext::getUnsignedWCharType() const {
5847   // FIXME: derive from "Target" ?
5848   return UnsignedIntTy;
5849 }
5850 
5851 QualType ASTContext::getIntPtrType() const {
5852   return getFromTargetType(Target->getIntPtrType());
5853 }
5854 
5855 QualType ASTContext::getUIntPtrType() const {
5856   return getCorrespondingUnsignedType(getIntPtrType());
5857 }
5858 
5859 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5860 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5861 QualType ASTContext::getPointerDiffType() const {
5862   return getFromTargetType(Target->getPtrDiffType(0));
5863 }
5864 
5865 /// Return the unique unsigned counterpart of "ptrdiff_t"
5866 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5867 /// in the definition of %tu format specifier.
5868 QualType ASTContext::getUnsignedPointerDiffType() const {
5869   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5870 }
5871 
5872 /// Return the unique type for "pid_t" defined in
5873 /// <sys/types.h>. We need this to compute the correct type for vfork().
5874 QualType ASTContext::getProcessIDType() const {
5875   return getFromTargetType(Target->getProcessIDType());
5876 }
5877 
5878 //===----------------------------------------------------------------------===//
5879 //                              Type Operators
5880 //===----------------------------------------------------------------------===//
5881 
5882 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5883   // Push qualifiers into arrays, and then discard any remaining
5884   // qualifiers.
5885   T = getCanonicalType(T);
5886   T = getVariableArrayDecayedType(T);
5887   const Type *Ty = T.getTypePtr();
5888   QualType Result;
5889   if (isa<ArrayType>(Ty)) {
5890     Result = getArrayDecayedType(QualType(Ty,0));
5891   } else if (isa<FunctionType>(Ty)) {
5892     Result = getPointerType(QualType(Ty, 0));
5893   } else {
5894     Result = QualType(Ty, 0);
5895   }
5896 
5897   return CanQualType::CreateUnsafe(Result);
5898 }
5899 
5900 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5901                                              Qualifiers &quals) {
5902   SplitQualType splitType = type.getSplitUnqualifiedType();
5903 
5904   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5905   // the unqualified desugared type and then drops it on the floor.
5906   // We then have to strip that sugar back off with
5907   // getUnqualifiedDesugaredType(), which is silly.
5908   const auto *AT =
5909       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5910 
5911   // If we don't have an array, just use the results in splitType.
5912   if (!AT) {
5913     quals = splitType.Quals;
5914     return QualType(splitType.Ty, 0);
5915   }
5916 
5917   // Otherwise, recurse on the array's element type.
5918   QualType elementType = AT->getElementType();
5919   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5920 
5921   // If that didn't change the element type, AT has no qualifiers, so we
5922   // can just use the results in splitType.
5923   if (elementType == unqualElementType) {
5924     assert(quals.empty()); // from the recursive call
5925     quals = splitType.Quals;
5926     return QualType(splitType.Ty, 0);
5927   }
5928 
5929   // Otherwise, add in the qualifiers from the outermost type, then
5930   // build the type back up.
5931   quals.addConsistentQualifiers(splitType.Quals);
5932 
5933   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5934     return getConstantArrayType(unqualElementType, CAT->getSize(),
5935                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5936   }
5937 
5938   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5939     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5940   }
5941 
5942   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5943     return getVariableArrayType(unqualElementType,
5944                                 VAT->getSizeExpr(),
5945                                 VAT->getSizeModifier(),
5946                                 VAT->getIndexTypeCVRQualifiers(),
5947                                 VAT->getBracketsRange());
5948   }
5949 
5950   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5951   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5952                                     DSAT->getSizeModifier(), 0,
5953                                     SourceRange());
5954 }
5955 
5956 /// Attempt to unwrap two types that may both be array types with the same bound
5957 /// (or both be array types of unknown bound) for the purpose of comparing the
5958 /// cv-decomposition of two types per C++ [conv.qual].
5959 ///
5960 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
5961 ///        C++20 [conv.qual], if permitted by the current language mode.
5962 void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
5963                                          bool AllowPiMismatch) {
5964   while (true) {
5965     auto *AT1 = getAsArrayType(T1);
5966     if (!AT1)
5967       return;
5968 
5969     auto *AT2 = getAsArrayType(T2);
5970     if (!AT2)
5971       return;
5972 
5973     // If we don't have two array types with the same constant bound nor two
5974     // incomplete array types, we've unwrapped everything we can.
5975     // C++20 also permits one type to be a constant array type and the other
5976     // to be an incomplete array type.
5977     // FIXME: Consider also unwrapping array of unknown bound and VLA.
5978     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5979       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5980       if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
5981             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
5982              isa<IncompleteArrayType>(AT2))))
5983         return;
5984     } else if (isa<IncompleteArrayType>(AT1)) {
5985       if (!(isa<IncompleteArrayType>(AT2) ||
5986             (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
5987              isa<ConstantArrayType>(AT2))))
5988         return;
5989     } else {
5990       return;
5991     }
5992 
5993     T1 = AT1->getElementType();
5994     T2 = AT2->getElementType();
5995   }
5996 }
5997 
5998 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5999 ///
6000 /// If T1 and T2 are both pointer types of the same kind, or both array types
6001 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6002 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6003 ///
6004 /// This function will typically be called in a loop that successively
6005 /// "unwraps" pointer and pointer-to-member types to compare them at each
6006 /// level.
6007 ///
6008 /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6009 ///        C++20 [conv.qual], if permitted by the current language mode.
6010 ///
6011 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
6012 /// pair of types that can't be unwrapped further.
6013 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
6014                                     bool AllowPiMismatch) {
6015   UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6016 
6017   const auto *T1PtrType = T1->getAs<PointerType>();
6018   const auto *T2PtrType = T2->getAs<PointerType>();
6019   if (T1PtrType && T2PtrType) {
6020     T1 = T1PtrType->getPointeeType();
6021     T2 = T2PtrType->getPointeeType();
6022     return true;
6023   }
6024 
6025   const auto *T1MPType = T1->getAs<MemberPointerType>();
6026   const auto *T2MPType = T2->getAs<MemberPointerType>();
6027   if (T1MPType && T2MPType &&
6028       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6029                              QualType(T2MPType->getClass(), 0))) {
6030     T1 = T1MPType->getPointeeType();
6031     T2 = T2MPType->getPointeeType();
6032     return true;
6033   }
6034 
6035   if (getLangOpts().ObjC) {
6036     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6037     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6038     if (T1OPType && T2OPType) {
6039       T1 = T1OPType->getPointeeType();
6040       T2 = T2OPType->getPointeeType();
6041       return true;
6042     }
6043   }
6044 
6045   // FIXME: Block pointers, too?
6046 
6047   return false;
6048 }
6049 
6050 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
6051   while (true) {
6052     Qualifiers Quals;
6053     T1 = getUnqualifiedArrayType(T1, Quals);
6054     T2 = getUnqualifiedArrayType(T2, Quals);
6055     if (hasSameType(T1, T2))
6056       return true;
6057     if (!UnwrapSimilarTypes(T1, T2))
6058       return false;
6059   }
6060 }
6061 
6062 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
6063   while (true) {
6064     Qualifiers Quals1, Quals2;
6065     T1 = getUnqualifiedArrayType(T1, Quals1);
6066     T2 = getUnqualifiedArrayType(T2, Quals2);
6067 
6068     Quals1.removeCVRQualifiers();
6069     Quals2.removeCVRQualifiers();
6070     if (Quals1 != Quals2)
6071       return false;
6072 
6073     if (hasSameType(T1, T2))
6074       return true;
6075 
6076     if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6077       return false;
6078   }
6079 }
6080 
6081 DeclarationNameInfo
6082 ASTContext::getNameForTemplate(TemplateName Name,
6083                                SourceLocation NameLoc) const {
6084   switch (Name.getKind()) {
6085   case TemplateName::QualifiedTemplate:
6086   case TemplateName::Template:
6087     // DNInfo work in progress: CHECKME: what about DNLoc?
6088     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6089                                NameLoc);
6090 
6091   case TemplateName::OverloadedTemplate: {
6092     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6093     // DNInfo work in progress: CHECKME: what about DNLoc?
6094     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6095   }
6096 
6097   case TemplateName::AssumedTemplate: {
6098     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6099     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6100   }
6101 
6102   case TemplateName::DependentTemplate: {
6103     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6104     DeclarationName DName;
6105     if (DTN->isIdentifier()) {
6106       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
6107       return DeclarationNameInfo(DName, NameLoc);
6108     } else {
6109       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
6110       // DNInfo work in progress: FIXME: source locations?
6111       DeclarationNameLoc DNLoc =
6112           DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
6113       return DeclarationNameInfo(DName, NameLoc, DNLoc);
6114     }
6115   }
6116 
6117   case TemplateName::SubstTemplateTemplateParm: {
6118     SubstTemplateTemplateParmStorage *subst
6119       = Name.getAsSubstTemplateTemplateParm();
6120     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6121                                NameLoc);
6122   }
6123 
6124   case TemplateName::SubstTemplateTemplateParmPack: {
6125     SubstTemplateTemplateParmPackStorage *subst
6126       = Name.getAsSubstTemplateTemplateParmPack();
6127     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
6128                                NameLoc);
6129   }
6130   }
6131 
6132   llvm_unreachable("bad template name kind!");
6133 }
6134 
6135 TemplateName
6136 ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
6137   switch (Name.getKind()) {
6138   case TemplateName::QualifiedTemplate:
6139   case TemplateName::Template: {
6140     TemplateDecl *Template = Name.getAsTemplateDecl();
6141     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
6142       Template = getCanonicalTemplateTemplateParmDecl(TTP);
6143 
6144     // The canonical template name is the canonical template declaration.
6145     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6146   }
6147 
6148   case TemplateName::OverloadedTemplate:
6149   case TemplateName::AssumedTemplate:
6150     llvm_unreachable("cannot canonicalize unresolved template");
6151 
6152   case TemplateName::DependentTemplate: {
6153     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6154     assert(DTN && "Non-dependent template names must refer to template decls.");
6155     return DTN->CanonicalTemplateName;
6156   }
6157 
6158   case TemplateName::SubstTemplateTemplateParm: {
6159     SubstTemplateTemplateParmStorage *subst
6160       = Name.getAsSubstTemplateTemplateParm();
6161     return getCanonicalTemplateName(subst->getReplacement());
6162   }
6163 
6164   case TemplateName::SubstTemplateTemplateParmPack: {
6165     SubstTemplateTemplateParmPackStorage *subst
6166                                   = Name.getAsSubstTemplateTemplateParmPack();
6167     TemplateTemplateParmDecl *canonParameter
6168       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
6169     TemplateArgument canonArgPack
6170       = getCanonicalTemplateArgument(subst->getArgumentPack());
6171     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
6172   }
6173   }
6174 
6175   llvm_unreachable("bad template name!");
6176 }
6177 
6178 bool ASTContext::hasSameTemplateName(const TemplateName &X,
6179                                      const TemplateName &Y) const {
6180   return getCanonicalTemplateName(X).getAsVoidPointer() ==
6181          getCanonicalTemplateName(Y).getAsVoidPointer();
6182 }
6183 
6184 bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
6185                                          const NamedDecl *Y) {
6186   if (X->getKind() != Y->getKind())
6187     return false;
6188 
6189   if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6190     auto *TY = cast<TemplateTypeParmDecl>(Y);
6191     if (TX->isParameterPack() != TY->isParameterPack())
6192       return false;
6193     if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6194       return false;
6195     const TypeConstraint *TXTC = TX->getTypeConstraint();
6196     const TypeConstraint *TYTC = TY->getTypeConstraint();
6197     if (!TXTC != !TYTC)
6198       return false;
6199     if (TXTC && TYTC) {
6200       auto *NCX = TXTC->getNamedConcept();
6201       auto *NCY = TYTC->getNamedConcept();
6202       if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6203         return false;
6204       if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
6205         return false;
6206       if (TXTC->hasExplicitTemplateArgs()) {
6207         auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
6208         auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
6209         if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
6210           return false;
6211         llvm::FoldingSetNodeID XID, YID;
6212         for (auto &ArgLoc : TXTCArgs->arguments())
6213           ArgLoc.getArgument().Profile(XID, X->getASTContext());
6214         for (auto &ArgLoc : TYTCArgs->arguments())
6215           ArgLoc.getArgument().Profile(YID, Y->getASTContext());
6216         if (XID != YID)
6217           return false;
6218       }
6219     }
6220     return true;
6221   }
6222 
6223   if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6224     auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6225     return TX->isParameterPack() == TY->isParameterPack() &&
6226            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
6227   }
6228 
6229   auto *TX = cast<TemplateTemplateParmDecl>(X);
6230   auto *TY = cast<TemplateTemplateParmDecl>(Y);
6231   return TX->isParameterPack() == TY->isParameterPack() &&
6232          isSameTemplateParameterList(TX->getTemplateParameters(),
6233                                      TY->getTemplateParameters());
6234 }
6235 
6236 bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X,
6237                                              const TemplateParameterList *Y) {
6238   if (X->size() != Y->size())
6239     return false;
6240 
6241   for (unsigned I = 0, N = X->size(); I != N; ++I)
6242     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6243       return false;
6244 
6245   const Expr *XRC = X->getRequiresClause();
6246   const Expr *YRC = Y->getRequiresClause();
6247   if (!XRC != !YRC)
6248     return false;
6249   if (XRC) {
6250     llvm::FoldingSetNodeID XRCID, YRCID;
6251     XRC->Profile(XRCID, *this, /*Canonical=*/true);
6252     YRC->Profile(YRCID, *this, /*Canonical=*/true);
6253     if (XRCID != YRCID)
6254       return false;
6255   }
6256 
6257   return true;
6258 }
6259 
6260 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
6261   if (auto *NS = X->getAsNamespace())
6262     return NS;
6263   if (auto *NAS = X->getAsNamespaceAlias())
6264     return NAS->getNamespace();
6265   return nullptr;
6266 }
6267 
6268 static bool isSameQualifier(const NestedNameSpecifier *X,
6269                             const NestedNameSpecifier *Y) {
6270   if (auto *NSX = getNamespace(X)) {
6271     auto *NSY = getNamespace(Y);
6272     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6273       return false;
6274   } else if (X->getKind() != Y->getKind())
6275     return false;
6276 
6277   // FIXME: For namespaces and types, we're permitted to check that the entity
6278   // is named via the same tokens. We should probably do so.
6279   switch (X->getKind()) {
6280   case NestedNameSpecifier::Identifier:
6281     if (X->getAsIdentifier() != Y->getAsIdentifier())
6282       return false;
6283     break;
6284   case NestedNameSpecifier::Namespace:
6285   case NestedNameSpecifier::NamespaceAlias:
6286     // We've already checked that we named the same namespace.
6287     break;
6288   case NestedNameSpecifier::TypeSpec:
6289   case NestedNameSpecifier::TypeSpecWithTemplate:
6290     if (X->getAsType()->getCanonicalTypeInternal() !=
6291         Y->getAsType()->getCanonicalTypeInternal())
6292       return false;
6293     break;
6294   case NestedNameSpecifier::Global:
6295   case NestedNameSpecifier::Super:
6296     return true;
6297   }
6298 
6299   // Recurse into earlier portion of NNS, if any.
6300   auto *PX = X->getPrefix();
6301   auto *PY = Y->getPrefix();
6302   if (PX && PY)
6303     return isSameQualifier(PX, PY);
6304   return !PX && !PY;
6305 }
6306 
6307 /// Determine whether the attributes we can overload on are identical for A and
6308 /// B. Will ignore any overloadable attrs represented in the type of A and B.
6309 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
6310                                      const FunctionDecl *B) {
6311   // Note that pass_object_size attributes are represented in the function's
6312   // ExtParameterInfo, so we don't need to check them here.
6313 
6314   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6315   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6316   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6317 
6318   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6319     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6320     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6321 
6322     // Return false if the number of enable_if attributes is different.
6323     if (!Cand1A || !Cand2A)
6324       return false;
6325 
6326     Cand1ID.clear();
6327     Cand2ID.clear();
6328 
6329     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6330     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6331 
6332     // Return false if any of the enable_if expressions of A and B are
6333     // different.
6334     if (Cand1ID != Cand2ID)
6335       return false;
6336   }
6337   return true;
6338 }
6339 
6340 bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) {
6341   if (X == Y)
6342     return true;
6343 
6344   if (X->getDeclName() != Y->getDeclName())
6345     return false;
6346 
6347   // Must be in the same context.
6348   //
6349   // Note that we can't use DeclContext::Equals here, because the DeclContexts
6350   // could be two different declarations of the same function. (We will fix the
6351   // semantic DC to refer to the primary definition after merging.)
6352   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6353                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6354     return false;
6355 
6356   // Two typedefs refer to the same entity if they have the same underlying
6357   // type.
6358   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6359     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6360       return hasSameType(TypedefX->getUnderlyingType(),
6361                          TypedefY->getUnderlyingType());
6362 
6363   // Must have the same kind.
6364   if (X->getKind() != Y->getKind())
6365     return false;
6366 
6367   // Objective-C classes and protocols with the same name always match.
6368   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6369     return true;
6370 
6371   if (isa<ClassTemplateSpecializationDecl>(X)) {
6372     // No need to handle these here: we merge them when adding them to the
6373     // template.
6374     return false;
6375   }
6376 
6377   // Compatible tags match.
6378   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6379     const auto *TagY = cast<TagDecl>(Y);
6380     return (TagX->getTagKind() == TagY->getTagKind()) ||
6381            ((TagX->getTagKind() == TTK_Struct ||
6382              TagX->getTagKind() == TTK_Class ||
6383              TagX->getTagKind() == TTK_Interface) &&
6384             (TagY->getTagKind() == TTK_Struct ||
6385              TagY->getTagKind() == TTK_Class ||
6386              TagY->getTagKind() == TTK_Interface));
6387   }
6388 
6389   // Functions with the same type and linkage match.
6390   // FIXME: This needs to cope with merging of prototyped/non-prototyped
6391   // functions, etc.
6392   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6393     const auto *FuncY = cast<FunctionDecl>(Y);
6394     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6395       const auto *CtorY = cast<CXXConstructorDecl>(Y);
6396       if (CtorX->getInheritedConstructor() &&
6397           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6398                         CtorY->getInheritedConstructor().getConstructor()))
6399         return false;
6400     }
6401 
6402     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6403       return false;
6404 
6405     // Multiversioned functions with different feature strings are represented
6406     // as separate declarations.
6407     if (FuncX->isMultiVersion()) {
6408       const auto *TAX = FuncX->getAttr<TargetAttr>();
6409       const auto *TAY = FuncY->getAttr<TargetAttr>();
6410       assert(TAX && TAY && "Multiversion Function without target attribute");
6411 
6412       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6413         return false;
6414     }
6415 
6416     const Expr *XRC = FuncX->getTrailingRequiresClause();
6417     const Expr *YRC = FuncY->getTrailingRequiresClause();
6418     if (!XRC != !YRC)
6419       return false;
6420     if (XRC) {
6421       llvm::FoldingSetNodeID XRCID, YRCID;
6422       XRC->Profile(XRCID, *this, /*Canonical=*/true);
6423       YRC->Profile(YRCID, *this, /*Canonical=*/true);
6424       if (XRCID != YRCID)
6425         return false;
6426     }
6427 
6428     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6429       // Map to the first declaration that we've already merged into this one.
6430       // The TSI of redeclarations might not match (due to calling conventions
6431       // being inherited onto the type but not the TSI), but the TSI type of
6432       // the first declaration of the function should match across modules.
6433       FD = FD->getCanonicalDecl();
6434       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6435                                      : FD->getType();
6436     };
6437     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6438     if (!hasSameType(XT, YT)) {
6439       // We can get functions with different types on the redecl chain in C++17
6440       // if they have differing exception specifications and at least one of
6441       // the excpetion specs is unresolved.
6442       auto *XFPT = XT->getAs<FunctionProtoType>();
6443       auto *YFPT = YT->getAs<FunctionProtoType>();
6444       if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6445           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6446            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
6447           // FIXME: We could make isSameEntity const after we make
6448           // hasSameFunctionTypeIgnoringExceptionSpec const.
6449           hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
6450         return true;
6451       return false;
6452     }
6453 
6454     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6455            hasSameOverloadableAttrs(FuncX, FuncY);
6456   }
6457 
6458   // Variables with the same type and linkage match.
6459   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6460     const auto *VarY = cast<VarDecl>(Y);
6461     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6462       if (hasSameType(VarX->getType(), VarY->getType()))
6463         return true;
6464 
6465       // We can get decls with different types on the redecl chain. Eg.
6466       // template <typename T> struct S { static T Var[]; }; // #1
6467       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6468       // Only? happens when completing an incomplete array type. In this case
6469       // when comparing #1 and #2 we should go through their element type.
6470       const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6471       const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6472       if (!VarXTy || !VarYTy)
6473         return false;
6474       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6475         return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6476     }
6477     return false;
6478   }
6479 
6480   // Namespaces with the same name and inlinedness match.
6481   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6482     const auto *NamespaceY = cast<NamespaceDecl>(Y);
6483     return NamespaceX->isInline() == NamespaceY->isInline();
6484   }
6485 
6486   // Identical template names and kinds match if their template parameter lists
6487   // and patterns match.
6488   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6489     const auto *TemplateY = cast<TemplateDecl>(Y);
6490     return isSameEntity(TemplateX->getTemplatedDecl(),
6491                         TemplateY->getTemplatedDecl()) &&
6492            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6493                                        TemplateY->getTemplateParameters());
6494   }
6495 
6496   // Fields with the same name and the same type match.
6497   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6498     const auto *FDY = cast<FieldDecl>(Y);
6499     // FIXME: Also check the bitwidth is odr-equivalent, if any.
6500     return hasSameType(FDX->getType(), FDY->getType());
6501   }
6502 
6503   // Indirect fields with the same target field match.
6504   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6505     const auto *IFDY = cast<IndirectFieldDecl>(Y);
6506     return IFDX->getAnonField()->getCanonicalDecl() ==
6507            IFDY->getAnonField()->getCanonicalDecl();
6508   }
6509 
6510   // Enumerators with the same name match.
6511   if (isa<EnumConstantDecl>(X))
6512     // FIXME: Also check the value is odr-equivalent.
6513     return true;
6514 
6515   // Using shadow declarations with the same target match.
6516   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6517     const auto *USY = cast<UsingShadowDecl>(Y);
6518     return USX->getTargetDecl() == USY->getTargetDecl();
6519   }
6520 
6521   // Using declarations with the same qualifier match. (We already know that
6522   // the name matches.)
6523   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6524     const auto *UY = cast<UsingDecl>(Y);
6525     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6526            UX->hasTypename() == UY->hasTypename() &&
6527            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6528   }
6529   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6530     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6531     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6532            UX->isAccessDeclaration() == UY->isAccessDeclaration();
6533   }
6534   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6535     return isSameQualifier(
6536         UX->getQualifier(),
6537         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6538   }
6539 
6540   // Using-pack declarations are only created by instantiation, and match if
6541   // they're instantiated from matching UnresolvedUsing...Decls.
6542   if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6543     return declaresSameEntity(
6544         UX->getInstantiatedFromUsingDecl(),
6545         cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6546   }
6547 
6548   // Namespace alias definitions with the same target match.
6549   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6550     const auto *NAY = cast<NamespaceAliasDecl>(Y);
6551     return NAX->getNamespace()->Equals(NAY->getNamespace());
6552   }
6553 
6554   return false;
6555 }
6556 
6557 TemplateArgument
6558 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
6559   switch (Arg.getKind()) {
6560     case TemplateArgument::Null:
6561       return Arg;
6562 
6563     case TemplateArgument::Expression:
6564       return Arg;
6565 
6566     case TemplateArgument::Declaration: {
6567       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6568       return TemplateArgument(D, Arg.getParamTypeForDecl());
6569     }
6570 
6571     case TemplateArgument::NullPtr:
6572       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
6573                               /*isNullPtr*/true);
6574 
6575     case TemplateArgument::Template:
6576       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
6577 
6578     case TemplateArgument::TemplateExpansion:
6579       return TemplateArgument(getCanonicalTemplateName(
6580                                          Arg.getAsTemplateOrTemplatePattern()),
6581                               Arg.getNumTemplateExpansions());
6582 
6583     case TemplateArgument::Integral:
6584       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
6585 
6586     case TemplateArgument::Type:
6587       return TemplateArgument(getCanonicalType(Arg.getAsType()));
6588 
6589     case TemplateArgument::Pack: {
6590       if (Arg.pack_size() == 0)
6591         return Arg;
6592 
6593       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
6594       unsigned Idx = 0;
6595       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
6596                                         AEnd = Arg.pack_end();
6597            A != AEnd; (void)++A, ++Idx)
6598         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
6599 
6600       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
6601     }
6602   }
6603 
6604   // Silence GCC warning
6605   llvm_unreachable("Unhandled template argument kind");
6606 }
6607 
6608 NestedNameSpecifier *
6609 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6610   if (!NNS)
6611     return nullptr;
6612 
6613   switch (NNS->getKind()) {
6614   case NestedNameSpecifier::Identifier:
6615     // Canonicalize the prefix but keep the identifier the same.
6616     return NestedNameSpecifier::Create(*this,
6617                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6618                                        NNS->getAsIdentifier());
6619 
6620   case NestedNameSpecifier::Namespace:
6621     // A namespace is canonical; build a nested-name-specifier with
6622     // this namespace and no prefix.
6623     return NestedNameSpecifier::Create(*this, nullptr,
6624                                  NNS->getAsNamespace()->getOriginalNamespace());
6625 
6626   case NestedNameSpecifier::NamespaceAlias:
6627     // A namespace is canonical; build a nested-name-specifier with
6628     // this namespace and no prefix.
6629     return NestedNameSpecifier::Create(*this, nullptr,
6630                                     NNS->getAsNamespaceAlias()->getNamespace()
6631                                                       ->getOriginalNamespace());
6632 
6633   // The difference between TypeSpec and TypeSpecWithTemplate is that the
6634   // latter will have the 'template' keyword when printed.
6635   case NestedNameSpecifier::TypeSpec:
6636   case NestedNameSpecifier::TypeSpecWithTemplate: {
6637     const Type *T = getCanonicalType(NNS->getAsType());
6638 
6639     // If we have some kind of dependent-named type (e.g., "typename T::type"),
6640     // break it apart into its prefix and identifier, then reconsititute those
6641     // as the canonical nested-name-specifier. This is required to canonicalize
6642     // a dependent nested-name-specifier involving typedefs of dependent-name
6643     // types, e.g.,
6644     //   typedef typename T::type T1;
6645     //   typedef typename T1::type T2;
6646     if (const auto *DNT = T->getAs<DependentNameType>())
6647       return NestedNameSpecifier::Create(
6648           *this, DNT->getQualifier(),
6649           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6650     if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6651       return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6652                                          const_cast<Type *>(T));
6653 
6654     // TODO: Set 'Template' parameter to true for other template types.
6655     return NestedNameSpecifier::Create(*this, nullptr, false,
6656                                        const_cast<Type *>(T));
6657   }
6658 
6659   case NestedNameSpecifier::Global:
6660   case NestedNameSpecifier::Super:
6661     // The global specifier and __super specifer are canonical and unique.
6662     return NNS;
6663   }
6664 
6665   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6666 }
6667 
6668 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6669   // Handle the non-qualified case efficiently.
6670   if (!T.hasLocalQualifiers()) {
6671     // Handle the common positive case fast.
6672     if (const auto *AT = dyn_cast<ArrayType>(T))
6673       return AT;
6674   }
6675 
6676   // Handle the common negative case fast.
6677   if (!isa<ArrayType>(T.getCanonicalType()))
6678     return nullptr;
6679 
6680   // Apply any qualifiers from the array type to the element type.  This
6681   // implements C99 6.7.3p8: "If the specification of an array type includes
6682   // any type qualifiers, the element type is so qualified, not the array type."
6683 
6684   // If we get here, we either have type qualifiers on the type, or we have
6685   // sugar such as a typedef in the way.  If we have type qualifiers on the type
6686   // we must propagate them down into the element type.
6687 
6688   SplitQualType split = T.getSplitDesugaredType();
6689   Qualifiers qs = split.Quals;
6690 
6691   // If we have a simple case, just return now.
6692   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6693   if (!ATy || qs.empty())
6694     return ATy;
6695 
6696   // Otherwise, we have an array and we have qualifiers on it.  Push the
6697   // qualifiers into the array element type and return a new array type.
6698   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6699 
6700   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6701     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6702                                                 CAT->getSizeExpr(),
6703                                                 CAT->getSizeModifier(),
6704                                            CAT->getIndexTypeCVRQualifiers()));
6705   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6706     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6707                                                   IAT->getSizeModifier(),
6708                                            IAT->getIndexTypeCVRQualifiers()));
6709 
6710   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6711     return cast<ArrayType>(
6712                      getDependentSizedArrayType(NewEltTy,
6713                                                 DSAT->getSizeExpr(),
6714                                                 DSAT->getSizeModifier(),
6715                                               DSAT->getIndexTypeCVRQualifiers(),
6716                                                 DSAT->getBracketsRange()));
6717 
6718   const auto *VAT = cast<VariableArrayType>(ATy);
6719   return cast<ArrayType>(getVariableArrayType(NewEltTy,
6720                                               VAT->getSizeExpr(),
6721                                               VAT->getSizeModifier(),
6722                                               VAT->getIndexTypeCVRQualifiers(),
6723                                               VAT->getBracketsRange()));
6724 }
6725 
6726 QualType ASTContext::getAdjustedParameterType(QualType T) const {
6727   if (T->isArrayType() || T->isFunctionType())
6728     return getDecayedType(T);
6729   return T;
6730 }
6731 
6732 QualType ASTContext::getSignatureParameterType(QualType T) const {
6733   T = getVariableArrayDecayedType(T);
6734   T = getAdjustedParameterType(T);
6735   return T.getUnqualifiedType();
6736 }
6737 
6738 QualType ASTContext::getExceptionObjectType(QualType T) const {
6739   // C++ [except.throw]p3:
6740   //   A throw-expression initializes a temporary object, called the exception
6741   //   object, the type of which is determined by removing any top-level
6742   //   cv-qualifiers from the static type of the operand of throw and adjusting
6743   //   the type from "array of T" or "function returning T" to "pointer to T"
6744   //   or "pointer to function returning T", [...]
6745   T = getVariableArrayDecayedType(T);
6746   if (T->isArrayType() || T->isFunctionType())
6747     T = getDecayedType(T);
6748   return T.getUnqualifiedType();
6749 }
6750 
6751 /// getArrayDecayedType - Return the properly qualified result of decaying the
6752 /// specified array type to a pointer.  This operation is non-trivial when
6753 /// handling typedefs etc.  The canonical type of "T" must be an array type,
6754 /// this returns a pointer to a properly qualified element of the array.
6755 ///
6756 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6757 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6758   // Get the element type with 'getAsArrayType' so that we don't lose any
6759   // typedefs in the element type of the array.  This also handles propagation
6760   // of type qualifiers from the array type into the element type if present
6761   // (C99 6.7.3p8).
6762   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6763   assert(PrettyArrayType && "Not an array type!");
6764 
6765   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6766 
6767   // int x[restrict 4] ->  int *restrict
6768   QualType Result = getQualifiedType(PtrTy,
6769                                      PrettyArrayType->getIndexTypeQualifiers());
6770 
6771   // int x[_Nullable] -> int * _Nullable
6772   if (auto Nullability = Ty->getNullability(*this)) {
6773     Result = const_cast<ASTContext *>(this)->getAttributedType(
6774         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6775   }
6776   return Result;
6777 }
6778 
6779 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6780   return getBaseElementType(array->getElementType());
6781 }
6782 
6783 QualType ASTContext::getBaseElementType(QualType type) const {
6784   Qualifiers qs;
6785   while (true) {
6786     SplitQualType split = type.getSplitDesugaredType();
6787     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6788     if (!array) break;
6789 
6790     type = array->getElementType();
6791     qs.addConsistentQualifiers(split.Quals);
6792   }
6793 
6794   return getQualifiedType(type, qs);
6795 }
6796 
6797 /// getConstantArrayElementCount - Returns number of constant array elements.
6798 uint64_t
6799 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6800   uint64_t ElementCount = 1;
6801   do {
6802     ElementCount *= CA->getSize().getZExtValue();
6803     CA = dyn_cast_or_null<ConstantArrayType>(
6804       CA->getElementType()->getAsArrayTypeUnsafe());
6805   } while (CA);
6806   return ElementCount;
6807 }
6808 
6809 /// getFloatingRank - Return a relative rank for floating point types.
6810 /// This routine will assert if passed a built-in type that isn't a float.
6811 static FloatingRank getFloatingRank(QualType T) {
6812   if (const auto *CT = T->getAs<ComplexType>())
6813     return getFloatingRank(CT->getElementType());
6814 
6815   switch (T->castAs<BuiltinType>()->getKind()) {
6816   default: llvm_unreachable("getFloatingRank(): not a floating type");
6817   case BuiltinType::Float16:    return Float16Rank;
6818   case BuiltinType::Half:       return HalfRank;
6819   case BuiltinType::Float:      return FloatRank;
6820   case BuiltinType::Double:     return DoubleRank;
6821   case BuiltinType::LongDouble: return LongDoubleRank;
6822   case BuiltinType::Float128:   return Float128Rank;
6823   case BuiltinType::BFloat16:   return BFloat16Rank;
6824   case BuiltinType::Ibm128:     return Ibm128Rank;
6825   }
6826 }
6827 
6828 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6829 /// point types, ignoring the domain of the type (i.e. 'double' ==
6830 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6831 /// LHS < RHS, return -1.
6832 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6833   FloatingRank LHSR = getFloatingRank(LHS);
6834   FloatingRank RHSR = getFloatingRank(RHS);
6835 
6836   if (LHSR == RHSR)
6837     return 0;
6838   if (LHSR > RHSR)
6839     return 1;
6840   return -1;
6841 }
6842 
6843 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6844   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6845     return 0;
6846   return getFloatingTypeOrder(LHS, RHS);
6847 }
6848 
6849 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6850 /// routine will assert if passed a built-in type that isn't an integer or enum,
6851 /// or if it is not canonicalized.
6852 unsigned ASTContext::getIntegerRank(const Type *T) const {
6853   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6854 
6855   // Results in this 'losing' to any type of the same size, but winning if
6856   // larger.
6857   if (const auto *EIT = dyn_cast<BitIntType>(T))
6858     return 0 + (EIT->getNumBits() << 3);
6859 
6860   switch (cast<BuiltinType>(T)->getKind()) {
6861   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6862   case BuiltinType::Bool:
6863     return 1 + (getIntWidth(BoolTy) << 3);
6864   case BuiltinType::Char_S:
6865   case BuiltinType::Char_U:
6866   case BuiltinType::SChar:
6867   case BuiltinType::UChar:
6868     return 2 + (getIntWidth(CharTy) << 3);
6869   case BuiltinType::Short:
6870   case BuiltinType::UShort:
6871     return 3 + (getIntWidth(ShortTy) << 3);
6872   case BuiltinType::Int:
6873   case BuiltinType::UInt:
6874     return 4 + (getIntWidth(IntTy) << 3);
6875   case BuiltinType::Long:
6876   case BuiltinType::ULong:
6877     return 5 + (getIntWidth(LongTy) << 3);
6878   case BuiltinType::LongLong:
6879   case BuiltinType::ULongLong:
6880     return 6 + (getIntWidth(LongLongTy) << 3);
6881   case BuiltinType::Int128:
6882   case BuiltinType::UInt128:
6883     return 7 + (getIntWidth(Int128Ty) << 3);
6884   }
6885 }
6886 
6887 /// Whether this is a promotable bitfield reference according
6888 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6889 ///
6890 /// \returns the type this bit-field will promote to, or NULL if no
6891 /// promotion occurs.
6892 QualType ASTContext::isPromotableBitField(Expr *E) const {
6893   if (E->isTypeDependent() || E->isValueDependent())
6894     return {};
6895 
6896   // C++ [conv.prom]p5:
6897   //    If the bit-field has an enumerated type, it is treated as any other
6898   //    value of that type for promotion purposes.
6899   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6900     return {};
6901 
6902   // FIXME: We should not do this unless E->refersToBitField() is true. This
6903   // matters in C where getSourceBitField() will find bit-fields for various
6904   // cases where the source expression is not a bit-field designator.
6905 
6906   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6907   if (!Field)
6908     return {};
6909 
6910   QualType FT = Field->getType();
6911 
6912   uint64_t BitWidth = Field->getBitWidthValue(*this);
6913   uint64_t IntSize = getTypeSize(IntTy);
6914   // C++ [conv.prom]p5:
6915   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6916   //   int if int can represent all the values of the bit-field; otherwise, it
6917   //   can be converted to unsigned int if unsigned int can represent all the
6918   //   values of the bit-field. If the bit-field is larger yet, no integral
6919   //   promotion applies to it.
6920   // C11 6.3.1.1/2:
6921   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6922   //   If an int can represent all values of the original type (as restricted by
6923   //   the width, for a bit-field), the value is converted to an int; otherwise,
6924   //   it is converted to an unsigned int.
6925   //
6926   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6927   //        We perform that promotion here to match GCC and C++.
6928   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6929   //        greater than that of 'int'. We perform that promotion to match GCC.
6930   if (BitWidth < IntSize)
6931     return IntTy;
6932 
6933   if (BitWidth == IntSize)
6934     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6935 
6936   // Bit-fields wider than int are not subject to promotions, and therefore act
6937   // like the base type. GCC has some weird bugs in this area that we
6938   // deliberately do not follow (GCC follows a pre-standard resolution to
6939   // C's DR315 which treats bit-width as being part of the type, and this leaks
6940   // into their semantics in some cases).
6941   return {};
6942 }
6943 
6944 /// getPromotedIntegerType - Returns the type that Promotable will
6945 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6946 /// integer type.
6947 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6948   assert(!Promotable.isNull());
6949   assert(Promotable->isPromotableIntegerType());
6950   if (const auto *ET = Promotable->getAs<EnumType>())
6951     return ET->getDecl()->getPromotionType();
6952 
6953   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6954     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6955     // (3.9.1) can be converted to a prvalue of the first of the following
6956     // types that can represent all the values of its underlying type:
6957     // int, unsigned int, long int, unsigned long int, long long int, or
6958     // unsigned long long int [...]
6959     // FIXME: Is there some better way to compute this?
6960     if (BT->getKind() == BuiltinType::WChar_S ||
6961         BT->getKind() == BuiltinType::WChar_U ||
6962         BT->getKind() == BuiltinType::Char8 ||
6963         BT->getKind() == BuiltinType::Char16 ||
6964         BT->getKind() == BuiltinType::Char32) {
6965       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6966       uint64_t FromSize = getTypeSize(BT);
6967       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6968                                   LongLongTy, UnsignedLongLongTy };
6969       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6970         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6971         if (FromSize < ToSize ||
6972             (FromSize == ToSize &&
6973              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6974           return PromoteTypes[Idx];
6975       }
6976       llvm_unreachable("char type should fit into long long");
6977     }
6978   }
6979 
6980   // At this point, we should have a signed or unsigned integer type.
6981   if (Promotable->isSignedIntegerType())
6982     return IntTy;
6983   uint64_t PromotableSize = getIntWidth(Promotable);
6984   uint64_t IntSize = getIntWidth(IntTy);
6985   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6986   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6987 }
6988 
6989 /// Recurses in pointer/array types until it finds an objc retainable
6990 /// type and returns its ownership.
6991 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6992   while (!T.isNull()) {
6993     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6994       return T.getObjCLifetime();
6995     if (T->isArrayType())
6996       T = getBaseElementType(T);
6997     else if (const auto *PT = T->getAs<PointerType>())
6998       T = PT->getPointeeType();
6999     else if (const auto *RT = T->getAs<ReferenceType>())
7000       T = RT->getPointeeType();
7001     else
7002       break;
7003   }
7004 
7005   return Qualifiers::OCL_None;
7006 }
7007 
7008 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7009   // Incomplete enum types are not treated as integer types.
7010   // FIXME: In C++, enum types are never integer types.
7011   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7012     return ET->getDecl()->getIntegerType().getTypePtr();
7013   return nullptr;
7014 }
7015 
7016 /// getIntegerTypeOrder - Returns the highest ranked integer type:
7017 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7018 /// LHS < RHS, return -1.
7019 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
7020   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7021   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7022 
7023   // Unwrap enums to their underlying type.
7024   if (const auto *ET = dyn_cast<EnumType>(LHSC))
7025     LHSC = getIntegerTypeForEnum(ET);
7026   if (const auto *ET = dyn_cast<EnumType>(RHSC))
7027     RHSC = getIntegerTypeForEnum(ET);
7028 
7029   if (LHSC == RHSC) return 0;
7030 
7031   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7032   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7033 
7034   unsigned LHSRank = getIntegerRank(LHSC);
7035   unsigned RHSRank = getIntegerRank(RHSC);
7036 
7037   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
7038     if (LHSRank == RHSRank) return 0;
7039     return LHSRank > RHSRank ? 1 : -1;
7040   }
7041 
7042   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7043   if (LHSUnsigned) {
7044     // If the unsigned [LHS] type is larger, return it.
7045     if (LHSRank >= RHSRank)
7046       return 1;
7047 
7048     // If the signed type can represent all values of the unsigned type, it
7049     // wins.  Because we are dealing with 2's complement and types that are
7050     // powers of two larger than each other, this is always safe.
7051     return -1;
7052   }
7053 
7054   // If the unsigned [RHS] type is larger, return it.
7055   if (RHSRank >= LHSRank)
7056     return -1;
7057 
7058   // If the signed type can represent all values of the unsigned type, it
7059   // wins.  Because we are dealing with 2's complement and types that are
7060   // powers of two larger than each other, this is always safe.
7061   return 1;
7062 }
7063 
7064 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
7065   if (CFConstantStringTypeDecl)
7066     return CFConstantStringTypeDecl;
7067 
7068   assert(!CFConstantStringTagDecl &&
7069          "tag and typedef should be initialized together");
7070   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7071   CFConstantStringTagDecl->startDefinition();
7072 
7073   struct {
7074     QualType Type;
7075     const char *Name;
7076   } Fields[5];
7077   unsigned Count = 0;
7078 
7079   /// Objective-C ABI
7080   ///
7081   ///    typedef struct __NSConstantString_tag {
7082   ///      const int *isa;
7083   ///      int flags;
7084   ///      const char *str;
7085   ///      long length;
7086   ///    } __NSConstantString;
7087   ///
7088   /// Swift ABI (4.1, 4.2)
7089   ///
7090   ///    typedef struct __NSConstantString_tag {
7091   ///      uintptr_t _cfisa;
7092   ///      uintptr_t _swift_rc;
7093   ///      _Atomic(uint64_t) _cfinfoa;
7094   ///      const char *_ptr;
7095   ///      uint32_t _length;
7096   ///    } __NSConstantString;
7097   ///
7098   /// Swift ABI (5.0)
7099   ///
7100   ///    typedef struct __NSConstantString_tag {
7101   ///      uintptr_t _cfisa;
7102   ///      uintptr_t _swift_rc;
7103   ///      _Atomic(uint64_t) _cfinfoa;
7104   ///      const char *_ptr;
7105   ///      uintptr_t _length;
7106   ///    } __NSConstantString;
7107 
7108   const auto CFRuntime = getLangOpts().CFRuntime;
7109   if (static_cast<unsigned>(CFRuntime) <
7110       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7111     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7112     Fields[Count++] = { IntTy, "flags" };
7113     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7114     Fields[Count++] = { LongTy, "length" };
7115   } else {
7116     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7117     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7118     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7119     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7120     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
7121         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
7122       Fields[Count++] = { IntTy, "_ptr" };
7123     else
7124       Fields[Count++] = { getUIntPtrType(), "_ptr" };
7125   }
7126 
7127   // Create fields
7128   for (unsigned i = 0; i < Count; ++i) {
7129     FieldDecl *Field =
7130         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7131                           SourceLocation(), &Idents.get(Fields[i].Name),
7132                           Fields[i].Type, /*TInfo=*/nullptr,
7133                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7134     Field->setAccess(AS_public);
7135     CFConstantStringTagDecl->addDecl(Field);
7136   }
7137 
7138   CFConstantStringTagDecl->completeDefinition();
7139   // This type is designed to be compatible with NSConstantString, but cannot
7140   // use the same name, since NSConstantString is an interface.
7141   auto tagType = getTagDeclType(CFConstantStringTagDecl);
7142   CFConstantStringTypeDecl =
7143       buildImplicitTypedef(tagType, "__NSConstantString");
7144 
7145   return CFConstantStringTypeDecl;
7146 }
7147 
7148 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
7149   if (!CFConstantStringTagDecl)
7150     getCFConstantStringDecl(); // Build the tag and the typedef.
7151   return CFConstantStringTagDecl;
7152 }
7153 
7154 // getCFConstantStringType - Return the type used for constant CFStrings.
7155 QualType ASTContext::getCFConstantStringType() const {
7156   return getTypedefType(getCFConstantStringDecl());
7157 }
7158 
7159 QualType ASTContext::getObjCSuperType() const {
7160   if (ObjCSuperType.isNull()) {
7161     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7162     getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7163     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7164   }
7165   return ObjCSuperType;
7166 }
7167 
7168 void ASTContext::setCFConstantStringType(QualType T) {
7169   const auto *TD = T->castAs<TypedefType>();
7170   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7171   const auto *TagType =
7172       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7173   CFConstantStringTagDecl = TagType->getDecl();
7174 }
7175 
7176 QualType ASTContext::getBlockDescriptorType() const {
7177   if (BlockDescriptorType)
7178     return getTagDeclType(BlockDescriptorType);
7179 
7180   RecordDecl *RD;
7181   // FIXME: Needs the FlagAppleBlock bit.
7182   RD = buildImplicitRecord("__block_descriptor");
7183   RD->startDefinition();
7184 
7185   QualType FieldTypes[] = {
7186     UnsignedLongTy,
7187     UnsignedLongTy,
7188   };
7189 
7190   static const char *const FieldNames[] = {
7191     "reserved",
7192     "Size"
7193   };
7194 
7195   for (size_t i = 0; i < 2; ++i) {
7196     FieldDecl *Field = FieldDecl::Create(
7197         *this, RD, SourceLocation(), SourceLocation(),
7198         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7199         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7200     Field->setAccess(AS_public);
7201     RD->addDecl(Field);
7202   }
7203 
7204   RD->completeDefinition();
7205 
7206   BlockDescriptorType = RD;
7207 
7208   return getTagDeclType(BlockDescriptorType);
7209 }
7210 
7211 QualType ASTContext::getBlockDescriptorExtendedType() const {
7212   if (BlockDescriptorExtendedType)
7213     return getTagDeclType(BlockDescriptorExtendedType);
7214 
7215   RecordDecl *RD;
7216   // FIXME: Needs the FlagAppleBlock bit.
7217   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7218   RD->startDefinition();
7219 
7220   QualType FieldTypes[] = {
7221     UnsignedLongTy,
7222     UnsignedLongTy,
7223     getPointerType(VoidPtrTy),
7224     getPointerType(VoidPtrTy)
7225   };
7226 
7227   static const char *const FieldNames[] = {
7228     "reserved",
7229     "Size",
7230     "CopyFuncPtr",
7231     "DestroyFuncPtr"
7232   };
7233 
7234   for (size_t i = 0; i < 4; ++i) {
7235     FieldDecl *Field = FieldDecl::Create(
7236         *this, RD, SourceLocation(), SourceLocation(),
7237         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7238         /*BitWidth=*/nullptr,
7239         /*Mutable=*/false, ICIS_NoInit);
7240     Field->setAccess(AS_public);
7241     RD->addDecl(Field);
7242   }
7243 
7244   RD->completeDefinition();
7245 
7246   BlockDescriptorExtendedType = RD;
7247   return getTagDeclType(BlockDescriptorExtendedType);
7248 }
7249 
7250 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
7251   const auto *BT = dyn_cast<BuiltinType>(T);
7252 
7253   if (!BT) {
7254     if (isa<PipeType>(T))
7255       return OCLTK_Pipe;
7256 
7257     return OCLTK_Default;
7258   }
7259 
7260   switch (BT->getKind()) {
7261 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
7262   case BuiltinType::Id:                                                        \
7263     return OCLTK_Image;
7264 #include "clang/Basic/OpenCLImageTypes.def"
7265 
7266   case BuiltinType::OCLClkEvent:
7267     return OCLTK_ClkEvent;
7268 
7269   case BuiltinType::OCLEvent:
7270     return OCLTK_Event;
7271 
7272   case BuiltinType::OCLQueue:
7273     return OCLTK_Queue;
7274 
7275   case BuiltinType::OCLReserveID:
7276     return OCLTK_ReserveID;
7277 
7278   case BuiltinType::OCLSampler:
7279     return OCLTK_Sampler;
7280 
7281   default:
7282     return OCLTK_Default;
7283   }
7284 }
7285 
7286 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
7287   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7288 }
7289 
7290 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7291 /// requires copy/dispose. Note that this must match the logic
7292 /// in buildByrefHelpers.
7293 bool ASTContext::BlockRequiresCopying(QualType Ty,
7294                                       const VarDecl *D) {
7295   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7296     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7297     if (!copyExpr && record->hasTrivialDestructor()) return false;
7298 
7299     return true;
7300   }
7301 
7302   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7303   // move or destroy.
7304   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
7305     return true;
7306 
7307   if (!Ty->isObjCRetainableType()) return false;
7308 
7309   Qualifiers qs = Ty.getQualifiers();
7310 
7311   // If we have lifetime, that dominates.
7312   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7313     switch (lifetime) {
7314       case Qualifiers::OCL_None: llvm_unreachable("impossible");
7315 
7316       // These are just bits as far as the runtime is concerned.
7317       case Qualifiers::OCL_ExplicitNone:
7318       case Qualifiers::OCL_Autoreleasing:
7319         return false;
7320 
7321       // These cases should have been taken care of when checking the type's
7322       // non-triviality.
7323       case Qualifiers::OCL_Weak:
7324       case Qualifiers::OCL_Strong:
7325         llvm_unreachable("impossible");
7326     }
7327     llvm_unreachable("fell out of lifetime switch!");
7328   }
7329   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7330           Ty->isObjCObjectPointerType());
7331 }
7332 
7333 bool ASTContext::getByrefLifetime(QualType Ty,
7334                               Qualifiers::ObjCLifetime &LifeTime,
7335                               bool &HasByrefExtendedLayout) const {
7336   if (!getLangOpts().ObjC ||
7337       getLangOpts().getGC() != LangOptions::NonGC)
7338     return false;
7339 
7340   HasByrefExtendedLayout = false;
7341   if (Ty->isRecordType()) {
7342     HasByrefExtendedLayout = true;
7343     LifeTime = Qualifiers::OCL_None;
7344   } else if ((LifeTime = Ty.getObjCLifetime())) {
7345     // Honor the ARC qualifiers.
7346   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7347     // The MRR rule.
7348     LifeTime = Qualifiers::OCL_ExplicitNone;
7349   } else {
7350     LifeTime = Qualifiers::OCL_None;
7351   }
7352   return true;
7353 }
7354 
7355 CanQualType ASTContext::getNSUIntegerType() const {
7356   assert(Target && "Expected target to be initialized");
7357   const llvm::Triple &T = Target->getTriple();
7358   // Windows is LLP64 rather than LP64
7359   if (T.isOSWindows() && T.isArch64Bit())
7360     return UnsignedLongLongTy;
7361   return UnsignedLongTy;
7362 }
7363 
7364 CanQualType ASTContext::getNSIntegerType() const {
7365   assert(Target && "Expected target to be initialized");
7366   const llvm::Triple &T = Target->getTriple();
7367   // Windows is LLP64 rather than LP64
7368   if (T.isOSWindows() && T.isArch64Bit())
7369     return LongLongTy;
7370   return LongTy;
7371 }
7372 
7373 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
7374   if (!ObjCInstanceTypeDecl)
7375     ObjCInstanceTypeDecl =
7376         buildImplicitTypedef(getObjCIdType(), "instancetype");
7377   return ObjCInstanceTypeDecl;
7378 }
7379 
7380 // This returns true if a type has been typedefed to BOOL:
7381 // typedef <type> BOOL;
7382 static bool isTypeTypedefedAsBOOL(QualType T) {
7383   if (const auto *TT = dyn_cast<TypedefType>(T))
7384     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7385       return II->isStr("BOOL");
7386 
7387   return false;
7388 }
7389 
7390 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
7391 /// purpose.
7392 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
7393   if (!type->isIncompleteArrayType() && type->isIncompleteType())
7394     return CharUnits::Zero();
7395 
7396   CharUnits sz = getTypeSizeInChars(type);
7397 
7398   // Make all integer and enum types at least as large as an int
7399   if (sz.isPositive() && type->isIntegralOrEnumerationType())
7400     sz = std::max(sz, getTypeSizeInChars(IntTy));
7401   // Treat arrays as pointers, since that's how they're passed in.
7402   else if (type->isArrayType())
7403     sz = getTypeSizeInChars(VoidPtrTy);
7404   return sz;
7405 }
7406 
7407 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
7408   return getTargetInfo().getCXXABI().isMicrosoft() &&
7409          VD->isStaticDataMember() &&
7410          VD->getType()->isIntegralOrEnumerationType() &&
7411          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7412 }
7413 
7414 ASTContext::InlineVariableDefinitionKind
7415 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
7416   if (!VD->isInline())
7417     return InlineVariableDefinitionKind::None;
7418 
7419   // In almost all cases, it's a weak definition.
7420   auto *First = VD->getFirstDecl();
7421   if (First->isInlineSpecified() || !First->isStaticDataMember())
7422     return InlineVariableDefinitionKind::Weak;
7423 
7424   // If there's a file-context declaration in this translation unit, it's a
7425   // non-discardable definition.
7426   for (auto *D : VD->redecls())
7427     if (D->getLexicalDeclContext()->isFileContext() &&
7428         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7429       return InlineVariableDefinitionKind::Strong;
7430 
7431   // If we've not seen one yet, we don't know.
7432   return InlineVariableDefinitionKind::WeakUnknown;
7433 }
7434 
7435 static std::string charUnitsToString(const CharUnits &CU) {
7436   return llvm::itostr(CU.getQuantity());
7437 }
7438 
7439 /// getObjCEncodingForBlock - Return the encoded type for this block
7440 /// declaration.
7441 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
7442   std::string S;
7443 
7444   const BlockDecl *Decl = Expr->getBlockDecl();
7445   QualType BlockTy =
7446       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7447   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7448   // Encode result type.
7449   if (getLangOpts().EncodeExtendedBlockSig)
7450     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
7451                                       true /*Extended*/);
7452   else
7453     getObjCEncodingForType(BlockReturnTy, S);
7454   // Compute size of all parameters.
7455   // Start with computing size of a pointer in number of bytes.
7456   // FIXME: There might(should) be a better way of doing this computation!
7457   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7458   CharUnits ParmOffset = PtrSize;
7459   for (auto PI : Decl->parameters()) {
7460     QualType PType = PI->getType();
7461     CharUnits sz = getObjCEncodingTypeSize(PType);
7462     if (sz.isZero())
7463       continue;
7464     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7465     ParmOffset += sz;
7466   }
7467   // Size of the argument frame
7468   S += charUnitsToString(ParmOffset);
7469   // Block pointer and offset.
7470   S += "@?0";
7471 
7472   // Argument types.
7473   ParmOffset = PtrSize;
7474   for (auto PVDecl : Decl->parameters()) {
7475     QualType PType = PVDecl->getOriginalType();
7476     if (const auto *AT =
7477             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7478       // Use array's original type only if it has known number of
7479       // elements.
7480       if (!isa<ConstantArrayType>(AT))
7481         PType = PVDecl->getType();
7482     } else if (PType->isFunctionType())
7483       PType = PVDecl->getType();
7484     if (getLangOpts().EncodeExtendedBlockSig)
7485       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
7486                                       S, true /*Extended*/);
7487     else
7488       getObjCEncodingForType(PType, S);
7489     S += charUnitsToString(ParmOffset);
7490     ParmOffset += getObjCEncodingTypeSize(PType);
7491   }
7492 
7493   return S;
7494 }
7495 
7496 std::string
7497 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
7498   std::string S;
7499   // Encode result type.
7500   getObjCEncodingForType(Decl->getReturnType(), S);
7501   CharUnits ParmOffset;
7502   // Compute size of all parameters.
7503   for (auto PI : Decl->parameters()) {
7504     QualType PType = PI->getType();
7505     CharUnits sz = getObjCEncodingTypeSize(PType);
7506     if (sz.isZero())
7507       continue;
7508 
7509     assert(sz.isPositive() &&
7510            "getObjCEncodingForFunctionDecl - Incomplete param type");
7511     ParmOffset += sz;
7512   }
7513   S += charUnitsToString(ParmOffset);
7514   ParmOffset = CharUnits::Zero();
7515 
7516   // Argument types.
7517   for (auto PVDecl : Decl->parameters()) {
7518     QualType PType = PVDecl->getOriginalType();
7519     if (const auto *AT =
7520             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7521       // Use array's original type only if it has known number of
7522       // elements.
7523       if (!isa<ConstantArrayType>(AT))
7524         PType = PVDecl->getType();
7525     } else if (PType->isFunctionType())
7526       PType = PVDecl->getType();
7527     getObjCEncodingForType(PType, S);
7528     S += charUnitsToString(ParmOffset);
7529     ParmOffset += getObjCEncodingTypeSize(PType);
7530   }
7531 
7532   return S;
7533 }
7534 
7535 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
7536 /// method parameter or return type. If Extended, include class names and
7537 /// block object types.
7538 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
7539                                                    QualType T, std::string& S,
7540                                                    bool Extended) const {
7541   // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7542   getObjCEncodingForTypeQualifier(QT, S);
7543   // Encode parameter type.
7544   ObjCEncOptions Options = ObjCEncOptions()
7545                                .setExpandPointedToStructures()
7546                                .setExpandStructures()
7547                                .setIsOutermostType();
7548   if (Extended)
7549     Options.setEncodeBlockParameters().setEncodeClassNames();
7550   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7551 }
7552 
7553 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
7554 /// declaration.
7555 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
7556                                                      bool Extended) const {
7557   // FIXME: This is not very efficient.
7558   // Encode return type.
7559   std::string S;
7560   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7561                                     Decl->getReturnType(), S, Extended);
7562   // Compute size of all parameters.
7563   // Start with computing size of a pointer in number of bytes.
7564   // FIXME: There might(should) be a better way of doing this computation!
7565   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7566   // The first two arguments (self and _cmd) are pointers; account for
7567   // their size.
7568   CharUnits ParmOffset = 2 * PtrSize;
7569   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7570        E = Decl->sel_param_end(); PI != E; ++PI) {
7571     QualType PType = (*PI)->getType();
7572     CharUnits sz = getObjCEncodingTypeSize(PType);
7573     if (sz.isZero())
7574       continue;
7575 
7576     assert(sz.isPositive() &&
7577            "getObjCEncodingForMethodDecl - Incomplete param type");
7578     ParmOffset += sz;
7579   }
7580   S += charUnitsToString(ParmOffset);
7581   S += "@0:";
7582   S += charUnitsToString(PtrSize);
7583 
7584   // Argument types.
7585   ParmOffset = 2 * PtrSize;
7586   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7587        E = Decl->sel_param_end(); PI != E; ++PI) {
7588     const ParmVarDecl *PVDecl = *PI;
7589     QualType PType = PVDecl->getOriginalType();
7590     if (const auto *AT =
7591             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7592       // Use array's original type only if it has known number of
7593       // elements.
7594       if (!isa<ConstantArrayType>(AT))
7595         PType = PVDecl->getType();
7596     } else if (PType->isFunctionType())
7597       PType = PVDecl->getType();
7598     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7599                                       PType, S, Extended);
7600     S += charUnitsToString(ParmOffset);
7601     ParmOffset += getObjCEncodingTypeSize(PType);
7602   }
7603 
7604   return S;
7605 }
7606 
7607 ObjCPropertyImplDecl *
7608 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7609                                       const ObjCPropertyDecl *PD,
7610                                       const Decl *Container) const {
7611   if (!Container)
7612     return nullptr;
7613   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7614     for (auto *PID : CID->property_impls())
7615       if (PID->getPropertyDecl() == PD)
7616         return PID;
7617   } else {
7618     const auto *OID = cast<ObjCImplementationDecl>(Container);
7619     for (auto *PID : OID->property_impls())
7620       if (PID->getPropertyDecl() == PD)
7621         return PID;
7622   }
7623   return nullptr;
7624 }
7625 
7626 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
7627 /// property declaration. If non-NULL, Container must be either an
7628 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7629 /// NULL when getting encodings for protocol properties.
7630 /// Property attributes are stored as a comma-delimited C string. The simple
7631 /// attributes readonly and bycopy are encoded as single characters. The
7632 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
7633 /// encoded as single characters, followed by an identifier. Property types
7634 /// are also encoded as a parametrized attribute. The characters used to encode
7635 /// these attributes are defined by the following enumeration:
7636 /// @code
7637 /// enum PropertyAttributes {
7638 /// kPropertyReadOnly = 'R',   // property is read-only.
7639 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7640 /// kPropertyByref = '&',  // property is a reference to the value last assigned
7641 /// kPropertyDynamic = 'D',    // property is dynamic
7642 /// kPropertyGetter = 'G',     // followed by getter selector name
7643 /// kPropertySetter = 'S',     // followed by setter selector name
7644 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7645 /// kPropertyType = 'T'              // followed by old-style type encoding.
7646 /// kPropertyWeak = 'W'              // 'weak' property
7647 /// kPropertyStrong = 'P'            // property GC'able
7648 /// kPropertyNonAtomic = 'N'         // property non-atomic
7649 /// };
7650 /// @endcode
7651 std::string
7652 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7653                                            const Decl *Container) const {
7654   // Collect information from the property implementation decl(s).
7655   bool Dynamic = false;
7656   ObjCPropertyImplDecl *SynthesizePID = nullptr;
7657 
7658   if (ObjCPropertyImplDecl *PropertyImpDecl =
7659       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7660     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7661       Dynamic = true;
7662     else
7663       SynthesizePID = PropertyImpDecl;
7664   }
7665 
7666   // FIXME: This is not very efficient.
7667   std::string S = "T";
7668 
7669   // Encode result type.
7670   // GCC has some special rules regarding encoding of properties which
7671   // closely resembles encoding of ivars.
7672   getObjCEncodingForPropertyType(PD->getType(), S);
7673 
7674   if (PD->isReadOnly()) {
7675     S += ",R";
7676     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7677       S += ",C";
7678     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7679       S += ",&";
7680     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7681       S += ",W";
7682   } else {
7683     switch (PD->getSetterKind()) {
7684     case ObjCPropertyDecl::Assign: break;
7685     case ObjCPropertyDecl::Copy:   S += ",C"; break;
7686     case ObjCPropertyDecl::Retain: S += ",&"; break;
7687     case ObjCPropertyDecl::Weak:   S += ",W"; break;
7688     }
7689   }
7690 
7691   // It really isn't clear at all what this means, since properties
7692   // are "dynamic by default".
7693   if (Dynamic)
7694     S += ",D";
7695 
7696   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7697     S += ",N";
7698 
7699   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7700     S += ",G";
7701     S += PD->getGetterName().getAsString();
7702   }
7703 
7704   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7705     S += ",S";
7706     S += PD->getSetterName().getAsString();
7707   }
7708 
7709   if (SynthesizePID) {
7710     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7711     S += ",V";
7712     S += OID->getNameAsString();
7713   }
7714 
7715   // FIXME: OBJCGC: weak & strong
7716   return S;
7717 }
7718 
7719 /// getLegacyIntegralTypeEncoding -
7720 /// Another legacy compatibility encoding: 32-bit longs are encoded as
7721 /// 'l' or 'L' , but not always.  For typedefs, we need to use
7722 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
7723 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7724   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
7725     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7726       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7727         PointeeTy = UnsignedIntTy;
7728       else
7729         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7730           PointeeTy = IntTy;
7731     }
7732   }
7733 }
7734 
7735 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7736                                         const FieldDecl *Field,
7737                                         QualType *NotEncodedT) const {
7738   // We follow the behavior of gcc, expanding structures which are
7739   // directly pointed to, and expanding embedded structures. Note that
7740   // these rules are sufficient to prevent recursive encoding of the
7741   // same type.
7742   getObjCEncodingForTypeImpl(T, S,
7743                              ObjCEncOptions()
7744                                  .setExpandPointedToStructures()
7745                                  .setExpandStructures()
7746                                  .setIsOutermostType(),
7747                              Field, NotEncodedT);
7748 }
7749 
7750 void ASTContext::getObjCEncodingForPropertyType(QualType T,
7751                                                 std::string& S) const {
7752   // Encode result type.
7753   // GCC has some special rules regarding encoding of properties which
7754   // closely resembles encoding of ivars.
7755   getObjCEncodingForTypeImpl(T, S,
7756                              ObjCEncOptions()
7757                                  .setExpandPointedToStructures()
7758                                  .setExpandStructures()
7759                                  .setIsOutermostType()
7760                                  .setEncodingProperty(),
7761                              /*Field=*/nullptr);
7762 }
7763 
7764 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7765                                             const BuiltinType *BT) {
7766     BuiltinType::Kind kind = BT->getKind();
7767     switch (kind) {
7768     case BuiltinType::Void:       return 'v';
7769     case BuiltinType::Bool:       return 'B';
7770     case BuiltinType::Char8:
7771     case BuiltinType::Char_U:
7772     case BuiltinType::UChar:      return 'C';
7773     case BuiltinType::Char16:
7774     case BuiltinType::UShort:     return 'S';
7775     case BuiltinType::Char32:
7776     case BuiltinType::UInt:       return 'I';
7777     case BuiltinType::ULong:
7778         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7779     case BuiltinType::UInt128:    return 'T';
7780     case BuiltinType::ULongLong:  return 'Q';
7781     case BuiltinType::Char_S:
7782     case BuiltinType::SChar:      return 'c';
7783     case BuiltinType::Short:      return 's';
7784     case BuiltinType::WChar_S:
7785     case BuiltinType::WChar_U:
7786     case BuiltinType::Int:        return 'i';
7787     case BuiltinType::Long:
7788       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7789     case BuiltinType::LongLong:   return 'q';
7790     case BuiltinType::Int128:     return 't';
7791     case BuiltinType::Float:      return 'f';
7792     case BuiltinType::Double:     return 'd';
7793     case BuiltinType::LongDouble: return 'D';
7794     case BuiltinType::NullPtr:    return '*'; // like char*
7795 
7796     case BuiltinType::BFloat16:
7797     case BuiltinType::Float16:
7798     case BuiltinType::Float128:
7799     case BuiltinType::Ibm128:
7800     case BuiltinType::Half:
7801     case BuiltinType::ShortAccum:
7802     case BuiltinType::Accum:
7803     case BuiltinType::LongAccum:
7804     case BuiltinType::UShortAccum:
7805     case BuiltinType::UAccum:
7806     case BuiltinType::ULongAccum:
7807     case BuiltinType::ShortFract:
7808     case BuiltinType::Fract:
7809     case BuiltinType::LongFract:
7810     case BuiltinType::UShortFract:
7811     case BuiltinType::UFract:
7812     case BuiltinType::ULongFract:
7813     case BuiltinType::SatShortAccum:
7814     case BuiltinType::SatAccum:
7815     case BuiltinType::SatLongAccum:
7816     case BuiltinType::SatUShortAccum:
7817     case BuiltinType::SatUAccum:
7818     case BuiltinType::SatULongAccum:
7819     case BuiltinType::SatShortFract:
7820     case BuiltinType::SatFract:
7821     case BuiltinType::SatLongFract:
7822     case BuiltinType::SatUShortFract:
7823     case BuiltinType::SatUFract:
7824     case BuiltinType::SatULongFract:
7825       // FIXME: potentially need @encodes for these!
7826       return ' ';
7827 
7828 #define SVE_TYPE(Name, Id, SingletonId) \
7829     case BuiltinType::Id:
7830 #include "clang/Basic/AArch64SVEACLETypes.def"
7831 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
7832 #include "clang/Basic/RISCVVTypes.def"
7833       {
7834         DiagnosticsEngine &Diags = C->getDiagnostics();
7835         unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
7836                                                 "cannot yet @encode type %0");
7837         Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7838         return ' ';
7839       }
7840 
7841     case BuiltinType::ObjCId:
7842     case BuiltinType::ObjCClass:
7843     case BuiltinType::ObjCSel:
7844       llvm_unreachable("@encoding ObjC primitive type");
7845 
7846     // OpenCL and placeholder types don't need @encodings.
7847 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7848     case BuiltinType::Id:
7849 #include "clang/Basic/OpenCLImageTypes.def"
7850 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7851     case BuiltinType::Id:
7852 #include "clang/Basic/OpenCLExtensionTypes.def"
7853     case BuiltinType::OCLEvent:
7854     case BuiltinType::OCLClkEvent:
7855     case BuiltinType::OCLQueue:
7856     case BuiltinType::OCLReserveID:
7857     case BuiltinType::OCLSampler:
7858     case BuiltinType::Dependent:
7859 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7860     case BuiltinType::Id:
7861 #include "clang/Basic/PPCTypes.def"
7862 #define BUILTIN_TYPE(KIND, ID)
7863 #define PLACEHOLDER_TYPE(KIND, ID) \
7864     case BuiltinType::KIND:
7865 #include "clang/AST/BuiltinTypes.def"
7866       llvm_unreachable("invalid builtin type for @encode");
7867     }
7868     llvm_unreachable("invalid BuiltinType::Kind value");
7869 }
7870 
7871 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7872   EnumDecl *Enum = ET->getDecl();
7873 
7874   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7875   if (!Enum->isFixed())
7876     return 'i';
7877 
7878   // The encoding of a fixed enum type matches its fixed underlying type.
7879   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7880   return getObjCEncodingForPrimitiveType(C, BT);
7881 }
7882 
7883 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7884                            QualType T, const FieldDecl *FD) {
7885   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7886   S += 'b';
7887   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7888   // The GNU runtime requires more information; bitfields are encoded as b,
7889   // then the offset (in bits) of the first element, then the type of the
7890   // bitfield, then the size in bits.  For example, in this structure:
7891   //
7892   // struct
7893   // {
7894   //    int integer;
7895   //    int flags:2;
7896   // };
7897   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7898   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7899   // information is not especially sensible, but we're stuck with it for
7900   // compatibility with GCC, although providing it breaks anything that
7901   // actually uses runtime introspection and wants to work on both runtimes...
7902   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7903     uint64_t Offset;
7904 
7905     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7906       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7907                                          IVD);
7908     } else {
7909       const RecordDecl *RD = FD->getParent();
7910       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7911       Offset = RL.getFieldOffset(FD->getFieldIndex());
7912     }
7913 
7914     S += llvm::utostr(Offset);
7915 
7916     if (const auto *ET = T->getAs<EnumType>())
7917       S += ObjCEncodingForEnumType(Ctx, ET);
7918     else {
7919       const auto *BT = T->castAs<BuiltinType>();
7920       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7921     }
7922   }
7923   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7924 }
7925 
7926 // Helper function for determining whether the encoded type string would include
7927 // a template specialization type.
7928 static bool hasTemplateSpecializationInEncodedString(const Type *T,
7929                                                      bool VisitBasesAndFields) {
7930   T = T->getBaseElementTypeUnsafe();
7931 
7932   if (auto *PT = T->getAs<PointerType>())
7933     return hasTemplateSpecializationInEncodedString(
7934         PT->getPointeeType().getTypePtr(), false);
7935 
7936   auto *CXXRD = T->getAsCXXRecordDecl();
7937 
7938   if (!CXXRD)
7939     return false;
7940 
7941   if (isa<ClassTemplateSpecializationDecl>(CXXRD))
7942     return true;
7943 
7944   if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
7945     return false;
7946 
7947   for (auto B : CXXRD->bases())
7948     if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
7949                                                  true))
7950       return true;
7951 
7952   for (auto *FD : CXXRD->fields())
7953     if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
7954                                                  true))
7955       return true;
7956 
7957   return false;
7958 }
7959 
7960 // FIXME: Use SmallString for accumulating string.
7961 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7962                                             const ObjCEncOptions Options,
7963                                             const FieldDecl *FD,
7964                                             QualType *NotEncodedT) const {
7965   CanQualType CT = getCanonicalType(T);
7966   switch (CT->getTypeClass()) {
7967   case Type::Builtin:
7968   case Type::Enum:
7969     if (FD && FD->isBitField())
7970       return EncodeBitField(this, S, T, FD);
7971     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7972       S += getObjCEncodingForPrimitiveType(this, BT);
7973     else
7974       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7975     return;
7976 
7977   case Type::Complex:
7978     S += 'j';
7979     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7980                                ObjCEncOptions(),
7981                                /*Field=*/nullptr);
7982     return;
7983 
7984   case Type::Atomic:
7985     S += 'A';
7986     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7987                                ObjCEncOptions(),
7988                                /*Field=*/nullptr);
7989     return;
7990 
7991   // encoding for pointer or reference types.
7992   case Type::Pointer:
7993   case Type::LValueReference:
7994   case Type::RValueReference: {
7995     QualType PointeeTy;
7996     if (isa<PointerType>(CT)) {
7997       const auto *PT = T->castAs<PointerType>();
7998       if (PT->isObjCSelType()) {
7999         S += ':';
8000         return;
8001       }
8002       PointeeTy = PT->getPointeeType();
8003     } else {
8004       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8005     }
8006 
8007     bool isReadOnly = false;
8008     // For historical/compatibility reasons, the read-only qualifier of the
8009     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
8010     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8011     // Also, do not emit the 'r' for anything but the outermost type!
8012     if (isa<TypedefType>(T.getTypePtr())) {
8013       if (Options.IsOutermostType() && T.isConstQualified()) {
8014         isReadOnly = true;
8015         S += 'r';
8016       }
8017     } else if (Options.IsOutermostType()) {
8018       QualType P = PointeeTy;
8019       while (auto PT = P->getAs<PointerType>())
8020         P = PT->getPointeeType();
8021       if (P.isConstQualified()) {
8022         isReadOnly = true;
8023         S += 'r';
8024       }
8025     }
8026     if (isReadOnly) {
8027       // Another legacy compatibility encoding. Some ObjC qualifier and type
8028       // combinations need to be rearranged.
8029       // Rewrite "in const" from "nr" to "rn"
8030       if (StringRef(S).endswith("nr"))
8031         S.replace(S.end()-2, S.end(), "rn");
8032     }
8033 
8034     if (PointeeTy->isCharType()) {
8035       // char pointer types should be encoded as '*' unless it is a
8036       // type that has been typedef'd to 'BOOL'.
8037       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8038         S += '*';
8039         return;
8040       }
8041     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8042       // GCC binary compat: Need to convert "struct objc_class *" to "#".
8043       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8044         S += '#';
8045         return;
8046       }
8047       // GCC binary compat: Need to convert "struct objc_object *" to "@".
8048       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8049         S += '@';
8050         return;
8051       }
8052       // If the encoded string for the class includes template names, just emit
8053       // "^v" for pointers to the class.
8054       if (getLangOpts().CPlusPlus &&
8055           (!getLangOpts().EncodeCXXClassTemplateSpec &&
8056            hasTemplateSpecializationInEncodedString(
8057                RTy, Options.ExpandPointedToStructures()))) {
8058         S += "^v";
8059         return;
8060       }
8061       // fall through...
8062     }
8063     S += '^';
8064     getLegacyIntegralTypeEncoding(PointeeTy);
8065 
8066     ObjCEncOptions NewOptions;
8067     if (Options.ExpandPointedToStructures())
8068       NewOptions.setExpandStructures();
8069     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8070                                /*Field=*/nullptr, NotEncodedT);
8071     return;
8072   }
8073 
8074   case Type::ConstantArray:
8075   case Type::IncompleteArray:
8076   case Type::VariableArray: {
8077     const auto *AT = cast<ArrayType>(CT);
8078 
8079     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8080       // Incomplete arrays are encoded as a pointer to the array element.
8081       S += '^';
8082 
8083       getObjCEncodingForTypeImpl(
8084           AT->getElementType(), S,
8085           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8086     } else {
8087       S += '[';
8088 
8089       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8090         S += llvm::utostr(CAT->getSize().getZExtValue());
8091       else {
8092         //Variable length arrays are encoded as a regular array with 0 elements.
8093         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8094                "Unknown array type!");
8095         S += '0';
8096       }
8097 
8098       getObjCEncodingForTypeImpl(
8099           AT->getElementType(), S,
8100           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8101           NotEncodedT);
8102       S += ']';
8103     }
8104     return;
8105   }
8106 
8107   case Type::FunctionNoProto:
8108   case Type::FunctionProto:
8109     S += '?';
8110     return;
8111 
8112   case Type::Record: {
8113     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8114     S += RDecl->isUnion() ? '(' : '{';
8115     // Anonymous structures print as '?'
8116     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8117       S += II->getName();
8118       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8119         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8120         llvm::raw_string_ostream OS(S);
8121         printTemplateArgumentList(OS, TemplateArgs.asArray(),
8122                                   getPrintingPolicy());
8123       }
8124     } else {
8125       S += '?';
8126     }
8127     if (Options.ExpandStructures()) {
8128       S += '=';
8129       if (!RDecl->isUnion()) {
8130         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8131       } else {
8132         for (const auto *Field : RDecl->fields()) {
8133           if (FD) {
8134             S += '"';
8135             S += Field->getNameAsString();
8136             S += '"';
8137           }
8138 
8139           // Special case bit-fields.
8140           if (Field->isBitField()) {
8141             getObjCEncodingForTypeImpl(Field->getType(), S,
8142                                        ObjCEncOptions().setExpandStructures(),
8143                                        Field);
8144           } else {
8145             QualType qt = Field->getType();
8146             getLegacyIntegralTypeEncoding(qt);
8147             getObjCEncodingForTypeImpl(
8148                 qt, S,
8149                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8150                 NotEncodedT);
8151           }
8152         }
8153       }
8154     }
8155     S += RDecl->isUnion() ? ')' : '}';
8156     return;
8157   }
8158 
8159   case Type::BlockPointer: {
8160     const auto *BT = T->castAs<BlockPointerType>();
8161     S += "@?"; // Unlike a pointer-to-function, which is "^?".
8162     if (Options.EncodeBlockParameters()) {
8163       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8164 
8165       S += '<';
8166       // Block return type
8167       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8168                                  Options.forComponentType(), FD, NotEncodedT);
8169       // Block self
8170       S += "@?";
8171       // Block parameters
8172       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8173         for (const auto &I : FPT->param_types())
8174           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8175                                      NotEncodedT);
8176       }
8177       S += '>';
8178     }
8179     return;
8180   }
8181 
8182   case Type::ObjCObject: {
8183     // hack to match legacy encoding of *id and *Class
8184     QualType Ty = getObjCObjectPointerType(CT);
8185     if (Ty->isObjCIdType()) {
8186       S += "{objc_object=}";
8187       return;
8188     }
8189     else if (Ty->isObjCClassType()) {
8190       S += "{objc_class=}";
8191       return;
8192     }
8193     // TODO: Double check to make sure this intentionally falls through.
8194     LLVM_FALLTHROUGH;
8195   }
8196 
8197   case Type::ObjCInterface: {
8198     // Ignore protocol qualifiers when mangling at this level.
8199     // @encode(class_name)
8200     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8201     S += '{';
8202     S += OI->getObjCRuntimeNameAsString();
8203     if (Options.ExpandStructures()) {
8204       S += '=';
8205       SmallVector<const ObjCIvarDecl*, 32> Ivars;
8206       DeepCollectObjCIvars(OI, true, Ivars);
8207       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8208         const FieldDecl *Field = Ivars[i];
8209         if (Field->isBitField())
8210           getObjCEncodingForTypeImpl(Field->getType(), S,
8211                                      ObjCEncOptions().setExpandStructures(),
8212                                      Field);
8213         else
8214           getObjCEncodingForTypeImpl(Field->getType(), S,
8215                                      ObjCEncOptions().setExpandStructures(), FD,
8216                                      NotEncodedT);
8217       }
8218     }
8219     S += '}';
8220     return;
8221   }
8222 
8223   case Type::ObjCObjectPointer: {
8224     const auto *OPT = T->castAs<ObjCObjectPointerType>();
8225     if (OPT->isObjCIdType()) {
8226       S += '@';
8227       return;
8228     }
8229 
8230     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8231       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8232       // Since this is a binary compatibility issue, need to consult with
8233       // runtime folks. Fortunately, this is a *very* obscure construct.
8234       S += '#';
8235       return;
8236     }
8237 
8238     if (OPT->isObjCQualifiedIdType()) {
8239       getObjCEncodingForTypeImpl(
8240           getObjCIdType(), S,
8241           Options.keepingOnly(ObjCEncOptions()
8242                                   .setExpandPointedToStructures()
8243                                   .setExpandStructures()),
8244           FD);
8245       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8246         // Note that we do extended encoding of protocol qualifier list
8247         // Only when doing ivar or property encoding.
8248         S += '"';
8249         for (const auto *I : OPT->quals()) {
8250           S += '<';
8251           S += I->getObjCRuntimeNameAsString();
8252           S += '>';
8253         }
8254         S += '"';
8255       }
8256       return;
8257     }
8258 
8259     S += '@';
8260     if (OPT->getInterfaceDecl() &&
8261         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8262       S += '"';
8263       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8264       for (const auto *I : OPT->quals()) {
8265         S += '<';
8266         S += I->getObjCRuntimeNameAsString();
8267         S += '>';
8268       }
8269       S += '"';
8270     }
8271     return;
8272   }
8273 
8274   // gcc just blithely ignores member pointers.
8275   // FIXME: we should do better than that.  'M' is available.
8276   case Type::MemberPointer:
8277   // This matches gcc's encoding, even though technically it is insufficient.
8278   //FIXME. We should do a better job than gcc.
8279   case Type::Vector:
8280   case Type::ExtVector:
8281   // Until we have a coherent encoding of these three types, issue warning.
8282     if (NotEncodedT)
8283       *NotEncodedT = T;
8284     return;
8285 
8286   case Type::ConstantMatrix:
8287     if (NotEncodedT)
8288       *NotEncodedT = T;
8289     return;
8290 
8291   case Type::BitInt:
8292     if (NotEncodedT)
8293       *NotEncodedT = T;
8294     return;
8295 
8296   // We could see an undeduced auto type here during error recovery.
8297   // Just ignore it.
8298   case Type::Auto:
8299   case Type::DeducedTemplateSpecialization:
8300     return;
8301 
8302   case Type::Pipe:
8303 #define ABSTRACT_TYPE(KIND, BASE)
8304 #define TYPE(KIND, BASE)
8305 #define DEPENDENT_TYPE(KIND, BASE) \
8306   case Type::KIND:
8307 #define NON_CANONICAL_TYPE(KIND, BASE) \
8308   case Type::KIND:
8309 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8310   case Type::KIND:
8311 #include "clang/AST/TypeNodes.inc"
8312     llvm_unreachable("@encode for dependent type!");
8313   }
8314   llvm_unreachable("bad type kind!");
8315 }
8316 
8317 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8318                                                  std::string &S,
8319                                                  const FieldDecl *FD,
8320                                                  bool includeVBases,
8321                                                  QualType *NotEncodedT) const {
8322   assert(RDecl && "Expected non-null RecordDecl");
8323   assert(!RDecl->isUnion() && "Should not be called for unions");
8324   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8325     return;
8326 
8327   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8328   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8329   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8330 
8331   if (CXXRec) {
8332     for (const auto &BI : CXXRec->bases()) {
8333       if (!BI.isVirtual()) {
8334         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8335         if (base->isEmpty())
8336           continue;
8337         uint64_t offs = toBits(layout.getBaseClassOffset(base));
8338         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8339                                   std::make_pair(offs, base));
8340       }
8341     }
8342   }
8343 
8344   unsigned i = 0;
8345   for (FieldDecl *Field : RDecl->fields()) {
8346     if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8347       continue;
8348     uint64_t offs = layout.getFieldOffset(i);
8349     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8350                               std::make_pair(offs, Field));
8351     ++i;
8352   }
8353 
8354   if (CXXRec && includeVBases) {
8355     for (const auto &BI : CXXRec->vbases()) {
8356       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8357       if (base->isEmpty())
8358         continue;
8359       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8360       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8361           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8362         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8363                                   std::make_pair(offs, base));
8364     }
8365   }
8366 
8367   CharUnits size;
8368   if (CXXRec) {
8369     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8370   } else {
8371     size = layout.getSize();
8372   }
8373 
8374 #ifndef NDEBUG
8375   uint64_t CurOffs = 0;
8376 #endif
8377   std::multimap<uint64_t, NamedDecl *>::iterator
8378     CurLayObj = FieldOrBaseOffsets.begin();
8379 
8380   if (CXXRec && CXXRec->isDynamicClass() &&
8381       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8382     if (FD) {
8383       S += "\"_vptr$";
8384       std::string recname = CXXRec->getNameAsString();
8385       if (recname.empty()) recname = "?";
8386       S += recname;
8387       S += '"';
8388     }
8389     S += "^^?";
8390 #ifndef NDEBUG
8391     CurOffs += getTypeSize(VoidPtrTy);
8392 #endif
8393   }
8394 
8395   if (!RDecl->hasFlexibleArrayMember()) {
8396     // Mark the end of the structure.
8397     uint64_t offs = toBits(size);
8398     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8399                               std::make_pair(offs, nullptr));
8400   }
8401 
8402   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8403 #ifndef NDEBUG
8404     assert(CurOffs <= CurLayObj->first);
8405     if (CurOffs < CurLayObj->first) {
8406       uint64_t padding = CurLayObj->first - CurOffs;
8407       // FIXME: There doesn't seem to be a way to indicate in the encoding that
8408       // packing/alignment of members is different that normal, in which case
8409       // the encoding will be out-of-sync with the real layout.
8410       // If the runtime switches to just consider the size of types without
8411       // taking into account alignment, we could make padding explicit in the
8412       // encoding (e.g. using arrays of chars). The encoding strings would be
8413       // longer then though.
8414       CurOffs += padding;
8415     }
8416 #endif
8417 
8418     NamedDecl *dcl = CurLayObj->second;
8419     if (!dcl)
8420       break; // reached end of structure.
8421 
8422     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8423       // We expand the bases without their virtual bases since those are going
8424       // in the initial structure. Note that this differs from gcc which
8425       // expands virtual bases each time one is encountered in the hierarchy,
8426       // making the encoding type bigger than it really is.
8427       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8428                                       NotEncodedT);
8429       assert(!base->isEmpty());
8430 #ifndef NDEBUG
8431       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8432 #endif
8433     } else {
8434       const auto *field = cast<FieldDecl>(dcl);
8435       if (FD) {
8436         S += '"';
8437         S += field->getNameAsString();
8438         S += '"';
8439       }
8440 
8441       if (field->isBitField()) {
8442         EncodeBitField(this, S, field->getType(), field);
8443 #ifndef NDEBUG
8444         CurOffs += field->getBitWidthValue(*this);
8445 #endif
8446       } else {
8447         QualType qt = field->getType();
8448         getLegacyIntegralTypeEncoding(qt);
8449         getObjCEncodingForTypeImpl(
8450             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8451             FD, NotEncodedT);
8452 #ifndef NDEBUG
8453         CurOffs += getTypeSize(field->getType());
8454 #endif
8455       }
8456     }
8457   }
8458 }
8459 
8460 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
8461                                                  std::string& S) const {
8462   if (QT & Decl::OBJC_TQ_In)
8463     S += 'n';
8464   if (QT & Decl::OBJC_TQ_Inout)
8465     S += 'N';
8466   if (QT & Decl::OBJC_TQ_Out)
8467     S += 'o';
8468   if (QT & Decl::OBJC_TQ_Bycopy)
8469     S += 'O';
8470   if (QT & Decl::OBJC_TQ_Byref)
8471     S += 'R';
8472   if (QT & Decl::OBJC_TQ_Oneway)
8473     S += 'V';
8474 }
8475 
8476 TypedefDecl *ASTContext::getObjCIdDecl() const {
8477   if (!ObjCIdDecl) {
8478     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
8479     T = getObjCObjectPointerType(T);
8480     ObjCIdDecl = buildImplicitTypedef(T, "id");
8481   }
8482   return ObjCIdDecl;
8483 }
8484 
8485 TypedefDecl *ASTContext::getObjCSelDecl() const {
8486   if (!ObjCSelDecl) {
8487     QualType T = getPointerType(ObjCBuiltinSelTy);
8488     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8489   }
8490   return ObjCSelDecl;
8491 }
8492 
8493 TypedefDecl *ASTContext::getObjCClassDecl() const {
8494   if (!ObjCClassDecl) {
8495     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
8496     T = getObjCObjectPointerType(T);
8497     ObjCClassDecl = buildImplicitTypedef(T, "Class");
8498   }
8499   return ObjCClassDecl;
8500 }
8501 
8502 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
8503   if (!ObjCProtocolClassDecl) {
8504     ObjCProtocolClassDecl
8505       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
8506                                   SourceLocation(),
8507                                   &Idents.get("Protocol"),
8508                                   /*typeParamList=*/nullptr,
8509                                   /*PrevDecl=*/nullptr,
8510                                   SourceLocation(), true);
8511   }
8512 
8513   return ObjCProtocolClassDecl;
8514 }
8515 
8516 //===----------------------------------------------------------------------===//
8517 // __builtin_va_list Construction Functions
8518 //===----------------------------------------------------------------------===//
8519 
8520 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
8521                                                  StringRef Name) {
8522   // typedef char* __builtin[_ms]_va_list;
8523   QualType T = Context->getPointerType(Context->CharTy);
8524   return Context->buildImplicitTypedef(T, Name);
8525 }
8526 
8527 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
8528   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8529 }
8530 
8531 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
8532   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8533 }
8534 
8535 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
8536   // typedef void* __builtin_va_list;
8537   QualType T = Context->getPointerType(Context->VoidTy);
8538   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8539 }
8540 
8541 static TypedefDecl *
8542 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
8543   // struct __va_list
8544   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8545   if (Context->getLangOpts().CPlusPlus) {
8546     // namespace std { struct __va_list {
8547     auto *NS = NamespaceDecl::Create(
8548         const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8549         /*Inline*/ false, SourceLocation(), SourceLocation(),
8550         &Context->Idents.get("std"),
8551         /*PrevDecl*/ nullptr);
8552     NS->setImplicit();
8553     VaListTagDecl->setDeclContext(NS);
8554   }
8555 
8556   VaListTagDecl->startDefinition();
8557 
8558   const size_t NumFields = 5;
8559   QualType FieldTypes[NumFields];
8560   const char *FieldNames[NumFields];
8561 
8562   // void *__stack;
8563   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8564   FieldNames[0] = "__stack";
8565 
8566   // void *__gr_top;
8567   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8568   FieldNames[1] = "__gr_top";
8569 
8570   // void *__vr_top;
8571   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8572   FieldNames[2] = "__vr_top";
8573 
8574   // int __gr_offs;
8575   FieldTypes[3] = Context->IntTy;
8576   FieldNames[3] = "__gr_offs";
8577 
8578   // int __vr_offs;
8579   FieldTypes[4] = Context->IntTy;
8580   FieldNames[4] = "__vr_offs";
8581 
8582   // Create fields
8583   for (unsigned i = 0; i < NumFields; ++i) {
8584     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8585                                          VaListTagDecl,
8586                                          SourceLocation(),
8587                                          SourceLocation(),
8588                                          &Context->Idents.get(FieldNames[i]),
8589                                          FieldTypes[i], /*TInfo=*/nullptr,
8590                                          /*BitWidth=*/nullptr,
8591                                          /*Mutable=*/false,
8592                                          ICIS_NoInit);
8593     Field->setAccess(AS_public);
8594     VaListTagDecl->addDecl(Field);
8595   }
8596   VaListTagDecl->completeDefinition();
8597   Context->VaListTagDecl = VaListTagDecl;
8598   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8599 
8600   // } __builtin_va_list;
8601   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8602 }
8603 
8604 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8605   // typedef struct __va_list_tag {
8606   RecordDecl *VaListTagDecl;
8607 
8608   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8609   VaListTagDecl->startDefinition();
8610 
8611   const size_t NumFields = 5;
8612   QualType FieldTypes[NumFields];
8613   const char *FieldNames[NumFields];
8614 
8615   //   unsigned char gpr;
8616   FieldTypes[0] = Context->UnsignedCharTy;
8617   FieldNames[0] = "gpr";
8618 
8619   //   unsigned char fpr;
8620   FieldTypes[1] = Context->UnsignedCharTy;
8621   FieldNames[1] = "fpr";
8622 
8623   //   unsigned short reserved;
8624   FieldTypes[2] = Context->UnsignedShortTy;
8625   FieldNames[2] = "reserved";
8626 
8627   //   void* overflow_arg_area;
8628   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8629   FieldNames[3] = "overflow_arg_area";
8630 
8631   //   void* reg_save_area;
8632   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8633   FieldNames[4] = "reg_save_area";
8634 
8635   // Create fields
8636   for (unsigned i = 0; i < NumFields; ++i) {
8637     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8638                                          SourceLocation(),
8639                                          SourceLocation(),
8640                                          &Context->Idents.get(FieldNames[i]),
8641                                          FieldTypes[i], /*TInfo=*/nullptr,
8642                                          /*BitWidth=*/nullptr,
8643                                          /*Mutable=*/false,
8644                                          ICIS_NoInit);
8645     Field->setAccess(AS_public);
8646     VaListTagDecl->addDecl(Field);
8647   }
8648   VaListTagDecl->completeDefinition();
8649   Context->VaListTagDecl = VaListTagDecl;
8650   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8651 
8652   // } __va_list_tag;
8653   TypedefDecl *VaListTagTypedefDecl =
8654       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8655 
8656   QualType VaListTagTypedefType =
8657     Context->getTypedefType(VaListTagTypedefDecl);
8658 
8659   // typedef __va_list_tag __builtin_va_list[1];
8660   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8661   QualType VaListTagArrayType
8662     = Context->getConstantArrayType(VaListTagTypedefType,
8663                                     Size, nullptr, ArrayType::Normal, 0);
8664   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8665 }
8666 
8667 static TypedefDecl *
8668 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8669   // struct __va_list_tag {
8670   RecordDecl *VaListTagDecl;
8671   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8672   VaListTagDecl->startDefinition();
8673 
8674   const size_t NumFields = 4;
8675   QualType FieldTypes[NumFields];
8676   const char *FieldNames[NumFields];
8677 
8678   //   unsigned gp_offset;
8679   FieldTypes[0] = Context->UnsignedIntTy;
8680   FieldNames[0] = "gp_offset";
8681 
8682   //   unsigned fp_offset;
8683   FieldTypes[1] = Context->UnsignedIntTy;
8684   FieldNames[1] = "fp_offset";
8685 
8686   //   void* overflow_arg_area;
8687   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8688   FieldNames[2] = "overflow_arg_area";
8689 
8690   //   void* reg_save_area;
8691   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8692   FieldNames[3] = "reg_save_area";
8693 
8694   // Create fields
8695   for (unsigned i = 0; i < NumFields; ++i) {
8696     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8697                                          VaListTagDecl,
8698                                          SourceLocation(),
8699                                          SourceLocation(),
8700                                          &Context->Idents.get(FieldNames[i]),
8701                                          FieldTypes[i], /*TInfo=*/nullptr,
8702                                          /*BitWidth=*/nullptr,
8703                                          /*Mutable=*/false,
8704                                          ICIS_NoInit);
8705     Field->setAccess(AS_public);
8706     VaListTagDecl->addDecl(Field);
8707   }
8708   VaListTagDecl->completeDefinition();
8709   Context->VaListTagDecl = VaListTagDecl;
8710   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8711 
8712   // };
8713 
8714   // typedef struct __va_list_tag __builtin_va_list[1];
8715   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8716   QualType VaListTagArrayType = Context->getConstantArrayType(
8717       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8718   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8719 }
8720 
8721 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8722   // typedef int __builtin_va_list[4];
8723   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8724   QualType IntArrayType = Context->getConstantArrayType(
8725       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
8726   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8727 }
8728 
8729 static TypedefDecl *
8730 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8731   // struct __va_list
8732   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8733   if (Context->getLangOpts().CPlusPlus) {
8734     // namespace std { struct __va_list {
8735     NamespaceDecl *NS;
8736     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8737                                Context->getTranslationUnitDecl(),
8738                                /*Inline*/false, SourceLocation(),
8739                                SourceLocation(), &Context->Idents.get("std"),
8740                                /*PrevDecl*/ nullptr);
8741     NS->setImplicit();
8742     VaListDecl->setDeclContext(NS);
8743   }
8744 
8745   VaListDecl->startDefinition();
8746 
8747   // void * __ap;
8748   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8749                                        VaListDecl,
8750                                        SourceLocation(),
8751                                        SourceLocation(),
8752                                        &Context->Idents.get("__ap"),
8753                                        Context->getPointerType(Context->VoidTy),
8754                                        /*TInfo=*/nullptr,
8755                                        /*BitWidth=*/nullptr,
8756                                        /*Mutable=*/false,
8757                                        ICIS_NoInit);
8758   Field->setAccess(AS_public);
8759   VaListDecl->addDecl(Field);
8760 
8761   // };
8762   VaListDecl->completeDefinition();
8763   Context->VaListTagDecl = VaListDecl;
8764 
8765   // typedef struct __va_list __builtin_va_list;
8766   QualType T = Context->getRecordType(VaListDecl);
8767   return Context->buildImplicitTypedef(T, "__builtin_va_list");
8768 }
8769 
8770 static TypedefDecl *
8771 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8772   // struct __va_list_tag {
8773   RecordDecl *VaListTagDecl;
8774   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8775   VaListTagDecl->startDefinition();
8776 
8777   const size_t NumFields = 4;
8778   QualType FieldTypes[NumFields];
8779   const char *FieldNames[NumFields];
8780 
8781   //   long __gpr;
8782   FieldTypes[0] = Context->LongTy;
8783   FieldNames[0] = "__gpr";
8784 
8785   //   long __fpr;
8786   FieldTypes[1] = Context->LongTy;
8787   FieldNames[1] = "__fpr";
8788 
8789   //   void *__overflow_arg_area;
8790   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8791   FieldNames[2] = "__overflow_arg_area";
8792 
8793   //   void *__reg_save_area;
8794   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8795   FieldNames[3] = "__reg_save_area";
8796 
8797   // Create fields
8798   for (unsigned i = 0; i < NumFields; ++i) {
8799     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8800                                          VaListTagDecl,
8801                                          SourceLocation(),
8802                                          SourceLocation(),
8803                                          &Context->Idents.get(FieldNames[i]),
8804                                          FieldTypes[i], /*TInfo=*/nullptr,
8805                                          /*BitWidth=*/nullptr,
8806                                          /*Mutable=*/false,
8807                                          ICIS_NoInit);
8808     Field->setAccess(AS_public);
8809     VaListTagDecl->addDecl(Field);
8810   }
8811   VaListTagDecl->completeDefinition();
8812   Context->VaListTagDecl = VaListTagDecl;
8813   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8814 
8815   // };
8816 
8817   // typedef __va_list_tag __builtin_va_list[1];
8818   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8819   QualType VaListTagArrayType = Context->getConstantArrayType(
8820       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
8821 
8822   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8823 }
8824 
8825 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
8826   // typedef struct __va_list_tag {
8827   RecordDecl *VaListTagDecl;
8828   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8829   VaListTagDecl->startDefinition();
8830 
8831   const size_t NumFields = 3;
8832   QualType FieldTypes[NumFields];
8833   const char *FieldNames[NumFields];
8834 
8835   //   void *CurrentSavedRegisterArea;
8836   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8837   FieldNames[0] = "__current_saved_reg_area_pointer";
8838 
8839   //   void *SavedRegAreaEnd;
8840   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8841   FieldNames[1] = "__saved_reg_area_end_pointer";
8842 
8843   //   void *OverflowArea;
8844   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8845   FieldNames[2] = "__overflow_area_pointer";
8846 
8847   // Create fields
8848   for (unsigned i = 0; i < NumFields; ++i) {
8849     FieldDecl *Field = FieldDecl::Create(
8850         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8851         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8852         /*TInfo=*/nullptr,
8853         /*BitWidth=*/nullptr,
8854         /*Mutable=*/false, ICIS_NoInit);
8855     Field->setAccess(AS_public);
8856     VaListTagDecl->addDecl(Field);
8857   }
8858   VaListTagDecl->completeDefinition();
8859   Context->VaListTagDecl = VaListTagDecl;
8860   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8861 
8862   // } __va_list_tag;
8863   TypedefDecl *VaListTagTypedefDecl =
8864       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8865 
8866   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8867 
8868   // typedef __va_list_tag __builtin_va_list[1];
8869   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8870   QualType VaListTagArrayType = Context->getConstantArrayType(
8871       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8872 
8873   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8874 }
8875 
8876 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8877                                      TargetInfo::BuiltinVaListKind Kind) {
8878   switch (Kind) {
8879   case TargetInfo::CharPtrBuiltinVaList:
8880     return CreateCharPtrBuiltinVaListDecl(Context);
8881   case TargetInfo::VoidPtrBuiltinVaList:
8882     return CreateVoidPtrBuiltinVaListDecl(Context);
8883   case TargetInfo::AArch64ABIBuiltinVaList:
8884     return CreateAArch64ABIBuiltinVaListDecl(Context);
8885   case TargetInfo::PowerABIBuiltinVaList:
8886     return CreatePowerABIBuiltinVaListDecl(Context);
8887   case TargetInfo::X86_64ABIBuiltinVaList:
8888     return CreateX86_64ABIBuiltinVaListDecl(Context);
8889   case TargetInfo::PNaClABIBuiltinVaList:
8890     return CreatePNaClABIBuiltinVaListDecl(Context);
8891   case TargetInfo::AAPCSABIBuiltinVaList:
8892     return CreateAAPCSABIBuiltinVaListDecl(Context);
8893   case TargetInfo::SystemZBuiltinVaList:
8894     return CreateSystemZBuiltinVaListDecl(Context);
8895   case TargetInfo::HexagonBuiltinVaList:
8896     return CreateHexagonBuiltinVaListDecl(Context);
8897   }
8898 
8899   llvm_unreachable("Unhandled __builtin_va_list type kind");
8900 }
8901 
8902 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8903   if (!BuiltinVaListDecl) {
8904     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8905     assert(BuiltinVaListDecl->isImplicit());
8906   }
8907 
8908   return BuiltinVaListDecl;
8909 }
8910 
8911 Decl *ASTContext::getVaListTagDecl() const {
8912   // Force the creation of VaListTagDecl by building the __builtin_va_list
8913   // declaration.
8914   if (!VaListTagDecl)
8915     (void)getBuiltinVaListDecl();
8916 
8917   return VaListTagDecl;
8918 }
8919 
8920 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8921   if (!BuiltinMSVaListDecl)
8922     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8923 
8924   return BuiltinMSVaListDecl;
8925 }
8926 
8927 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8928   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8929 }
8930 
8931 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8932   assert(ObjCConstantStringType.isNull() &&
8933          "'NSConstantString' type already set!");
8934 
8935   ObjCConstantStringType = getObjCInterfaceType(Decl);
8936 }
8937 
8938 /// Retrieve the template name that corresponds to a non-empty
8939 /// lookup.
8940 TemplateName
8941 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8942                                       UnresolvedSetIterator End) const {
8943   unsigned size = End - Begin;
8944   assert(size > 1 && "set is not overloaded!");
8945 
8946   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8947                           size * sizeof(FunctionTemplateDecl*));
8948   auto *OT = new (memory) OverloadedTemplateStorage(size);
8949 
8950   NamedDecl **Storage = OT->getStorage();
8951   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8952     NamedDecl *D = *I;
8953     assert(isa<FunctionTemplateDecl>(D) ||
8954            isa<UnresolvedUsingValueDecl>(D) ||
8955            (isa<UsingShadowDecl>(D) &&
8956             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8957     *Storage++ = D;
8958   }
8959 
8960   return TemplateName(OT);
8961 }
8962 
8963 /// Retrieve a template name representing an unqualified-id that has been
8964 /// assumed to name a template for ADL purposes.
8965 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8966   auto *OT = new (*this) AssumedTemplateStorage(Name);
8967   return TemplateName(OT);
8968 }
8969 
8970 /// Retrieve the template name that represents a qualified
8971 /// template name such as \c std::vector.
8972 TemplateName
8973 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8974                                      bool TemplateKeyword,
8975                                      TemplateDecl *Template) const {
8976   assert(NNS && "Missing nested-name-specifier in qualified template name");
8977 
8978   // FIXME: Canonicalization?
8979   llvm::FoldingSetNodeID ID;
8980   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8981 
8982   void *InsertPos = nullptr;
8983   QualifiedTemplateName *QTN =
8984     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8985   if (!QTN) {
8986     QTN = new (*this, alignof(QualifiedTemplateName))
8987         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8988     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8989   }
8990 
8991   return TemplateName(QTN);
8992 }
8993 
8994 /// Retrieve the template name that represents a dependent
8995 /// template name such as \c MetaFun::template apply.
8996 TemplateName
8997 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8998                                      const IdentifierInfo *Name) const {
8999   assert((!NNS || NNS->isDependent()) &&
9000          "Nested name specifier must be dependent");
9001 
9002   llvm::FoldingSetNodeID ID;
9003   DependentTemplateName::Profile(ID, NNS, Name);
9004 
9005   void *InsertPos = nullptr;
9006   DependentTemplateName *QTN =
9007     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9008 
9009   if (QTN)
9010     return TemplateName(QTN);
9011 
9012   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9013   if (CanonNNS == NNS) {
9014     QTN = new (*this, alignof(DependentTemplateName))
9015         DependentTemplateName(NNS, Name);
9016   } else {
9017     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9018     QTN = new (*this, alignof(DependentTemplateName))
9019         DependentTemplateName(NNS, Name, Canon);
9020     DependentTemplateName *CheckQTN =
9021       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9022     assert(!CheckQTN && "Dependent type name canonicalization broken");
9023     (void)CheckQTN;
9024   }
9025 
9026   DependentTemplateNames.InsertNode(QTN, InsertPos);
9027   return TemplateName(QTN);
9028 }
9029 
9030 /// Retrieve the template name that represents a dependent
9031 /// template name such as \c MetaFun::template operator+.
9032 TemplateName
9033 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9034                                      OverloadedOperatorKind Operator) const {
9035   assert((!NNS || NNS->isDependent()) &&
9036          "Nested name specifier must be dependent");
9037 
9038   llvm::FoldingSetNodeID ID;
9039   DependentTemplateName::Profile(ID, NNS, Operator);
9040 
9041   void *InsertPos = nullptr;
9042   DependentTemplateName *QTN
9043     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9044 
9045   if (QTN)
9046     return TemplateName(QTN);
9047 
9048   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9049   if (CanonNNS == NNS) {
9050     QTN = new (*this, alignof(DependentTemplateName))
9051         DependentTemplateName(NNS, Operator);
9052   } else {
9053     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9054     QTN = new (*this, alignof(DependentTemplateName))
9055         DependentTemplateName(NNS, Operator, Canon);
9056 
9057     DependentTemplateName *CheckQTN
9058       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9059     assert(!CheckQTN && "Dependent template name canonicalization broken");
9060     (void)CheckQTN;
9061   }
9062 
9063   DependentTemplateNames.InsertNode(QTN, InsertPos);
9064   return TemplateName(QTN);
9065 }
9066 
9067 TemplateName
9068 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
9069                                          TemplateName replacement) const {
9070   llvm::FoldingSetNodeID ID;
9071   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
9072 
9073   void *insertPos = nullptr;
9074   SubstTemplateTemplateParmStorage *subst
9075     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9076 
9077   if (!subst) {
9078     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
9079     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9080   }
9081 
9082   return TemplateName(subst);
9083 }
9084 
9085 TemplateName
9086 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
9087                                        const TemplateArgument &ArgPack) const {
9088   auto &Self = const_cast<ASTContext &>(*this);
9089   llvm::FoldingSetNodeID ID;
9090   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
9091 
9092   void *InsertPos = nullptr;
9093   SubstTemplateTemplateParmPackStorage *Subst
9094     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9095 
9096   if (!Subst) {
9097     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
9098                                                            ArgPack.pack_size(),
9099                                                          ArgPack.pack_begin());
9100     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9101   }
9102 
9103   return TemplateName(Subst);
9104 }
9105 
9106 /// getFromTargetType - Given one of the integer types provided by
9107 /// TargetInfo, produce the corresponding type. The unsigned @p Type
9108 /// is actually a value of type @c TargetInfo::IntType.
9109 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9110   switch (Type) {
9111   case TargetInfo::NoInt: return {};
9112   case TargetInfo::SignedChar: return SignedCharTy;
9113   case TargetInfo::UnsignedChar: return UnsignedCharTy;
9114   case TargetInfo::SignedShort: return ShortTy;
9115   case TargetInfo::UnsignedShort: return UnsignedShortTy;
9116   case TargetInfo::SignedInt: return IntTy;
9117   case TargetInfo::UnsignedInt: return UnsignedIntTy;
9118   case TargetInfo::SignedLong: return LongTy;
9119   case TargetInfo::UnsignedLong: return UnsignedLongTy;
9120   case TargetInfo::SignedLongLong: return LongLongTy;
9121   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
9122   }
9123 
9124   llvm_unreachable("Unhandled TargetInfo::IntType value");
9125 }
9126 
9127 //===----------------------------------------------------------------------===//
9128 //                        Type Predicates.
9129 //===----------------------------------------------------------------------===//
9130 
9131 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9132 /// garbage collection attribute.
9133 ///
9134 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
9135   if (getLangOpts().getGC() == LangOptions::NonGC)
9136     return Qualifiers::GCNone;
9137 
9138   assert(getLangOpts().ObjC);
9139   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9140 
9141   // Default behaviour under objective-C's gc is for ObjC pointers
9142   // (or pointers to them) be treated as though they were declared
9143   // as __strong.
9144   if (GCAttrs == Qualifiers::GCNone) {
9145     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
9146       return Qualifiers::Strong;
9147     else if (Ty->isPointerType())
9148       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
9149   } else {
9150     // It's not valid to set GC attributes on anything that isn't a
9151     // pointer.
9152 #ifndef NDEBUG
9153     QualType CT = Ty->getCanonicalTypeInternal();
9154     while (const auto *AT = dyn_cast<ArrayType>(CT))
9155       CT = AT->getElementType();
9156     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9157 #endif
9158   }
9159   return GCAttrs;
9160 }
9161 
9162 //===----------------------------------------------------------------------===//
9163 //                        Type Compatibility Testing
9164 //===----------------------------------------------------------------------===//
9165 
9166 /// areCompatVectorTypes - Return true if the two specified vector types are
9167 /// compatible.
9168 static bool areCompatVectorTypes(const VectorType *LHS,
9169                                  const VectorType *RHS) {
9170   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9171   return LHS->getElementType() == RHS->getElementType() &&
9172          LHS->getNumElements() == RHS->getNumElements();
9173 }
9174 
9175 /// areCompatMatrixTypes - Return true if the two specified matrix types are
9176 /// compatible.
9177 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
9178                                  const ConstantMatrixType *RHS) {
9179   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9180   return LHS->getElementType() == RHS->getElementType() &&
9181          LHS->getNumRows() == RHS->getNumRows() &&
9182          LHS->getNumColumns() == RHS->getNumColumns();
9183 }
9184 
9185 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
9186                                           QualType SecondVec) {
9187   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9188   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9189 
9190   if (hasSameUnqualifiedType(FirstVec, SecondVec))
9191     return true;
9192 
9193   // Treat Neon vector types and most AltiVec vector types as if they are the
9194   // equivalent GCC vector types.
9195   const auto *First = FirstVec->castAs<VectorType>();
9196   const auto *Second = SecondVec->castAs<VectorType>();
9197   if (First->getNumElements() == Second->getNumElements() &&
9198       hasSameType(First->getElementType(), Second->getElementType()) &&
9199       First->getVectorKind() != VectorType::AltiVecPixel &&
9200       First->getVectorKind() != VectorType::AltiVecBool &&
9201       Second->getVectorKind() != VectorType::AltiVecPixel &&
9202       Second->getVectorKind() != VectorType::AltiVecBool &&
9203       First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9204       First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
9205       Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
9206       Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
9207     return true;
9208 
9209   return false;
9210 }
9211 
9212 /// getSVETypeSize - Return SVE vector or predicate register size.
9213 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9214   assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
9215   return Ty->getKind() == BuiltinType::SveBool
9216              ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
9217              : Context.getLangOpts().VScaleMin * 128;
9218 }
9219 
9220 bool ASTContext::areCompatibleSveTypes(QualType FirstType,
9221                                        QualType SecondType) {
9222   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9223           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9224          "Expected SVE builtin type and vector type!");
9225 
9226   auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9227     if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9228       if (const auto *VT = SecondType->getAs<VectorType>()) {
9229         // Predicates have the same representation as uint8 so we also have to
9230         // check the kind to make these types incompatible.
9231         if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
9232           return BT->getKind() == BuiltinType::SveBool;
9233         else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
9234           return VT->getElementType().getCanonicalType() ==
9235                  FirstType->getSveEltType(*this);
9236         else if (VT->getVectorKind() == VectorType::GenericVector)
9237           return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9238                  hasSameType(VT->getElementType(),
9239                              getBuiltinVectorTypeInfo(BT).ElementType);
9240       }
9241     }
9242     return false;
9243   };
9244 
9245   return IsValidCast(FirstType, SecondType) ||
9246          IsValidCast(SecondType, FirstType);
9247 }
9248 
9249 bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
9250                                           QualType SecondType) {
9251   assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
9252           (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
9253          "Expected SVE builtin type and vector type!");
9254 
9255   auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9256     const auto *BT = FirstType->getAs<BuiltinType>();
9257     if (!BT)
9258       return false;
9259 
9260     const auto *VecTy = SecondType->getAs<VectorType>();
9261     if (VecTy &&
9262         (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9263          VecTy->getVectorKind() == VectorType::GenericVector)) {
9264       const LangOptions::LaxVectorConversionKind LVCKind =
9265           getLangOpts().getLaxVectorConversions();
9266 
9267       // Can not convert between sve predicates and sve vectors because of
9268       // different size.
9269       if (BT->getKind() == BuiltinType::SveBool &&
9270           VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
9271         return false;
9272 
9273       // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9274       // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9275       // converts to VLAT and VLAT implicitly converts to GNUT."
9276       // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9277       // predicates.
9278       if (VecTy->getVectorKind() == VectorType::GenericVector &&
9279           getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9280         return false;
9281 
9282       // If -flax-vector-conversions=all is specified, the types are
9283       // certainly compatible.
9284       if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9285         return true;
9286 
9287       // If -flax-vector-conversions=integer is specified, the types are
9288       // compatible if the elements are integer types.
9289       if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9290         return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9291                FirstType->getSveEltType(*this)->isIntegerType();
9292     }
9293 
9294     return false;
9295   };
9296 
9297   return IsLaxCompatible(FirstType, SecondType) ||
9298          IsLaxCompatible(SecondType, FirstType);
9299 }
9300 
9301 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
9302   while (true) {
9303     // __strong id
9304     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9305       if (Attr->getAttrKind() == attr::ObjCOwnership)
9306         return true;
9307 
9308       Ty = Attr->getModifiedType();
9309 
9310     // X *__strong (...)
9311     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9312       Ty = Paren->getInnerType();
9313 
9314     // We do not want to look through typedefs, typeof(expr),
9315     // typeof(type), or any other way that the type is somehow
9316     // abstracted.
9317     } else {
9318       return false;
9319     }
9320   }
9321 }
9322 
9323 //===----------------------------------------------------------------------===//
9324 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9325 //===----------------------------------------------------------------------===//
9326 
9327 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9328 /// inheritance hierarchy of 'rProto'.
9329 bool
9330 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
9331                                            ObjCProtocolDecl *rProto) const {
9332   if (declaresSameEntity(lProto, rProto))
9333     return true;
9334   for (auto *PI : rProto->protocols())
9335     if (ProtocolCompatibleWithProtocol(lProto, PI))
9336       return true;
9337   return false;
9338 }
9339 
9340 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
9341 /// Class<pr1, ...>.
9342 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
9343     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9344   for (auto *lhsProto : lhs->quals()) {
9345     bool match = false;
9346     for (auto *rhsProto : rhs->quals()) {
9347       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9348         match = true;
9349         break;
9350       }
9351     }
9352     if (!match)
9353       return false;
9354   }
9355   return true;
9356 }
9357 
9358 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9359 /// ObjCQualifiedIDType.
9360 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
9361     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9362     bool compare) {
9363   // Allow id<P..> and an 'id' in all cases.
9364   if (lhs->isObjCIdType() || rhs->isObjCIdType())
9365     return true;
9366 
9367   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9368   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9369       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
9370     return false;
9371 
9372   if (lhs->isObjCQualifiedIdType()) {
9373     if (rhs->qual_empty()) {
9374       // If the RHS is a unqualified interface pointer "NSString*",
9375       // make sure we check the class hierarchy.
9376       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9377         for (auto *I : lhs->quals()) {
9378           // when comparing an id<P> on lhs with a static type on rhs,
9379           // see if static class implements all of id's protocols, directly or
9380           // through its super class and categories.
9381           if (!rhsID->ClassImplementsProtocol(I, true))
9382             return false;
9383         }
9384       }
9385       // If there are no qualifiers and no interface, we have an 'id'.
9386       return true;
9387     }
9388     // Both the right and left sides have qualifiers.
9389     for (auto *lhsProto : lhs->quals()) {
9390       bool match = false;
9391 
9392       // when comparing an id<P> on lhs with a static type on rhs,
9393       // see if static class implements all of id's protocols, directly or
9394       // through its super class and categories.
9395       for (auto *rhsProto : rhs->quals()) {
9396         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9397             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9398           match = true;
9399           break;
9400         }
9401       }
9402       // If the RHS is a qualified interface pointer "NSString<P>*",
9403       // make sure we check the class hierarchy.
9404       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9405         for (auto *I : lhs->quals()) {
9406           // when comparing an id<P> on lhs with a static type on rhs,
9407           // see if static class implements all of id's protocols, directly or
9408           // through its super class and categories.
9409           if (rhsID->ClassImplementsProtocol(I, true)) {
9410             match = true;
9411             break;
9412           }
9413         }
9414       }
9415       if (!match)
9416         return false;
9417     }
9418 
9419     return true;
9420   }
9421 
9422   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9423 
9424   if (lhs->getInterfaceType()) {
9425     // If both the right and left sides have qualifiers.
9426     for (auto *lhsProto : lhs->quals()) {
9427       bool match = false;
9428 
9429       // when comparing an id<P> on rhs with a static type on lhs,
9430       // see if static class implements all of id's protocols, directly or
9431       // through its super class and categories.
9432       // First, lhs protocols in the qualifier list must be found, direct
9433       // or indirect in rhs's qualifier list or it is a mismatch.
9434       for (auto *rhsProto : rhs->quals()) {
9435         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9436             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9437           match = true;
9438           break;
9439         }
9440       }
9441       if (!match)
9442         return false;
9443     }
9444 
9445     // Static class's protocols, or its super class or category protocols
9446     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9447     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9448       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9449       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9450       // This is rather dubious but matches gcc's behavior. If lhs has
9451       // no type qualifier and its class has no static protocol(s)
9452       // assume that it is mismatch.
9453       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9454         return false;
9455       for (auto *lhsProto : LHSInheritedProtocols) {
9456         bool match = false;
9457         for (auto *rhsProto : rhs->quals()) {
9458           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9459               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9460             match = true;
9461             break;
9462           }
9463         }
9464         if (!match)
9465           return false;
9466       }
9467     }
9468     return true;
9469   }
9470   return false;
9471 }
9472 
9473 /// canAssignObjCInterfaces - Return true if the two interface types are
9474 /// compatible for assignment from RHS to LHS.  This handles validation of any
9475 /// protocol qualifiers on the LHS or RHS.
9476 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
9477                                          const ObjCObjectPointerType *RHSOPT) {
9478   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9479   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9480 
9481   // If either type represents the built-in 'id' type, return true.
9482   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9483     return true;
9484 
9485   // Function object that propagates a successful result or handles
9486   // __kindof types.
9487   auto finish = [&](bool succeeded) -> bool {
9488     if (succeeded)
9489       return true;
9490 
9491     if (!RHS->isKindOfType())
9492       return false;
9493 
9494     // Strip off __kindof and protocol qualifiers, then check whether
9495     // we can assign the other way.
9496     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9497                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9498   };
9499 
9500   // Casts from or to id<P> are allowed when the other side has compatible
9501   // protocols.
9502   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9503     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9504   }
9505 
9506   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9507   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9508     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9509   }
9510 
9511   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9512   if (LHS->isObjCClass() && RHS->isObjCClass()) {
9513     return true;
9514   }
9515 
9516   // If we have 2 user-defined types, fall into that path.
9517   if (LHS->getInterface() && RHS->getInterface()) {
9518     return finish(canAssignObjCInterfaces(LHS, RHS));
9519   }
9520 
9521   return false;
9522 }
9523 
9524 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9525 /// for providing type-safety for objective-c pointers used to pass/return
9526 /// arguments in block literals. When passed as arguments, passing 'A*' where
9527 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9528 /// not OK. For the return type, the opposite is not OK.
9529 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
9530                                          const ObjCObjectPointerType *LHSOPT,
9531                                          const ObjCObjectPointerType *RHSOPT,
9532                                          bool BlockReturnType) {
9533 
9534   // Function object that propagates a successful result or handles
9535   // __kindof types.
9536   auto finish = [&](bool succeeded) -> bool {
9537     if (succeeded)
9538       return true;
9539 
9540     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9541     if (!Expected->isKindOfType())
9542       return false;
9543 
9544     // Strip off __kindof and protocol qualifiers, then check whether
9545     // we can assign the other way.
9546     return canAssignObjCInterfacesInBlockPointer(
9547              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9548              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9549              BlockReturnType);
9550   };
9551 
9552   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9553     return true;
9554 
9555   if (LHSOPT->isObjCBuiltinType()) {
9556     return finish(RHSOPT->isObjCBuiltinType() ||
9557                   RHSOPT->isObjCQualifiedIdType());
9558   }
9559 
9560   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9561     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9562       // Use for block parameters previous type checking for compatibility.
9563       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9564                     // Or corrected type checking as in non-compat mode.
9565                     (!BlockReturnType &&
9566                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9567     else
9568       return finish(ObjCQualifiedIdTypesAreCompatible(
9569           (BlockReturnType ? LHSOPT : RHSOPT),
9570           (BlockReturnType ? RHSOPT : LHSOPT), false));
9571   }
9572 
9573   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9574   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9575   if (LHS && RHS)  { // We have 2 user-defined types.
9576     if (LHS != RHS) {
9577       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9578         return finish(BlockReturnType);
9579       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9580         return finish(!BlockReturnType);
9581     }
9582     else
9583       return true;
9584   }
9585   return false;
9586 }
9587 
9588 /// Comparison routine for Objective-C protocols to be used with
9589 /// llvm::array_pod_sort.
9590 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9591                                       ObjCProtocolDecl * const *rhs) {
9592   return (*lhs)->getName().compare((*rhs)->getName());
9593 }
9594 
9595 /// getIntersectionOfProtocols - This routine finds the intersection of set
9596 /// of protocols inherited from two distinct objective-c pointer objects with
9597 /// the given common base.
9598 /// It is used to build composite qualifier list of the composite type of
9599 /// the conditional expression involving two objective-c pointer objects.
9600 static
9601 void getIntersectionOfProtocols(ASTContext &Context,
9602                                 const ObjCInterfaceDecl *CommonBase,
9603                                 const ObjCObjectPointerType *LHSOPT,
9604                                 const ObjCObjectPointerType *RHSOPT,
9605       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9606 
9607   const ObjCObjectType* LHS = LHSOPT->getObjectType();
9608   const ObjCObjectType* RHS = RHSOPT->getObjectType();
9609   assert(LHS->getInterface() && "LHS must have an interface base");
9610   assert(RHS->getInterface() && "RHS must have an interface base");
9611 
9612   // Add all of the protocols for the LHS.
9613   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9614 
9615   // Start with the protocol qualifiers.
9616   for (auto proto : LHS->quals()) {
9617     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9618   }
9619 
9620   // Also add the protocols associated with the LHS interface.
9621   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9622 
9623   // Add all of the protocols for the RHS.
9624   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9625 
9626   // Start with the protocol qualifiers.
9627   for (auto proto : RHS->quals()) {
9628     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9629   }
9630 
9631   // Also add the protocols associated with the RHS interface.
9632   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9633 
9634   // Compute the intersection of the collected protocol sets.
9635   for (auto proto : LHSProtocolSet) {
9636     if (RHSProtocolSet.count(proto))
9637       IntersectionSet.push_back(proto);
9638   }
9639 
9640   // Compute the set of protocols that is implied by either the common type or
9641   // the protocols within the intersection.
9642   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9643   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9644 
9645   // Remove any implied protocols from the list of inherited protocols.
9646   if (!ImpliedProtocols.empty()) {
9647     llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
9648       return ImpliedProtocols.contains(proto);
9649     });
9650   }
9651 
9652   // Sort the remaining protocols by name.
9653   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9654                        compareObjCProtocolsByName);
9655 }
9656 
9657 /// Determine whether the first type is a subtype of the second.
9658 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9659                                      QualType rhs) {
9660   // Common case: two object pointers.
9661   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9662   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9663   if (lhsOPT && rhsOPT)
9664     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9665 
9666   // Two block pointers.
9667   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9668   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9669   if (lhsBlock && rhsBlock)
9670     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9671 
9672   // If either is an unqualified 'id' and the other is a block, it's
9673   // acceptable.
9674   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9675       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9676     return true;
9677 
9678   return false;
9679 }
9680 
9681 // Check that the given Objective-C type argument lists are equivalent.
9682 static bool sameObjCTypeArgs(ASTContext &ctx,
9683                              const ObjCInterfaceDecl *iface,
9684                              ArrayRef<QualType> lhsArgs,
9685                              ArrayRef<QualType> rhsArgs,
9686                              bool stripKindOf) {
9687   if (lhsArgs.size() != rhsArgs.size())
9688     return false;
9689 
9690   ObjCTypeParamList *typeParams = iface->getTypeParamList();
9691   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9692     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9693       continue;
9694 
9695     switch (typeParams->begin()[i]->getVariance()) {
9696     case ObjCTypeParamVariance::Invariant:
9697       if (!stripKindOf ||
9698           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9699                            rhsArgs[i].stripObjCKindOfType(ctx))) {
9700         return false;
9701       }
9702       break;
9703 
9704     case ObjCTypeParamVariance::Covariant:
9705       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
9706         return false;
9707       break;
9708 
9709     case ObjCTypeParamVariance::Contravariant:
9710       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
9711         return false;
9712       break;
9713     }
9714   }
9715 
9716   return true;
9717 }
9718 
9719 QualType ASTContext::areCommonBaseCompatible(
9720            const ObjCObjectPointerType *Lptr,
9721            const ObjCObjectPointerType *Rptr) {
9722   const ObjCObjectType *LHS = Lptr->getObjectType();
9723   const ObjCObjectType *RHS = Rptr->getObjectType();
9724   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
9725   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
9726 
9727   if (!LDecl || !RDecl)
9728     return {};
9729 
9730   // When either LHS or RHS is a kindof type, we should return a kindof type.
9731   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
9732   // kindof(A).
9733   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
9734 
9735   // Follow the left-hand side up the class hierarchy until we either hit a
9736   // root or find the RHS. Record the ancestors in case we don't find it.
9737   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
9738     LHSAncestors;
9739   while (true) {
9740     // Record this ancestor. We'll need this if the common type isn't in the
9741     // path from the LHS to the root.
9742     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
9743 
9744     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
9745       // Get the type arguments.
9746       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
9747       bool anyChanges = false;
9748       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9749         // Both have type arguments, compare them.
9750         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9751                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9752                               /*stripKindOf=*/true))
9753           return {};
9754       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9755         // If only one has type arguments, the result will not have type
9756         // arguments.
9757         LHSTypeArgs = {};
9758         anyChanges = true;
9759       }
9760 
9761       // Compute the intersection of protocols.
9762       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9763       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
9764                                  Protocols);
9765       if (!Protocols.empty())
9766         anyChanges = true;
9767 
9768       // If anything in the LHS will have changed, build a new result type.
9769       // If we need to return a kindof type but LHS is not a kindof type, we
9770       // build a new result type.
9771       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
9772         QualType Result = getObjCInterfaceType(LHS->getInterface());
9773         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
9774                                    anyKindOf || LHS->isKindOfType());
9775         return getObjCObjectPointerType(Result);
9776       }
9777 
9778       return getObjCObjectPointerType(QualType(LHS, 0));
9779     }
9780 
9781     // Find the superclass.
9782     QualType LHSSuperType = LHS->getSuperClassType();
9783     if (LHSSuperType.isNull())
9784       break;
9785 
9786     LHS = LHSSuperType->castAs<ObjCObjectType>();
9787   }
9788 
9789   // We didn't find anything by following the LHS to its root; now check
9790   // the RHS against the cached set of ancestors.
9791   while (true) {
9792     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
9793     if (KnownLHS != LHSAncestors.end()) {
9794       LHS = KnownLHS->second;
9795 
9796       // Get the type arguments.
9797       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
9798       bool anyChanges = false;
9799       if (LHS->isSpecialized() && RHS->isSpecialized()) {
9800         // Both have type arguments, compare them.
9801         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
9802                               LHS->getTypeArgs(), RHS->getTypeArgs(),
9803                               /*stripKindOf=*/true))
9804           return {};
9805       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
9806         // If only one has type arguments, the result will not have type
9807         // arguments.
9808         RHSTypeArgs = {};
9809         anyChanges = true;
9810       }
9811 
9812       // Compute the intersection of protocols.
9813       SmallVector<ObjCProtocolDecl *, 8> Protocols;
9814       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
9815                                  Protocols);
9816       if (!Protocols.empty())
9817         anyChanges = true;
9818 
9819       // If we need to return a kindof type but RHS is not a kindof type, we
9820       // build a new result type.
9821       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
9822         QualType Result = getObjCInterfaceType(RHS->getInterface());
9823         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
9824                                    anyKindOf || RHS->isKindOfType());
9825         return getObjCObjectPointerType(Result);
9826       }
9827 
9828       return getObjCObjectPointerType(QualType(RHS, 0));
9829     }
9830 
9831     // Find the superclass of the RHS.
9832     QualType RHSSuperType = RHS->getSuperClassType();
9833     if (RHSSuperType.isNull())
9834       break;
9835 
9836     RHS = RHSSuperType->castAs<ObjCObjectType>();
9837   }
9838 
9839   return {};
9840 }
9841 
9842 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
9843                                          const ObjCObjectType *RHS) {
9844   assert(LHS->getInterface() && "LHS is not an interface type");
9845   assert(RHS->getInterface() && "RHS is not an interface type");
9846 
9847   // Verify that the base decls are compatible: the RHS must be a subclass of
9848   // the LHS.
9849   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
9850   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
9851   if (!IsSuperClass)
9852     return false;
9853 
9854   // If the LHS has protocol qualifiers, determine whether all of them are
9855   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
9856   // LHS).
9857   if (LHS->getNumProtocols() > 0) {
9858     // OK if conversion of LHS to SuperClass results in narrowing of types
9859     // ; i.e., SuperClass may implement at least one of the protocols
9860     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
9861     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
9862     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
9863     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
9864     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
9865     // qualifiers.
9866     for (auto *RHSPI : RHS->quals())
9867       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
9868     // If there is no protocols associated with RHS, it is not a match.
9869     if (SuperClassInheritedProtocols.empty())
9870       return false;
9871 
9872     for (const auto *LHSProto : LHS->quals()) {
9873       bool SuperImplementsProtocol = false;
9874       for (auto *SuperClassProto : SuperClassInheritedProtocols)
9875         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
9876           SuperImplementsProtocol = true;
9877           break;
9878         }
9879       if (!SuperImplementsProtocol)
9880         return false;
9881     }
9882   }
9883 
9884   // If the LHS is specialized, we may need to check type arguments.
9885   if (LHS->isSpecialized()) {
9886     // Follow the superclass chain until we've matched the LHS class in the
9887     // hierarchy. This substitutes type arguments through.
9888     const ObjCObjectType *RHSSuper = RHS;
9889     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
9890       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
9891 
9892     // If the RHS is specializd, compare type arguments.
9893     if (RHSSuper->isSpecialized() &&
9894         !sameObjCTypeArgs(*this, LHS->getInterface(),
9895                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
9896                           /*stripKindOf=*/true)) {
9897       return false;
9898     }
9899   }
9900 
9901   return true;
9902 }
9903 
9904 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
9905   // get the "pointed to" types
9906   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
9907   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
9908 
9909   if (!LHSOPT || !RHSOPT)
9910     return false;
9911 
9912   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
9913          canAssignObjCInterfaces(RHSOPT, LHSOPT);
9914 }
9915 
9916 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
9917   return canAssignObjCInterfaces(
9918       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
9919       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
9920 }
9921 
9922 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
9923 /// both shall have the identically qualified version of a compatible type.
9924 /// C99 6.2.7p1: Two types have compatible types if their types are the
9925 /// same. See 6.7.[2,3,5] for additional rules.
9926 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
9927                                     bool CompareUnqualified) {
9928   if (getLangOpts().CPlusPlus)
9929     return hasSameType(LHS, RHS);
9930 
9931   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9932 }
9933 
9934 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9935   return typesAreCompatible(LHS, RHS);
9936 }
9937 
9938 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9939   return !mergeTypes(LHS, RHS, true).isNull();
9940 }
9941 
9942 /// mergeTransparentUnionType - if T is a transparent union type and a member
9943 /// of T is compatible with SubType, return the merged type, else return
9944 /// QualType()
9945 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9946                                                bool OfBlockPointer,
9947                                                bool Unqualified) {
9948   if (const RecordType *UT = T->getAsUnionType()) {
9949     RecordDecl *UD = UT->getDecl();
9950     if (UD->hasAttr<TransparentUnionAttr>()) {
9951       for (const auto *I : UD->fields()) {
9952         QualType ET = I->getType().getUnqualifiedType();
9953         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9954         if (!MT.isNull())
9955           return MT;
9956       }
9957     }
9958   }
9959 
9960   return {};
9961 }
9962 
9963 /// mergeFunctionParameterTypes - merge two types which appear as function
9964 /// parameter types
9965 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9966                                                  bool OfBlockPointer,
9967                                                  bool Unqualified) {
9968   // GNU extension: two types are compatible if they appear as a function
9969   // argument, one of the types is a transparent union type and the other
9970   // type is compatible with a union member
9971   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9972                                               Unqualified);
9973   if (!lmerge.isNull())
9974     return lmerge;
9975 
9976   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9977                                               Unqualified);
9978   if (!rmerge.isNull())
9979     return rmerge;
9980 
9981   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9982 }
9983 
9984 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9985                                         bool OfBlockPointer, bool Unqualified,
9986                                         bool AllowCXX) {
9987   const auto *lbase = lhs->castAs<FunctionType>();
9988   const auto *rbase = rhs->castAs<FunctionType>();
9989   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9990   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9991   bool allLTypes = true;
9992   bool allRTypes = true;
9993 
9994   // Check return type
9995   QualType retType;
9996   if (OfBlockPointer) {
9997     QualType RHS = rbase->getReturnType();
9998     QualType LHS = lbase->getReturnType();
9999     bool UnqualifiedResult = Unqualified;
10000     if (!UnqualifiedResult)
10001       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10002     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10003   }
10004   else
10005     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10006                          Unqualified);
10007   if (retType.isNull())
10008     return {};
10009 
10010   if (Unqualified)
10011     retType = retType.getUnqualifiedType();
10012 
10013   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10014   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10015   if (Unqualified) {
10016     LRetType = LRetType.getUnqualifiedType();
10017     RRetType = RRetType.getUnqualifiedType();
10018   }
10019 
10020   if (getCanonicalType(retType) != LRetType)
10021     allLTypes = false;
10022   if (getCanonicalType(retType) != RRetType)
10023     allRTypes = false;
10024 
10025   // FIXME: double check this
10026   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10027   //                           rbase->getRegParmAttr() != 0 &&
10028   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10029   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10030   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10031 
10032   // Compatible functions must have compatible calling conventions
10033   if (lbaseInfo.getCC() != rbaseInfo.getCC())
10034     return {};
10035 
10036   // Regparm is part of the calling convention.
10037   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10038     return {};
10039   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10040     return {};
10041 
10042   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10043     return {};
10044   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10045     return {};
10046   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10047     return {};
10048 
10049   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
10050   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10051 
10052   if (lbaseInfo.getNoReturn() != NoReturn)
10053     allLTypes = false;
10054   if (rbaseInfo.getNoReturn() != NoReturn)
10055     allRTypes = false;
10056 
10057   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10058 
10059   if (lproto && rproto) { // two C99 style function prototypes
10060     assert((AllowCXX ||
10061             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10062            "C++ shouldn't be here");
10063     // Compatible functions must have the same number of parameters
10064     if (lproto->getNumParams() != rproto->getNumParams())
10065       return {};
10066 
10067     // Variadic and non-variadic functions aren't compatible
10068     if (lproto->isVariadic() != rproto->isVariadic())
10069       return {};
10070 
10071     if (lproto->getMethodQuals() != rproto->getMethodQuals())
10072       return {};
10073 
10074     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
10075     bool canUseLeft, canUseRight;
10076     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10077                                newParamInfos))
10078       return {};
10079 
10080     if (!canUseLeft)
10081       allLTypes = false;
10082     if (!canUseRight)
10083       allRTypes = false;
10084 
10085     // Check parameter type compatibility
10086     SmallVector<QualType, 10> types;
10087     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10088       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10089       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10090       QualType paramType = mergeFunctionParameterTypes(
10091           lParamType, rParamType, OfBlockPointer, Unqualified);
10092       if (paramType.isNull())
10093         return {};
10094 
10095       if (Unqualified)
10096         paramType = paramType.getUnqualifiedType();
10097 
10098       types.push_back(paramType);
10099       if (Unqualified) {
10100         lParamType = lParamType.getUnqualifiedType();
10101         rParamType = rParamType.getUnqualifiedType();
10102       }
10103 
10104       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10105         allLTypes = false;
10106       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10107         allRTypes = false;
10108     }
10109 
10110     if (allLTypes) return lhs;
10111     if (allRTypes) return rhs;
10112 
10113     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10114     EPI.ExtInfo = einfo;
10115     EPI.ExtParameterInfos =
10116         newParamInfos.empty() ? nullptr : newParamInfos.data();
10117     return getFunctionType(retType, types, EPI);
10118   }
10119 
10120   if (lproto) allRTypes = false;
10121   if (rproto) allLTypes = false;
10122 
10123   const FunctionProtoType *proto = lproto ? lproto : rproto;
10124   if (proto) {
10125     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10126     if (proto->isVariadic())
10127       return {};
10128     // Check that the types are compatible with the types that
10129     // would result from default argument promotions (C99 6.7.5.3p15).
10130     // The only types actually affected are promotable integer
10131     // types and floats, which would be passed as a different
10132     // type depending on whether the prototype is visible.
10133     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10134       QualType paramTy = proto->getParamType(i);
10135 
10136       // Look at the converted type of enum types, since that is the type used
10137       // to pass enum values.
10138       if (const auto *Enum = paramTy->getAs<EnumType>()) {
10139         paramTy = Enum->getDecl()->getIntegerType();
10140         if (paramTy.isNull())
10141           return {};
10142       }
10143 
10144       if (paramTy->isPromotableIntegerType() ||
10145           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10146         return {};
10147     }
10148 
10149     if (allLTypes) return lhs;
10150     if (allRTypes) return rhs;
10151 
10152     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
10153     EPI.ExtInfo = einfo;
10154     return getFunctionType(retType, proto->getParamTypes(), EPI);
10155   }
10156 
10157   if (allLTypes) return lhs;
10158   if (allRTypes) return rhs;
10159   return getFunctionNoProtoType(retType, einfo);
10160 }
10161 
10162 /// Given that we have an enum type and a non-enum type, try to merge them.
10163 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
10164                                      QualType other, bool isBlockReturnType) {
10165   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10166   // a signed integer type, or an unsigned integer type.
10167   // Compatibility is based on the underlying type, not the promotion
10168   // type.
10169   QualType underlyingType = ET->getDecl()->getIntegerType();
10170   if (underlyingType.isNull())
10171     return {};
10172   if (Context.hasSameType(underlyingType, other))
10173     return other;
10174 
10175   // In block return types, we're more permissive and accept any
10176   // integral type of the same size.
10177   if (isBlockReturnType && other->isIntegerType() &&
10178       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10179     return other;
10180 
10181   return {};
10182 }
10183 
10184 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
10185                                 bool OfBlockPointer,
10186                                 bool Unqualified, bool BlockReturnType) {
10187   // For C++ we will not reach this code with reference types (see below),
10188   // for OpenMP variant call overloading we might.
10189   //
10190   // C++ [expr]: If an expression initially has the type "reference to T", the
10191   // type is adjusted to "T" prior to any further analysis, the expression
10192   // designates the object or function denoted by the reference, and the
10193   // expression is an lvalue unless the reference is an rvalue reference and
10194   // the expression is a function call (possibly inside parentheses).
10195   auto *LHSRefTy = LHS->getAs<ReferenceType>();
10196   auto *RHSRefTy = RHS->getAs<ReferenceType>();
10197   if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10198       LHS->getTypeClass() == RHS->getTypeClass())
10199     return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10200                       OfBlockPointer, Unqualified, BlockReturnType);
10201   if (LHSRefTy || RHSRefTy)
10202     return {};
10203 
10204   if (Unqualified) {
10205     LHS = LHS.getUnqualifiedType();
10206     RHS = RHS.getUnqualifiedType();
10207   }
10208 
10209   QualType LHSCan = getCanonicalType(LHS),
10210            RHSCan = getCanonicalType(RHS);
10211 
10212   // If two types are identical, they are compatible.
10213   if (LHSCan == RHSCan)
10214     return LHS;
10215 
10216   // If the qualifiers are different, the types aren't compatible... mostly.
10217   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10218   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10219   if (LQuals != RQuals) {
10220     // If any of these qualifiers are different, we have a type
10221     // mismatch.
10222     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10223         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10224         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10225         LQuals.hasUnaligned() != RQuals.hasUnaligned())
10226       return {};
10227 
10228     // Exactly one GC qualifier difference is allowed: __strong is
10229     // okay if the other type has no GC qualifier but is an Objective
10230     // C object pointer (i.e. implicitly strong by default).  We fix
10231     // this by pretending that the unqualified type was actually
10232     // qualified __strong.
10233     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10234     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10235     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10236 
10237     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10238       return {};
10239 
10240     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10241       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
10242     }
10243     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10244       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
10245     }
10246     return {};
10247   }
10248 
10249   // Okay, qualifiers are equal.
10250 
10251   Type::TypeClass LHSClass = LHSCan->getTypeClass();
10252   Type::TypeClass RHSClass = RHSCan->getTypeClass();
10253 
10254   // We want to consider the two function types to be the same for these
10255   // comparisons, just force one to the other.
10256   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10257   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10258 
10259   // Same as above for arrays
10260   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10261     LHSClass = Type::ConstantArray;
10262   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10263     RHSClass = Type::ConstantArray;
10264 
10265   // ObjCInterfaces are just specialized ObjCObjects.
10266   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10267   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10268 
10269   // Canonicalize ExtVector -> Vector.
10270   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10271   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10272 
10273   // If the canonical type classes don't match.
10274   if (LHSClass != RHSClass) {
10275     // Note that we only have special rules for turning block enum
10276     // returns into block int returns, not vice-versa.
10277     if (const auto *ETy = LHS->getAs<EnumType>()) {
10278       return mergeEnumWithInteger(*this, ETy, RHS, false);
10279     }
10280     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10281       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10282     }
10283     // allow block pointer type to match an 'id' type.
10284     if (OfBlockPointer && !BlockReturnType) {
10285        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10286          return LHS;
10287       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10288         return RHS;
10289     }
10290 
10291     return {};
10292   }
10293 
10294   // The canonical type classes match.
10295   switch (LHSClass) {
10296 #define TYPE(Class, Base)
10297 #define ABSTRACT_TYPE(Class, Base)
10298 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10299 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10300 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
10301 #include "clang/AST/TypeNodes.inc"
10302     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10303 
10304   case Type::Auto:
10305   case Type::DeducedTemplateSpecialization:
10306   case Type::LValueReference:
10307   case Type::RValueReference:
10308   case Type::MemberPointer:
10309     llvm_unreachable("C++ should never be in mergeTypes");
10310 
10311   case Type::ObjCInterface:
10312   case Type::IncompleteArray:
10313   case Type::VariableArray:
10314   case Type::FunctionProto:
10315   case Type::ExtVector:
10316     llvm_unreachable("Types are eliminated above");
10317 
10318   case Type::Pointer:
10319   {
10320     // Merge two pointer types, while trying to preserve typedef info
10321     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10322     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10323     if (Unqualified) {
10324       LHSPointee = LHSPointee.getUnqualifiedType();
10325       RHSPointee = RHSPointee.getUnqualifiedType();
10326     }
10327     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10328                                      Unqualified);
10329     if (ResultType.isNull())
10330       return {};
10331     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10332       return LHS;
10333     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10334       return RHS;
10335     return getPointerType(ResultType);
10336   }
10337   case Type::BlockPointer:
10338   {
10339     // Merge two block pointer types, while trying to preserve typedef info
10340     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10341     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10342     if (Unqualified) {
10343       LHSPointee = LHSPointee.getUnqualifiedType();
10344       RHSPointee = RHSPointee.getUnqualifiedType();
10345     }
10346     if (getLangOpts().OpenCL) {
10347       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10348       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10349       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10350       // 6.12.5) thus the following check is asymmetric.
10351       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10352         return {};
10353       LHSPteeQual.removeAddressSpace();
10354       RHSPteeQual.removeAddressSpace();
10355       LHSPointee =
10356           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10357       RHSPointee =
10358           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10359     }
10360     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10361                                      Unqualified);
10362     if (ResultType.isNull())
10363       return {};
10364     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10365       return LHS;
10366     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10367       return RHS;
10368     return getBlockPointerType(ResultType);
10369   }
10370   case Type::Atomic:
10371   {
10372     // Merge two pointer types, while trying to preserve typedef info
10373     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10374     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10375     if (Unqualified) {
10376       LHSValue = LHSValue.getUnqualifiedType();
10377       RHSValue = RHSValue.getUnqualifiedType();
10378     }
10379     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10380                                      Unqualified);
10381     if (ResultType.isNull())
10382       return {};
10383     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10384       return LHS;
10385     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10386       return RHS;
10387     return getAtomicType(ResultType);
10388   }
10389   case Type::ConstantArray:
10390   {
10391     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10392     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10393     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10394       return {};
10395 
10396     QualType LHSElem = getAsArrayType(LHS)->getElementType();
10397     QualType RHSElem = getAsArrayType(RHS)->getElementType();
10398     if (Unqualified) {
10399       LHSElem = LHSElem.getUnqualifiedType();
10400       RHSElem = RHSElem.getUnqualifiedType();
10401     }
10402 
10403     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10404     if (ResultType.isNull())
10405       return {};
10406 
10407     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10408     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10409 
10410     // If either side is a variable array, and both are complete, check whether
10411     // the current dimension is definite.
10412     if (LVAT || RVAT) {
10413       auto SizeFetch = [this](const VariableArrayType* VAT,
10414           const ConstantArrayType* CAT)
10415           -> std::pair<bool,llvm::APInt> {
10416         if (VAT) {
10417           Optional<llvm::APSInt> TheInt;
10418           Expr *E = VAT->getSizeExpr();
10419           if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10420             return std::make_pair(true, *TheInt);
10421           return std::make_pair(false, llvm::APSInt());
10422         }
10423         if (CAT)
10424           return std::make_pair(true, CAT->getSize());
10425         return std::make_pair(false, llvm::APInt());
10426       };
10427 
10428       bool HaveLSize, HaveRSize;
10429       llvm::APInt LSize, RSize;
10430       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10431       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10432       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10433         return {}; // Definite, but unequal, array dimension
10434     }
10435 
10436     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10437       return LHS;
10438     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10439       return RHS;
10440     if (LCAT)
10441       return getConstantArrayType(ResultType, LCAT->getSize(),
10442                                   LCAT->getSizeExpr(),
10443                                   ArrayType::ArraySizeModifier(), 0);
10444     if (RCAT)
10445       return getConstantArrayType(ResultType, RCAT->getSize(),
10446                                   RCAT->getSizeExpr(),
10447                                   ArrayType::ArraySizeModifier(), 0);
10448     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10449       return LHS;
10450     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10451       return RHS;
10452     if (LVAT) {
10453       // FIXME: This isn't correct! But tricky to implement because
10454       // the array's size has to be the size of LHS, but the type
10455       // has to be different.
10456       return LHS;
10457     }
10458     if (RVAT) {
10459       // FIXME: This isn't correct! But tricky to implement because
10460       // the array's size has to be the size of RHS, but the type
10461       // has to be different.
10462       return RHS;
10463     }
10464     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10465     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10466     return getIncompleteArrayType(ResultType,
10467                                   ArrayType::ArraySizeModifier(), 0);
10468   }
10469   case Type::FunctionNoProto:
10470     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
10471   case Type::Record:
10472   case Type::Enum:
10473     return {};
10474   case Type::Builtin:
10475     // Only exactly equal builtin types are compatible, which is tested above.
10476     return {};
10477   case Type::Complex:
10478     // Distinct complex types are incompatible.
10479     return {};
10480   case Type::Vector:
10481     // FIXME: The merged type should be an ExtVector!
10482     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10483                              RHSCan->castAs<VectorType>()))
10484       return LHS;
10485     return {};
10486   case Type::ConstantMatrix:
10487     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
10488                              RHSCan->castAs<ConstantMatrixType>()))
10489       return LHS;
10490     return {};
10491   case Type::ObjCObject: {
10492     // Check if the types are assignment compatible.
10493     // FIXME: This should be type compatibility, e.g. whether
10494     // "LHS x; RHS x;" at global scope is legal.
10495     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
10496                                 RHS->castAs<ObjCObjectType>()))
10497       return LHS;
10498     return {};
10499   }
10500   case Type::ObjCObjectPointer:
10501     if (OfBlockPointer) {
10502       if (canAssignObjCInterfacesInBlockPointer(
10503               LHS->castAs<ObjCObjectPointerType>(),
10504               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10505         return LHS;
10506       return {};
10507     }
10508     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
10509                                 RHS->castAs<ObjCObjectPointerType>()))
10510       return LHS;
10511     return {};
10512   case Type::Pipe:
10513     assert(LHS != RHS &&
10514            "Equivalent pipe types should have already been handled!");
10515     return {};
10516   case Type::BitInt: {
10517     // Merge two bit-precise int types, while trying to preserve typedef info.
10518     bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10519     bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10520     unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10521     unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10522 
10523     // Like unsigned/int, shouldn't have a type if they don't match.
10524     if (LHSUnsigned != RHSUnsigned)
10525       return {};
10526 
10527     if (LHSBits != RHSBits)
10528       return {};
10529     return LHS;
10530   }
10531   }
10532 
10533   llvm_unreachable("Invalid Type::Class!");
10534 }
10535 
10536 bool ASTContext::mergeExtParameterInfo(
10537     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10538     bool &CanUseFirst, bool &CanUseSecond,
10539     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
10540   assert(NewParamInfos.empty() && "param info list not empty");
10541   CanUseFirst = CanUseSecond = true;
10542   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10543   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10544 
10545   // Fast path: if the first type doesn't have ext parameter infos,
10546   // we match if and only if the second type also doesn't have them.
10547   if (!FirstHasInfo && !SecondHasInfo)
10548     return true;
10549 
10550   bool NeedParamInfo = false;
10551   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10552                           : SecondFnType->getExtParameterInfos().size();
10553 
10554   for (size_t I = 0; I < E; ++I) {
10555     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10556     if (FirstHasInfo)
10557       FirstParam = FirstFnType->getExtParameterInfo(I);
10558     if (SecondHasInfo)
10559       SecondParam = SecondFnType->getExtParameterInfo(I);
10560 
10561     // Cannot merge unless everything except the noescape flag matches.
10562     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10563       return false;
10564 
10565     bool FirstNoEscape = FirstParam.isNoEscape();
10566     bool SecondNoEscape = SecondParam.isNoEscape();
10567     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10568     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10569     if (NewParamInfos.back().getOpaqueValue())
10570       NeedParamInfo = true;
10571     if (FirstNoEscape != IsNoEscape)
10572       CanUseFirst = false;
10573     if (SecondNoEscape != IsNoEscape)
10574       CanUseSecond = false;
10575   }
10576 
10577   if (!NeedParamInfo)
10578     NewParamInfos.clear();
10579 
10580   return true;
10581 }
10582 
10583 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10584   ObjCLayouts[CD] = nullptr;
10585 }
10586 
10587 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10588 /// 'RHS' attributes and returns the merged version; including for function
10589 /// return types.
10590 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10591   QualType LHSCan = getCanonicalType(LHS),
10592   RHSCan = getCanonicalType(RHS);
10593   // If two types are identical, they are compatible.
10594   if (LHSCan == RHSCan)
10595     return LHS;
10596   if (RHSCan->isFunctionType()) {
10597     if (!LHSCan->isFunctionType())
10598       return {};
10599     QualType OldReturnType =
10600         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10601     QualType NewReturnType =
10602         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10603     QualType ResReturnType =
10604       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10605     if (ResReturnType.isNull())
10606       return {};
10607     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10608       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10609       // In either case, use OldReturnType to build the new function type.
10610       const auto *F = LHS->castAs<FunctionType>();
10611       if (const auto *FPT = cast<FunctionProtoType>(F)) {
10612         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10613         EPI.ExtInfo = getFunctionExtInfo(LHS);
10614         QualType ResultType =
10615             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10616         return ResultType;
10617       }
10618     }
10619     return {};
10620   }
10621 
10622   // If the qualifiers are different, the types can still be merged.
10623   Qualifiers LQuals = LHSCan.getLocalQualifiers();
10624   Qualifiers RQuals = RHSCan.getLocalQualifiers();
10625   if (LQuals != RQuals) {
10626     // If any of these qualifiers are different, we have a type mismatch.
10627     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10628         LQuals.getAddressSpace() != RQuals.getAddressSpace())
10629       return {};
10630 
10631     // Exactly one GC qualifier difference is allowed: __strong is
10632     // okay if the other type has no GC qualifier but is an Objective
10633     // C object pointer (i.e. implicitly strong by default).  We fix
10634     // this by pretending that the unqualified type was actually
10635     // qualified __strong.
10636     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10637     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10638     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10639 
10640     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10641       return {};
10642 
10643     if (GC_L == Qualifiers::Strong)
10644       return LHS;
10645     if (GC_R == Qualifiers::Strong)
10646       return RHS;
10647     return {};
10648   }
10649 
10650   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10651     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10652     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10653     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10654     if (ResQT == LHSBaseQT)
10655       return LHS;
10656     if (ResQT == RHSBaseQT)
10657       return RHS;
10658   }
10659   return {};
10660 }
10661 
10662 //===----------------------------------------------------------------------===//
10663 //                         Integer Predicates
10664 //===----------------------------------------------------------------------===//
10665 
10666 unsigned ASTContext::getIntWidth(QualType T) const {
10667   if (const auto *ET = T->getAs<EnumType>())
10668     T = ET->getDecl()->getIntegerType();
10669   if (T->isBooleanType())
10670     return 1;
10671   if (const auto *EIT = T->getAs<BitIntType>())
10672     return EIT->getNumBits();
10673   // For builtin types, just use the standard type sizing method
10674   return (unsigned)getTypeSize(T);
10675 }
10676 
10677 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10678   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
10679          "Unexpected type");
10680 
10681   // Turn <4 x signed int> -> <4 x unsigned int>
10682   if (const auto *VTy = T->getAs<VectorType>())
10683     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
10684                          VTy->getNumElements(), VTy->getVectorKind());
10685 
10686   // For _BitInt, return an unsigned _BitInt with same width.
10687   if (const auto *EITy = T->getAs<BitIntType>())
10688     return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
10689 
10690   // For enums, get the underlying integer type of the enum, and let the general
10691   // integer type signchanging code handle it.
10692   if (const auto *ETy = T->getAs<EnumType>())
10693     T = ETy->getDecl()->getIntegerType();
10694 
10695   switch (T->castAs<BuiltinType>()->getKind()) {
10696   case BuiltinType::Char_S:
10697   case BuiltinType::SChar:
10698     return UnsignedCharTy;
10699   case BuiltinType::Short:
10700     return UnsignedShortTy;
10701   case BuiltinType::Int:
10702     return UnsignedIntTy;
10703   case BuiltinType::Long:
10704     return UnsignedLongTy;
10705   case BuiltinType::LongLong:
10706     return UnsignedLongLongTy;
10707   case BuiltinType::Int128:
10708     return UnsignedInt128Ty;
10709   // wchar_t is special. It is either signed or not, but when it's signed,
10710   // there's no matching "unsigned wchar_t". Therefore we return the unsigned
10711   // version of it's underlying type instead.
10712   case BuiltinType::WChar_S:
10713     return getUnsignedWCharType();
10714 
10715   case BuiltinType::ShortAccum:
10716     return UnsignedShortAccumTy;
10717   case BuiltinType::Accum:
10718     return UnsignedAccumTy;
10719   case BuiltinType::LongAccum:
10720     return UnsignedLongAccumTy;
10721   case BuiltinType::SatShortAccum:
10722     return SatUnsignedShortAccumTy;
10723   case BuiltinType::SatAccum:
10724     return SatUnsignedAccumTy;
10725   case BuiltinType::SatLongAccum:
10726     return SatUnsignedLongAccumTy;
10727   case BuiltinType::ShortFract:
10728     return UnsignedShortFractTy;
10729   case BuiltinType::Fract:
10730     return UnsignedFractTy;
10731   case BuiltinType::LongFract:
10732     return UnsignedLongFractTy;
10733   case BuiltinType::SatShortFract:
10734     return SatUnsignedShortFractTy;
10735   case BuiltinType::SatFract:
10736     return SatUnsignedFractTy;
10737   case BuiltinType::SatLongFract:
10738     return SatUnsignedLongFractTy;
10739   default:
10740     llvm_unreachable("Unexpected signed integer or fixed point type");
10741   }
10742 }
10743 
10744 QualType ASTContext::getCorrespondingSignedType(QualType T) const {
10745   assert((T->hasUnsignedIntegerRepresentation() ||
10746           T->isUnsignedFixedPointType()) &&
10747          "Unexpected type");
10748 
10749   // Turn <4 x unsigned int> -> <4 x signed int>
10750   if (const auto *VTy = T->getAs<VectorType>())
10751     return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
10752                          VTy->getNumElements(), VTy->getVectorKind());
10753 
10754   // For _BitInt, return a signed _BitInt with same width.
10755   if (const auto *EITy = T->getAs<BitIntType>())
10756     return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
10757 
10758   // For enums, get the underlying integer type of the enum, and let the general
10759   // integer type signchanging code handle it.
10760   if (const auto *ETy = T->getAs<EnumType>())
10761     T = ETy->getDecl()->getIntegerType();
10762 
10763   switch (T->castAs<BuiltinType>()->getKind()) {
10764   case BuiltinType::Char_U:
10765   case BuiltinType::UChar:
10766     return SignedCharTy;
10767   case BuiltinType::UShort:
10768     return ShortTy;
10769   case BuiltinType::UInt:
10770     return IntTy;
10771   case BuiltinType::ULong:
10772     return LongTy;
10773   case BuiltinType::ULongLong:
10774     return LongLongTy;
10775   case BuiltinType::UInt128:
10776     return Int128Ty;
10777   // wchar_t is special. It is either unsigned or not, but when it's unsigned,
10778   // there's no matching "signed wchar_t". Therefore we return the signed
10779   // version of it's underlying type instead.
10780   case BuiltinType::WChar_U:
10781     return getSignedWCharType();
10782 
10783   case BuiltinType::UShortAccum:
10784     return ShortAccumTy;
10785   case BuiltinType::UAccum:
10786     return AccumTy;
10787   case BuiltinType::ULongAccum:
10788     return LongAccumTy;
10789   case BuiltinType::SatUShortAccum:
10790     return SatShortAccumTy;
10791   case BuiltinType::SatUAccum:
10792     return SatAccumTy;
10793   case BuiltinType::SatULongAccum:
10794     return SatLongAccumTy;
10795   case BuiltinType::UShortFract:
10796     return ShortFractTy;
10797   case BuiltinType::UFract:
10798     return FractTy;
10799   case BuiltinType::ULongFract:
10800     return LongFractTy;
10801   case BuiltinType::SatUShortFract:
10802     return SatShortFractTy;
10803   case BuiltinType::SatUFract:
10804     return SatFractTy;
10805   case BuiltinType::SatULongFract:
10806     return SatLongFractTy;
10807   default:
10808     llvm_unreachable("Unexpected unsigned integer or fixed point type");
10809   }
10810 }
10811 
10812 ASTMutationListener::~ASTMutationListener() = default;
10813 
10814 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
10815                                             QualType ReturnType) {}
10816 
10817 //===----------------------------------------------------------------------===//
10818 //                          Builtin Type Computation
10819 //===----------------------------------------------------------------------===//
10820 
10821 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
10822 /// pointer over the consumed characters.  This returns the resultant type.  If
10823 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
10824 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
10825 /// a vector of "i*".
10826 ///
10827 /// RequiresICE is filled in on return to indicate whether the value is required
10828 /// to be an Integer Constant Expression.
10829 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
10830                                   ASTContext::GetBuiltinTypeError &Error,
10831                                   bool &RequiresICE,
10832                                   bool AllowTypeModifiers) {
10833   // Modifiers.
10834   int HowLong = 0;
10835   bool Signed = false, Unsigned = false;
10836   RequiresICE = false;
10837 
10838   // Read the prefixed modifiers first.
10839   bool Done = false;
10840   #ifndef NDEBUG
10841   bool IsSpecial = false;
10842   #endif
10843   while (!Done) {
10844     switch (*Str++) {
10845     default: Done = true; --Str; break;
10846     case 'I':
10847       RequiresICE = true;
10848       break;
10849     case 'S':
10850       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
10851       assert(!Signed && "Can't use 'S' modifier multiple times!");
10852       Signed = true;
10853       break;
10854     case 'U':
10855       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
10856       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
10857       Unsigned = true;
10858       break;
10859     case 'L':
10860       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
10861       assert(HowLong <= 2 && "Can't have LLLL modifier");
10862       ++HowLong;
10863       break;
10864     case 'N':
10865       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
10866       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10867       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
10868       #ifndef NDEBUG
10869       IsSpecial = true;
10870       #endif
10871       if (Context.getTargetInfo().getLongWidth() == 32)
10872         ++HowLong;
10873       break;
10874     case 'W':
10875       // This modifier represents int64 type.
10876       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10877       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
10878       #ifndef NDEBUG
10879       IsSpecial = true;
10880       #endif
10881       switch (Context.getTargetInfo().getInt64Type()) {
10882       default:
10883         llvm_unreachable("Unexpected integer type");
10884       case TargetInfo::SignedLong:
10885         HowLong = 1;
10886         break;
10887       case TargetInfo::SignedLongLong:
10888         HowLong = 2;
10889         break;
10890       }
10891       break;
10892     case 'Z':
10893       // This modifier represents int32 type.
10894       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10895       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
10896       #ifndef NDEBUG
10897       IsSpecial = true;
10898       #endif
10899       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
10900       default:
10901         llvm_unreachable("Unexpected integer type");
10902       case TargetInfo::SignedInt:
10903         HowLong = 0;
10904         break;
10905       case TargetInfo::SignedLong:
10906         HowLong = 1;
10907         break;
10908       case TargetInfo::SignedLongLong:
10909         HowLong = 2;
10910         break;
10911       }
10912       break;
10913     case 'O':
10914       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
10915       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
10916       #ifndef NDEBUG
10917       IsSpecial = true;
10918       #endif
10919       if (Context.getLangOpts().OpenCL)
10920         HowLong = 1;
10921       else
10922         HowLong = 2;
10923       break;
10924     }
10925   }
10926 
10927   QualType Type;
10928 
10929   // Read the base type.
10930   switch (*Str++) {
10931   default: llvm_unreachable("Unknown builtin type letter!");
10932   case 'x':
10933     assert(HowLong == 0 && !Signed && !Unsigned &&
10934            "Bad modifiers used with 'x'!");
10935     Type = Context.Float16Ty;
10936     break;
10937   case 'y':
10938     assert(HowLong == 0 && !Signed && !Unsigned &&
10939            "Bad modifiers used with 'y'!");
10940     Type = Context.BFloat16Ty;
10941     break;
10942   case 'v':
10943     assert(HowLong == 0 && !Signed && !Unsigned &&
10944            "Bad modifiers used with 'v'!");
10945     Type = Context.VoidTy;
10946     break;
10947   case 'h':
10948     assert(HowLong == 0 && !Signed && !Unsigned &&
10949            "Bad modifiers used with 'h'!");
10950     Type = Context.HalfTy;
10951     break;
10952   case 'f':
10953     assert(HowLong == 0 && !Signed && !Unsigned &&
10954            "Bad modifiers used with 'f'!");
10955     Type = Context.FloatTy;
10956     break;
10957   case 'd':
10958     assert(HowLong < 3 && !Signed && !Unsigned &&
10959            "Bad modifiers used with 'd'!");
10960     if (HowLong == 1)
10961       Type = Context.LongDoubleTy;
10962     else if (HowLong == 2)
10963       Type = Context.Float128Ty;
10964     else
10965       Type = Context.DoubleTy;
10966     break;
10967   case 's':
10968     assert(HowLong == 0 && "Bad modifiers used with 's'!");
10969     if (Unsigned)
10970       Type = Context.UnsignedShortTy;
10971     else
10972       Type = Context.ShortTy;
10973     break;
10974   case 'i':
10975     if (HowLong == 3)
10976       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
10977     else if (HowLong == 2)
10978       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
10979     else if (HowLong == 1)
10980       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
10981     else
10982       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
10983     break;
10984   case 'c':
10985     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
10986     if (Signed)
10987       Type = Context.SignedCharTy;
10988     else if (Unsigned)
10989       Type = Context.UnsignedCharTy;
10990     else
10991       Type = Context.CharTy;
10992     break;
10993   case 'b': // boolean
10994     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
10995     Type = Context.BoolTy;
10996     break;
10997   case 'z':  // size_t.
10998     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
10999     Type = Context.getSizeType();
11000     break;
11001   case 'w':  // wchar_t.
11002     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11003     Type = Context.getWideCharType();
11004     break;
11005   case 'F':
11006     Type = Context.getCFConstantStringType();
11007     break;
11008   case 'G':
11009     Type = Context.getObjCIdType();
11010     break;
11011   case 'H':
11012     Type = Context.getObjCSelType();
11013     break;
11014   case 'M':
11015     Type = Context.getObjCSuperType();
11016     break;
11017   case 'a':
11018     Type = Context.getBuiltinVaListType();
11019     assert(!Type.isNull() && "builtin va list type not initialized!");
11020     break;
11021   case 'A':
11022     // This is a "reference" to a va_list; however, what exactly
11023     // this means depends on how va_list is defined. There are two
11024     // different kinds of va_list: ones passed by value, and ones
11025     // passed by reference.  An example of a by-value va_list is
11026     // x86, where va_list is a char*. An example of by-ref va_list
11027     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11028     // we want this argument to be a char*&; for x86-64, we want
11029     // it to be a __va_list_tag*.
11030     Type = Context.getBuiltinVaListType();
11031     assert(!Type.isNull() && "builtin va list type not initialized!");
11032     if (Type->isArrayType())
11033       Type = Context.getArrayDecayedType(Type);
11034     else
11035       Type = Context.getLValueReferenceType(Type);
11036     break;
11037   case 'q': {
11038     char *End;
11039     unsigned NumElements = strtoul(Str, &End, 10);
11040     assert(End != Str && "Missing vector size");
11041     Str = End;
11042 
11043     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11044                                              RequiresICE, false);
11045     assert(!RequiresICE && "Can't require vector ICE");
11046 
11047     Type = Context.getScalableVectorType(ElementType, NumElements);
11048     break;
11049   }
11050   case 'V': {
11051     char *End;
11052     unsigned NumElements = strtoul(Str, &End, 10);
11053     assert(End != Str && "Missing vector size");
11054     Str = End;
11055 
11056     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11057                                              RequiresICE, false);
11058     assert(!RequiresICE && "Can't require vector ICE");
11059 
11060     // TODO: No way to make AltiVec vectors in builtins yet.
11061     Type = Context.getVectorType(ElementType, NumElements,
11062                                  VectorType::GenericVector);
11063     break;
11064   }
11065   case 'E': {
11066     char *End;
11067 
11068     unsigned NumElements = strtoul(Str, &End, 10);
11069     assert(End != Str && "Missing vector size");
11070 
11071     Str = End;
11072 
11073     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11074                                              false);
11075     Type = Context.getExtVectorType(ElementType, NumElements);
11076     break;
11077   }
11078   case 'X': {
11079     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11080                                              false);
11081     assert(!RequiresICE && "Can't require complex ICE");
11082     Type = Context.getComplexType(ElementType);
11083     break;
11084   }
11085   case 'Y':
11086     Type = Context.getPointerDiffType();
11087     break;
11088   case 'P':
11089     Type = Context.getFILEType();
11090     if (Type.isNull()) {
11091       Error = ASTContext::GE_Missing_stdio;
11092       return {};
11093     }
11094     break;
11095   case 'J':
11096     if (Signed)
11097       Type = Context.getsigjmp_bufType();
11098     else
11099       Type = Context.getjmp_bufType();
11100 
11101     if (Type.isNull()) {
11102       Error = ASTContext::GE_Missing_setjmp;
11103       return {};
11104     }
11105     break;
11106   case 'K':
11107     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11108     Type = Context.getucontext_tType();
11109 
11110     if (Type.isNull()) {
11111       Error = ASTContext::GE_Missing_ucontext;
11112       return {};
11113     }
11114     break;
11115   case 'p':
11116     Type = Context.getProcessIDType();
11117     break;
11118   }
11119 
11120   // If there are modifiers and if we're allowed to parse them, go for it.
11121   Done = !AllowTypeModifiers;
11122   while (!Done) {
11123     switch (char c = *Str++) {
11124     default: Done = true; --Str; break;
11125     case '*':
11126     case '&': {
11127       // Both pointers and references can have their pointee types
11128       // qualified with an address space.
11129       char *End;
11130       unsigned AddrSpace = strtoul(Str, &End, 10);
11131       if (End != Str) {
11132         // Note AddrSpace == 0 is not the same as an unspecified address space.
11133         Type = Context.getAddrSpaceQualType(
11134           Type,
11135           Context.getLangASForBuiltinAddressSpace(AddrSpace));
11136         Str = End;
11137       }
11138       if (c == '*')
11139         Type = Context.getPointerType(Type);
11140       else
11141         Type = Context.getLValueReferenceType(Type);
11142       break;
11143     }
11144     // FIXME: There's no way to have a built-in with an rvalue ref arg.
11145     case 'C':
11146       Type = Type.withConst();
11147       break;
11148     case 'D':
11149       Type = Context.getVolatileType(Type);
11150       break;
11151     case 'R':
11152       Type = Type.withRestrict();
11153       break;
11154     }
11155   }
11156 
11157   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11158          "Integer constant 'I' type must be an integer");
11159 
11160   return Type;
11161 }
11162 
11163 // On some targets such as PowerPC, some of the builtins are defined with custom
11164 // type descriptors for target-dependent types. These descriptors are decoded in
11165 // other functions, but it may be useful to be able to fall back to default
11166 // descriptor decoding to define builtins mixing target-dependent and target-
11167 // independent types. This function allows decoding one type descriptor with
11168 // default decoding.
11169 QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11170                                    GetBuiltinTypeError &Error, bool &RequireICE,
11171                                    bool AllowTypeModifiers) const {
11172   return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11173 }
11174 
11175 /// GetBuiltinType - Return the type for the specified builtin.
11176 QualType ASTContext::GetBuiltinType(unsigned Id,
11177                                     GetBuiltinTypeError &Error,
11178                                     unsigned *IntegerConstantArgs) const {
11179   const char *TypeStr = BuiltinInfo.getTypeString(Id);
11180   if (TypeStr[0] == '\0') {
11181     Error = GE_Missing_type;
11182     return {};
11183   }
11184 
11185   SmallVector<QualType, 8> ArgTypes;
11186 
11187   bool RequiresICE = false;
11188   Error = GE_None;
11189   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11190                                        RequiresICE, true);
11191   if (Error != GE_None)
11192     return {};
11193 
11194   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11195 
11196   while (TypeStr[0] && TypeStr[0] != '.') {
11197     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11198     if (Error != GE_None)
11199       return {};
11200 
11201     // If this argument is required to be an IntegerConstantExpression and the
11202     // caller cares, fill in the bitmask we return.
11203     if (RequiresICE && IntegerConstantArgs)
11204       *IntegerConstantArgs |= 1 << ArgTypes.size();
11205 
11206     // Do array -> pointer decay.  The builtin should use the decayed type.
11207     if (Ty->isArrayType())
11208       Ty = getArrayDecayedType(Ty);
11209 
11210     ArgTypes.push_back(Ty);
11211   }
11212 
11213   if (Id == Builtin::BI__GetExceptionInfo)
11214     return {};
11215 
11216   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11217          "'.' should only occur at end of builtin type list!");
11218 
11219   bool Variadic = (TypeStr[0] == '.');
11220 
11221   FunctionType::ExtInfo EI(getDefaultCallingConvention(
11222       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11223   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11224 
11225 
11226   // We really shouldn't be making a no-proto type here.
11227   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
11228     return getFunctionNoProtoType(ResType, EI);
11229 
11230   FunctionProtoType::ExtProtoInfo EPI;
11231   EPI.ExtInfo = EI;
11232   EPI.Variadic = Variadic;
11233   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
11234     EPI.ExceptionSpec.Type =
11235         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
11236 
11237   return getFunctionType(ResType, ArgTypes, EPI);
11238 }
11239 
11240 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
11241                                              const FunctionDecl *FD) {
11242   if (!FD->isExternallyVisible())
11243     return GVA_Internal;
11244 
11245   // Non-user-provided functions get emitted as weak definitions with every
11246   // use, no matter whether they've been explicitly instantiated etc.
11247   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
11248     if (!MD->isUserProvided())
11249       return GVA_DiscardableODR;
11250 
11251   GVALinkage External;
11252   switch (FD->getTemplateSpecializationKind()) {
11253   case TSK_Undeclared:
11254   case TSK_ExplicitSpecialization:
11255     External = GVA_StrongExternal;
11256     break;
11257 
11258   case TSK_ExplicitInstantiationDefinition:
11259     return GVA_StrongODR;
11260 
11261   // C++11 [temp.explicit]p10:
11262   //   [ Note: The intent is that an inline function that is the subject of
11263   //   an explicit instantiation declaration will still be implicitly
11264   //   instantiated when used so that the body can be considered for
11265   //   inlining, but that no out-of-line copy of the inline function would be
11266   //   generated in the translation unit. -- end note ]
11267   case TSK_ExplicitInstantiationDeclaration:
11268     return GVA_AvailableExternally;
11269 
11270   case TSK_ImplicitInstantiation:
11271     External = GVA_DiscardableODR;
11272     break;
11273   }
11274 
11275   if (!FD->isInlined())
11276     return External;
11277 
11278   if ((!Context.getLangOpts().CPlusPlus &&
11279        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11280        !FD->hasAttr<DLLExportAttr>()) ||
11281       FD->hasAttr<GNUInlineAttr>()) {
11282     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11283 
11284     // GNU or C99 inline semantics. Determine whether this symbol should be
11285     // externally visible.
11286     if (FD->isInlineDefinitionExternallyVisible())
11287       return External;
11288 
11289     // C99 inline semantics, where the symbol is not externally visible.
11290     return GVA_AvailableExternally;
11291   }
11292 
11293   // Functions specified with extern and inline in -fms-compatibility mode
11294   // forcibly get emitted.  While the body of the function cannot be later
11295   // replaced, the function definition cannot be discarded.
11296   if (FD->isMSExternInline())
11297     return GVA_StrongODR;
11298 
11299   return GVA_DiscardableODR;
11300 }
11301 
11302 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
11303                                                 const Decl *D, GVALinkage L) {
11304   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11305   // dllexport/dllimport on inline functions.
11306   if (D->hasAttr<DLLImportAttr>()) {
11307     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11308       return GVA_AvailableExternally;
11309   } else if (D->hasAttr<DLLExportAttr>()) {
11310     if (L == GVA_DiscardableODR)
11311       return GVA_StrongODR;
11312   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11313     // Device-side functions with __global__ attribute must always be
11314     // visible externally so they can be launched from host.
11315     if (D->hasAttr<CUDAGlobalAttr>() &&
11316         (L == GVA_DiscardableODR || L == GVA_Internal))
11317       return GVA_StrongODR;
11318     // Single source offloading languages like CUDA/HIP need to be able to
11319     // access static device variables from host code of the same compilation
11320     // unit. This is done by externalizing the static variable with a shared
11321     // name between the host and device compilation which is the same for the
11322     // same compilation unit whereas different among different compilation
11323     // units.
11324     if (Context.shouldExternalizeStaticVar(D))
11325       return GVA_StrongExternal;
11326   }
11327   return L;
11328 }
11329 
11330 /// Adjust the GVALinkage for a declaration based on what an external AST source
11331 /// knows about whether there can be other definitions of this declaration.
11332 static GVALinkage
11333 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
11334                                           GVALinkage L) {
11335   ExternalASTSource *Source = Ctx.getExternalSource();
11336   if (!Source)
11337     return L;
11338 
11339   switch (Source->hasExternalDefinitions(D)) {
11340   case ExternalASTSource::EK_Never:
11341     // Other translation units rely on us to provide the definition.
11342     if (L == GVA_DiscardableODR)
11343       return GVA_StrongODR;
11344     break;
11345 
11346   case ExternalASTSource::EK_Always:
11347     return GVA_AvailableExternally;
11348 
11349   case ExternalASTSource::EK_ReplyHazy:
11350     break;
11351   }
11352   return L;
11353 }
11354 
11355 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
11356   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
11357            adjustGVALinkageForAttributes(*this, FD,
11358              basicGVALinkageForFunction(*this, FD)));
11359 }
11360 
11361 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
11362                                              const VarDecl *VD) {
11363   if (!VD->isExternallyVisible())
11364     return GVA_Internal;
11365 
11366   if (VD->isStaticLocal()) {
11367     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11368     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11369       LexicalContext = LexicalContext->getLexicalParent();
11370 
11371     // ObjC Blocks can create local variables that don't have a FunctionDecl
11372     // LexicalContext.
11373     if (!LexicalContext)
11374       return GVA_DiscardableODR;
11375 
11376     // Otherwise, let the static local variable inherit its linkage from the
11377     // nearest enclosing function.
11378     auto StaticLocalLinkage =
11379         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11380 
11381     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11382     // be emitted in any object with references to the symbol for the object it
11383     // contains, whether inline or out-of-line."
11384     // Similar behavior is observed with MSVC. An alternative ABI could use
11385     // StrongODR/AvailableExternally to match the function, but none are
11386     // known/supported currently.
11387     if (StaticLocalLinkage == GVA_StrongODR ||
11388         StaticLocalLinkage == GVA_AvailableExternally)
11389       return GVA_DiscardableODR;
11390     return StaticLocalLinkage;
11391   }
11392 
11393   // MSVC treats in-class initialized static data members as definitions.
11394   // By giving them non-strong linkage, out-of-line definitions won't
11395   // cause link errors.
11396   if (Context.isMSStaticDataMemberInlineDefinition(VD))
11397     return GVA_DiscardableODR;
11398 
11399   // Most non-template variables have strong linkage; inline variables are
11400   // linkonce_odr or (occasionally, for compatibility) weak_odr.
11401   GVALinkage StrongLinkage;
11402   switch (Context.getInlineVariableDefinitionKind(VD)) {
11403   case ASTContext::InlineVariableDefinitionKind::None:
11404     StrongLinkage = GVA_StrongExternal;
11405     break;
11406   case ASTContext::InlineVariableDefinitionKind::Weak:
11407   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
11408     StrongLinkage = GVA_DiscardableODR;
11409     break;
11410   case ASTContext::InlineVariableDefinitionKind::Strong:
11411     StrongLinkage = GVA_StrongODR;
11412     break;
11413   }
11414 
11415   switch (VD->getTemplateSpecializationKind()) {
11416   case TSK_Undeclared:
11417     return StrongLinkage;
11418 
11419   case TSK_ExplicitSpecialization:
11420     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11421                    VD->isStaticDataMember()
11422                ? GVA_StrongODR
11423                : StrongLinkage;
11424 
11425   case TSK_ExplicitInstantiationDefinition:
11426     return GVA_StrongODR;
11427 
11428   case TSK_ExplicitInstantiationDeclaration:
11429     return GVA_AvailableExternally;
11430 
11431   case TSK_ImplicitInstantiation:
11432     return GVA_DiscardableODR;
11433   }
11434 
11435   llvm_unreachable("Invalid Linkage!");
11436 }
11437 
11438 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
11439   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
11440            adjustGVALinkageForAttributes(*this, VD,
11441              basicGVALinkageForVariable(*this, VD)));
11442 }
11443 
11444 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
11445   if (const auto *VD = dyn_cast<VarDecl>(D)) {
11446     if (!VD->isFileVarDecl())
11447       return false;
11448     // Global named register variables (GNU extension) are never emitted.
11449     if (VD->getStorageClass() == SC_Register)
11450       return false;
11451     if (VD->getDescribedVarTemplate() ||
11452         isa<VarTemplatePartialSpecializationDecl>(VD))
11453       return false;
11454   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11455     // We never need to emit an uninstantiated function template.
11456     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11457       return false;
11458   } else if (isa<PragmaCommentDecl>(D))
11459     return true;
11460   else if (isa<PragmaDetectMismatchDecl>(D))
11461     return true;
11462   else if (isa<OMPRequiresDecl>(D))
11463     return true;
11464   else if (isa<OMPThreadPrivateDecl>(D))
11465     return !D->getDeclContext()->isDependentContext();
11466   else if (isa<OMPAllocateDecl>(D))
11467     return !D->getDeclContext()->isDependentContext();
11468   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11469     return !D->getDeclContext()->isDependentContext();
11470   else if (isa<ImportDecl>(D))
11471     return true;
11472   else
11473     return false;
11474 
11475   // If this is a member of a class template, we do not need to emit it.
11476   if (D->getDeclContext()->isDependentContext())
11477     return false;
11478 
11479   // Weak references don't produce any output by themselves.
11480   if (D->hasAttr<WeakRefAttr>())
11481     return false;
11482 
11483   // Aliases and used decls are required.
11484   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11485     return true;
11486 
11487   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11488     // Forward declarations aren't required.
11489     if (!FD->doesThisDeclarationHaveABody())
11490       return FD->doesDeclarationForceExternallyVisibleDefinition();
11491 
11492     // Constructors and destructors are required.
11493     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11494       return true;
11495 
11496     // The key function for a class is required.  This rule only comes
11497     // into play when inline functions can be key functions, though.
11498     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11499       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11500         const CXXRecordDecl *RD = MD->getParent();
11501         if (MD->isOutOfLine() && RD->isDynamicClass()) {
11502           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11503           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11504             return true;
11505         }
11506       }
11507     }
11508 
11509     GVALinkage Linkage = GetGVALinkageForFunction(FD);
11510 
11511     // static, static inline, always_inline, and extern inline functions can
11512     // always be deferred.  Normal inline functions can be deferred in C99/C++.
11513     // Implicit template instantiations can also be deferred in C++.
11514     return !isDiscardableGVALinkage(Linkage);
11515   }
11516 
11517   const auto *VD = cast<VarDecl>(D);
11518   assert(VD->isFileVarDecl() && "Expected file scoped var");
11519 
11520   // If the decl is marked as `declare target to`, it should be emitted for the
11521   // host and for the device.
11522   if (LangOpts.OpenMP &&
11523       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11524     return true;
11525 
11526   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11527       !isMSStaticDataMemberInlineDefinition(VD))
11528     return false;
11529 
11530   // Variables that can be needed in other TUs are required.
11531   auto Linkage = GetGVALinkageForVariable(VD);
11532   if (!isDiscardableGVALinkage(Linkage))
11533     return true;
11534 
11535   // We never need to emit a variable that is available in another TU.
11536   if (Linkage == GVA_AvailableExternally)
11537     return false;
11538 
11539   // Variables that have destruction with side-effects are required.
11540   if (VD->needsDestruction(*this))
11541     return true;
11542 
11543   // Variables that have initialization with side-effects are required.
11544   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11545       // We can get a value-dependent initializer during error recovery.
11546       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11547     return true;
11548 
11549   // Likewise, variables with tuple-like bindings are required if their
11550   // bindings have side-effects.
11551   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11552     for (const auto *BD : DD->bindings())
11553       if (const auto *BindingVD = BD->getHoldingVar())
11554         if (DeclMustBeEmitted(BindingVD))
11555           return true;
11556 
11557   return false;
11558 }
11559 
11560 void ASTContext::forEachMultiversionedFunctionVersion(
11561     const FunctionDecl *FD,
11562     llvm::function_ref<void(FunctionDecl *)> Pred) const {
11563   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11564   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11565   FD = FD->getMostRecentDecl();
11566   // FIXME: The order of traversal here matters and depends on the order of
11567   // lookup results, which happens to be (mostly) oldest-to-newest, but we
11568   // shouldn't rely on that.
11569   for (auto *CurDecl :
11570        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
11571     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
11572     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
11573         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
11574       SeenDecls.insert(CurFD);
11575       Pred(CurFD);
11576     }
11577   }
11578 }
11579 
11580 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
11581                                                     bool IsCXXMethod,
11582                                                     bool IsBuiltin) const {
11583   // Pass through to the C++ ABI object
11584   if (IsCXXMethod)
11585     return ABI->getDefaultMethodCallConv(IsVariadic);
11586 
11587   // Builtins ignore user-specified default calling convention and remain the
11588   // Target's default calling convention.
11589   if (!IsBuiltin) {
11590     switch (LangOpts.getDefaultCallingConv()) {
11591     case LangOptions::DCC_None:
11592       break;
11593     case LangOptions::DCC_CDecl:
11594       return CC_C;
11595     case LangOptions::DCC_FastCall:
11596       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11597         return CC_X86FastCall;
11598       break;
11599     case LangOptions::DCC_StdCall:
11600       if (!IsVariadic)
11601         return CC_X86StdCall;
11602       break;
11603     case LangOptions::DCC_VectorCall:
11604       // __vectorcall cannot be applied to variadic functions.
11605       if (!IsVariadic)
11606         return CC_X86VectorCall;
11607       break;
11608     case LangOptions::DCC_RegCall:
11609       // __regcall cannot be applied to variadic functions.
11610       if (!IsVariadic)
11611         return CC_X86RegCall;
11612       break;
11613     }
11614   }
11615   return Target->getDefaultCallingConv();
11616 }
11617 
11618 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11619   // Pass through to the C++ ABI object
11620   return ABI->isNearlyEmpty(RD);
11621 }
11622 
11623 VTableContextBase *ASTContext::getVTableContext() {
11624   if (!VTContext.get()) {
11625     auto ABI = Target->getCXXABI();
11626     if (ABI.isMicrosoft())
11627       VTContext.reset(new MicrosoftVTableContext(*this));
11628     else {
11629       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11630                                  ? ItaniumVTableContext::Relative
11631                                  : ItaniumVTableContext::Pointer;
11632       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
11633     }
11634   }
11635   return VTContext.get();
11636 }
11637 
11638 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
11639   if (!T)
11640     T = Target;
11641   switch (T->getCXXABI().getKind()) {
11642   case TargetCXXABI::AppleARM64:
11643   case TargetCXXABI::Fuchsia:
11644   case TargetCXXABI::GenericAArch64:
11645   case TargetCXXABI::GenericItanium:
11646   case TargetCXXABI::GenericARM:
11647   case TargetCXXABI::GenericMIPS:
11648   case TargetCXXABI::iOS:
11649   case TargetCXXABI::WebAssembly:
11650   case TargetCXXABI::WatchOS:
11651   case TargetCXXABI::XL:
11652     return ItaniumMangleContext::create(*this, getDiagnostics());
11653   case TargetCXXABI::Microsoft:
11654     return MicrosoftMangleContext::create(*this, getDiagnostics());
11655   }
11656   llvm_unreachable("Unsupported ABI");
11657 }
11658 
11659 MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
11660   assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
11661          "Device mangle context does not support Microsoft mangling.");
11662   switch (T.getCXXABI().getKind()) {
11663   case TargetCXXABI::AppleARM64:
11664   case TargetCXXABI::Fuchsia:
11665   case TargetCXXABI::GenericAArch64:
11666   case TargetCXXABI::GenericItanium:
11667   case TargetCXXABI::GenericARM:
11668   case TargetCXXABI::GenericMIPS:
11669   case TargetCXXABI::iOS:
11670   case TargetCXXABI::WebAssembly:
11671   case TargetCXXABI::WatchOS:
11672   case TargetCXXABI::XL:
11673     return ItaniumMangleContext::create(
11674         *this, getDiagnostics(),
11675         [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> {
11676           if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
11677             return RD->getDeviceLambdaManglingNumber();
11678           return llvm::None;
11679         });
11680   case TargetCXXABI::Microsoft:
11681     return MicrosoftMangleContext::create(*this, getDiagnostics());
11682   }
11683   llvm_unreachable("Unsupported ABI");
11684 }
11685 
11686 CXXABI::~CXXABI() = default;
11687 
11688 size_t ASTContext::getSideTableAllocatedMemory() const {
11689   return ASTRecordLayouts.getMemorySize() +
11690          llvm::capacity_in_bytes(ObjCLayouts) +
11691          llvm::capacity_in_bytes(KeyFunctions) +
11692          llvm::capacity_in_bytes(ObjCImpls) +
11693          llvm::capacity_in_bytes(BlockVarCopyInits) +
11694          llvm::capacity_in_bytes(DeclAttrs) +
11695          llvm::capacity_in_bytes(TemplateOrInstantiation) +
11696          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
11697          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
11698          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
11699          llvm::capacity_in_bytes(OverriddenMethods) +
11700          llvm::capacity_in_bytes(Types) +
11701          llvm::capacity_in_bytes(VariableArrayTypes);
11702 }
11703 
11704 /// getIntTypeForBitwidth -
11705 /// sets integer QualTy according to specified details:
11706 /// bitwidth, signed/unsigned.
11707 /// Returns empty type if there is no appropriate target types.
11708 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
11709                                            unsigned Signed) const {
11710   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
11711   CanQualType QualTy = getFromTargetType(Ty);
11712   if (!QualTy && DestWidth == 128)
11713     return Signed ? Int128Ty : UnsignedInt128Ty;
11714   return QualTy;
11715 }
11716 
11717 /// getRealTypeForBitwidth -
11718 /// sets floating point QualTy according to specified bitwidth.
11719 /// Returns empty type if there is no appropriate target types.
11720 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
11721                                             FloatModeKind ExplicitType) const {
11722   FloatModeKind Ty =
11723       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
11724   switch (Ty) {
11725   case FloatModeKind::Float:
11726     return FloatTy;
11727   case FloatModeKind::Double:
11728     return DoubleTy;
11729   case FloatModeKind::LongDouble:
11730     return LongDoubleTy;
11731   case FloatModeKind::Float128:
11732     return Float128Ty;
11733   case FloatModeKind::Ibm128:
11734     return Ibm128Ty;
11735   case FloatModeKind::NoFloat:
11736     return {};
11737   }
11738 
11739   llvm_unreachable("Unhandled TargetInfo::RealType value");
11740 }
11741 
11742 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
11743   if (Number > 1)
11744     MangleNumbers[ND] = Number;
11745 }
11746 
11747 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
11748   auto I = MangleNumbers.find(ND);
11749   return I != MangleNumbers.end() ? I->second : 1;
11750 }
11751 
11752 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
11753   if (Number > 1)
11754     StaticLocalNumbers[VD] = Number;
11755 }
11756 
11757 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
11758   auto I = StaticLocalNumbers.find(VD);
11759   return I != StaticLocalNumbers.end() ? I->second : 1;
11760 }
11761 
11762 MangleNumberingContext &
11763 ASTContext::getManglingNumberContext(const DeclContext *DC) {
11764   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
11765   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
11766   if (!MCtx)
11767     MCtx = createMangleNumberingContext();
11768   return *MCtx;
11769 }
11770 
11771 MangleNumberingContext &
11772 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
11773   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
11774   std::unique_ptr<MangleNumberingContext> &MCtx =
11775       ExtraMangleNumberingContexts[D];
11776   if (!MCtx)
11777     MCtx = createMangleNumberingContext();
11778   return *MCtx;
11779 }
11780 
11781 std::unique_ptr<MangleNumberingContext>
11782 ASTContext::createMangleNumberingContext() const {
11783   return ABI->createMangleNumberingContext();
11784 }
11785 
11786 const CXXConstructorDecl *
11787 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
11788   return ABI->getCopyConstructorForExceptionObject(
11789       cast<CXXRecordDecl>(RD->getFirstDecl()));
11790 }
11791 
11792 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
11793                                                       CXXConstructorDecl *CD) {
11794   return ABI->addCopyConstructorForExceptionObject(
11795       cast<CXXRecordDecl>(RD->getFirstDecl()),
11796       cast<CXXConstructorDecl>(CD->getFirstDecl()));
11797 }
11798 
11799 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
11800                                                  TypedefNameDecl *DD) {
11801   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
11802 }
11803 
11804 TypedefNameDecl *
11805 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
11806   return ABI->getTypedefNameForUnnamedTagDecl(TD);
11807 }
11808 
11809 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
11810                                                 DeclaratorDecl *DD) {
11811   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
11812 }
11813 
11814 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
11815   return ABI->getDeclaratorForUnnamedTagDecl(TD);
11816 }
11817 
11818 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
11819   ParamIndices[D] = index;
11820 }
11821 
11822 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
11823   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
11824   assert(I != ParamIndices.end() &&
11825          "ParmIndices lacks entry set by ParmVarDecl");
11826   return I->second;
11827 }
11828 
11829 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
11830                                                unsigned Length) const {
11831   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
11832   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
11833     EltTy = EltTy.withConst();
11834 
11835   EltTy = adjustStringLiteralBaseType(EltTy);
11836 
11837   // Get an array type for the string, according to C99 6.4.5. This includes
11838   // the null terminator character.
11839   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
11840                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
11841 }
11842 
11843 StringLiteral *
11844 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
11845   StringLiteral *&Result = StringLiteralCache[Key];
11846   if (!Result)
11847     Result = StringLiteral::Create(
11848         *this, Key, StringLiteral::Ascii,
11849         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
11850         SourceLocation());
11851   return Result;
11852 }
11853 
11854 MSGuidDecl *
11855 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
11856   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
11857 
11858   llvm::FoldingSetNodeID ID;
11859   MSGuidDecl::Profile(ID, Parts);
11860 
11861   void *InsertPos;
11862   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
11863     return Existing;
11864 
11865   QualType GUIDType = getMSGuidType().withConst();
11866   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
11867   MSGuidDecls.InsertNode(New, InsertPos);
11868   return New;
11869 }
11870 
11871 TemplateParamObjectDecl *
11872 ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
11873   assert(T->isRecordType() && "template param object of unexpected type");
11874 
11875   // C++ [temp.param]p8:
11876   //   [...] a static storage duration object of type 'const T' [...]
11877   T.addConst();
11878 
11879   llvm::FoldingSetNodeID ID;
11880   TemplateParamObjectDecl::Profile(ID, T, V);
11881 
11882   void *InsertPos;
11883   if (TemplateParamObjectDecl *Existing =
11884           TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
11885     return Existing;
11886 
11887   TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
11888   TemplateParamObjectDecls.InsertNode(New, InsertPos);
11889   return New;
11890 }
11891 
11892 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
11893   const llvm::Triple &T = getTargetInfo().getTriple();
11894   if (!T.isOSDarwin())
11895     return false;
11896 
11897   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
11898       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
11899     return false;
11900 
11901   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
11902   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
11903   uint64_t Size = sizeChars.getQuantity();
11904   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
11905   unsigned Align = alignChars.getQuantity();
11906   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
11907   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
11908 }
11909 
11910 bool
11911 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
11912                                 const ObjCMethodDecl *MethodImpl) {
11913   // No point trying to match an unavailable/deprecated mothod.
11914   if (MethodDecl->hasAttr<UnavailableAttr>()
11915       || MethodDecl->hasAttr<DeprecatedAttr>())
11916     return false;
11917   if (MethodDecl->getObjCDeclQualifier() !=
11918       MethodImpl->getObjCDeclQualifier())
11919     return false;
11920   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
11921     return false;
11922 
11923   if (MethodDecl->param_size() != MethodImpl->param_size())
11924     return false;
11925 
11926   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
11927        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
11928        EF = MethodDecl->param_end();
11929        IM != EM && IF != EF; ++IM, ++IF) {
11930     const ParmVarDecl *DeclVar = (*IF);
11931     const ParmVarDecl *ImplVar = (*IM);
11932     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
11933       return false;
11934     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
11935       return false;
11936   }
11937 
11938   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
11939 }
11940 
11941 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
11942   LangAS AS;
11943   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
11944     AS = LangAS::Default;
11945   else
11946     AS = QT->getPointeeType().getAddressSpace();
11947 
11948   return getTargetInfo().getNullPointerValue(AS);
11949 }
11950 
11951 unsigned ASTContext::getTargetAddressSpace(QualType T) const {
11952   // Return the address space for the type. If the type is a
11953   // function type without an address space qualifier, the
11954   // program address space is used. Otherwise, the target picks
11955   // the best address space based on the type information
11956   return T->isFunctionType() && !T.hasAddressSpace()
11957              ? getTargetInfo().getProgramAddressSpace()
11958              : getTargetAddressSpace(T.getQualifiers());
11959 }
11960 
11961 unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
11962   return getTargetAddressSpace(Q.getAddressSpace());
11963 }
11964 
11965 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
11966   if (isTargetAddressSpace(AS))
11967     return toTargetAddressSpace(AS);
11968   else
11969     return (*AddrSpaceMap)[(unsigned)AS];
11970 }
11971 
11972 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
11973   assert(Ty->isFixedPointType());
11974 
11975   if (Ty->isSaturatedFixedPointType()) return Ty;
11976 
11977   switch (Ty->castAs<BuiltinType>()->getKind()) {
11978     default:
11979       llvm_unreachable("Not a fixed point type!");
11980     case BuiltinType::ShortAccum:
11981       return SatShortAccumTy;
11982     case BuiltinType::Accum:
11983       return SatAccumTy;
11984     case BuiltinType::LongAccum:
11985       return SatLongAccumTy;
11986     case BuiltinType::UShortAccum:
11987       return SatUnsignedShortAccumTy;
11988     case BuiltinType::UAccum:
11989       return SatUnsignedAccumTy;
11990     case BuiltinType::ULongAccum:
11991       return SatUnsignedLongAccumTy;
11992     case BuiltinType::ShortFract:
11993       return SatShortFractTy;
11994     case BuiltinType::Fract:
11995       return SatFractTy;
11996     case BuiltinType::LongFract:
11997       return SatLongFractTy;
11998     case BuiltinType::UShortFract:
11999       return SatUnsignedShortFractTy;
12000     case BuiltinType::UFract:
12001       return SatUnsignedFractTy;
12002     case BuiltinType::ULongFract:
12003       return SatUnsignedLongFractTy;
12004   }
12005 }
12006 
12007 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
12008   if (LangOpts.OpenCL)
12009     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
12010 
12011   if (LangOpts.CUDA)
12012     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
12013 
12014   return getLangASFromTargetAS(AS);
12015 }
12016 
12017 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
12018 // doesn't include ASTContext.h
12019 template
12020 clang::LazyGenerationalUpdatePtr<
12021     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
12022 clang::LazyGenerationalUpdatePtr<
12023     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
12024         const clang::ASTContext &Ctx, Decl *Value);
12025 
12026 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
12027   assert(Ty->isFixedPointType());
12028 
12029   const TargetInfo &Target = getTargetInfo();
12030   switch (Ty->castAs<BuiltinType>()->getKind()) {
12031     default:
12032       llvm_unreachable("Not a fixed point type!");
12033     case BuiltinType::ShortAccum:
12034     case BuiltinType::SatShortAccum:
12035       return Target.getShortAccumScale();
12036     case BuiltinType::Accum:
12037     case BuiltinType::SatAccum:
12038       return Target.getAccumScale();
12039     case BuiltinType::LongAccum:
12040     case BuiltinType::SatLongAccum:
12041       return Target.getLongAccumScale();
12042     case BuiltinType::UShortAccum:
12043     case BuiltinType::SatUShortAccum:
12044       return Target.getUnsignedShortAccumScale();
12045     case BuiltinType::UAccum:
12046     case BuiltinType::SatUAccum:
12047       return Target.getUnsignedAccumScale();
12048     case BuiltinType::ULongAccum:
12049     case BuiltinType::SatULongAccum:
12050       return Target.getUnsignedLongAccumScale();
12051     case BuiltinType::ShortFract:
12052     case BuiltinType::SatShortFract:
12053       return Target.getShortFractScale();
12054     case BuiltinType::Fract:
12055     case BuiltinType::SatFract:
12056       return Target.getFractScale();
12057     case BuiltinType::LongFract:
12058     case BuiltinType::SatLongFract:
12059       return Target.getLongFractScale();
12060     case BuiltinType::UShortFract:
12061     case BuiltinType::SatUShortFract:
12062       return Target.getUnsignedShortFractScale();
12063     case BuiltinType::UFract:
12064     case BuiltinType::SatUFract:
12065       return Target.getUnsignedFractScale();
12066     case BuiltinType::ULongFract:
12067     case BuiltinType::SatULongFract:
12068       return Target.getUnsignedLongFractScale();
12069   }
12070 }
12071 
12072 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
12073   assert(Ty->isFixedPointType());
12074 
12075   const TargetInfo &Target = getTargetInfo();
12076   switch (Ty->castAs<BuiltinType>()->getKind()) {
12077     default:
12078       llvm_unreachable("Not a fixed point type!");
12079     case BuiltinType::ShortAccum:
12080     case BuiltinType::SatShortAccum:
12081       return Target.getShortAccumIBits();
12082     case BuiltinType::Accum:
12083     case BuiltinType::SatAccum:
12084       return Target.getAccumIBits();
12085     case BuiltinType::LongAccum:
12086     case BuiltinType::SatLongAccum:
12087       return Target.getLongAccumIBits();
12088     case BuiltinType::UShortAccum:
12089     case BuiltinType::SatUShortAccum:
12090       return Target.getUnsignedShortAccumIBits();
12091     case BuiltinType::UAccum:
12092     case BuiltinType::SatUAccum:
12093       return Target.getUnsignedAccumIBits();
12094     case BuiltinType::ULongAccum:
12095     case BuiltinType::SatULongAccum:
12096       return Target.getUnsignedLongAccumIBits();
12097     case BuiltinType::ShortFract:
12098     case BuiltinType::SatShortFract:
12099     case BuiltinType::Fract:
12100     case BuiltinType::SatFract:
12101     case BuiltinType::LongFract:
12102     case BuiltinType::SatLongFract:
12103     case BuiltinType::UShortFract:
12104     case BuiltinType::SatUShortFract:
12105     case BuiltinType::UFract:
12106     case BuiltinType::SatUFract:
12107     case BuiltinType::ULongFract:
12108     case BuiltinType::SatULongFract:
12109       return 0;
12110   }
12111 }
12112 
12113 llvm::FixedPointSemantics
12114 ASTContext::getFixedPointSemantics(QualType Ty) const {
12115   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
12116          "Can only get the fixed point semantics for a "
12117          "fixed point or integer type.");
12118   if (Ty->isIntegerType())
12119     return llvm::FixedPointSemantics::GetIntegerSemantics(
12120         getIntWidth(Ty), Ty->isSignedIntegerType());
12121 
12122   bool isSigned = Ty->isSignedFixedPointType();
12123   return llvm::FixedPointSemantics(
12124       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
12125       Ty->isSaturatedFixedPointType(),
12126       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
12127 }
12128 
12129 llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
12130   assert(Ty->isFixedPointType());
12131   return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
12132 }
12133 
12134 llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
12135   assert(Ty->isFixedPointType());
12136   return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
12137 }
12138 
12139 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
12140   assert(Ty->isUnsignedFixedPointType() &&
12141          "Expected unsigned fixed point type");
12142 
12143   switch (Ty->castAs<BuiltinType>()->getKind()) {
12144   case BuiltinType::UShortAccum:
12145     return ShortAccumTy;
12146   case BuiltinType::UAccum:
12147     return AccumTy;
12148   case BuiltinType::ULongAccum:
12149     return LongAccumTy;
12150   case BuiltinType::SatUShortAccum:
12151     return SatShortAccumTy;
12152   case BuiltinType::SatUAccum:
12153     return SatAccumTy;
12154   case BuiltinType::SatULongAccum:
12155     return SatLongAccumTy;
12156   case BuiltinType::UShortFract:
12157     return ShortFractTy;
12158   case BuiltinType::UFract:
12159     return FractTy;
12160   case BuiltinType::ULongFract:
12161     return LongFractTy;
12162   case BuiltinType::SatUShortFract:
12163     return SatShortFractTy;
12164   case BuiltinType::SatUFract:
12165     return SatFractTy;
12166   case BuiltinType::SatULongFract:
12167     return SatLongFractTy;
12168   default:
12169     llvm_unreachable("Unexpected unsigned fixed point type");
12170   }
12171 }
12172 
12173 ParsedTargetAttr
12174 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
12175   assert(TD != nullptr);
12176   ParsedTargetAttr ParsedAttr = TD->parse();
12177 
12178   llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
12179     return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
12180   });
12181   return ParsedAttr;
12182 }
12183 
12184 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12185                                        const FunctionDecl *FD) const {
12186   if (FD)
12187     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
12188   else
12189     Target->initFeatureMap(FeatureMap, getDiagnostics(),
12190                            Target->getTargetOpts().CPU,
12191                            Target->getTargetOpts().Features);
12192 }
12193 
12194 // Fills in the supplied string map with the set of target features for the
12195 // passed in function.
12196 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
12197                                        GlobalDecl GD) const {
12198   StringRef TargetCPU = Target->getTargetOpts().CPU;
12199   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
12200   if (const auto *TD = FD->getAttr<TargetAttr>()) {
12201     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
12202 
12203     // Make a copy of the features as passed on the command line into the
12204     // beginning of the additional features from the function to override.
12205     ParsedAttr.Features.insert(
12206         ParsedAttr.Features.begin(),
12207         Target->getTargetOpts().FeaturesAsWritten.begin(),
12208         Target->getTargetOpts().FeaturesAsWritten.end());
12209 
12210     if (ParsedAttr.Architecture != "" &&
12211         Target->isValidCPUName(ParsedAttr.Architecture))
12212       TargetCPU = ParsedAttr.Architecture;
12213 
12214     // Now populate the feature map, first with the TargetCPU which is either
12215     // the default or a new one from the target attribute string. Then we'll use
12216     // the passed in features (FeaturesAsWritten) along with the new ones from
12217     // the attribute.
12218     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
12219                            ParsedAttr.Features);
12220   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
12221     llvm::SmallVector<StringRef, 32> FeaturesTmp;
12222     Target->getCPUSpecificCPUDispatchFeatures(
12223         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
12224     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
12225     Features.insert(Features.begin(),
12226                     Target->getTargetOpts().FeaturesAsWritten.begin(),
12227                     Target->getTargetOpts().FeaturesAsWritten.end());
12228     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12229   } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
12230     std::vector<std::string> Features;
12231     StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
12232     if (VersionStr.startswith("arch="))
12233       TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
12234     else if (VersionStr != "default")
12235       Features.push_back((StringRef{"+"} + VersionStr).str());
12236 
12237     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
12238   } else {
12239     FeatureMap = Target->getTargetOpts().FeatureMap;
12240   }
12241 }
12242 
12243 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
12244   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
12245   return *OMPTraitInfoVector.back();
12246 }
12247 
12248 const StreamingDiagnostic &clang::
12249 operator<<(const StreamingDiagnostic &DB,
12250            const ASTContext::SectionInfo &Section) {
12251   if (Section.Decl)
12252     return DB << Section.Decl;
12253   return DB << "a prior #pragma section";
12254 }
12255 
12256 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
12257   bool IsStaticVar =
12258       isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
12259   bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
12260                               !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
12261                              (D->hasAttr<CUDAConstantAttr>() &&
12262                               !D->getAttr<CUDAConstantAttr>()->isImplicit());
12263   // CUDA/HIP: static managed variables need to be externalized since it is
12264   // a declaration in IR, therefore cannot have internal linkage.
12265   return IsStaticVar &&
12266          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar);
12267 }
12268 
12269 bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
12270   return mayExternalizeStaticVar(D) &&
12271          (D->hasAttr<HIPManagedAttr>() ||
12272           CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
12273 }
12274 
12275 StringRef ASTContext::getCUIDHash() const {
12276   if (!CUIDHash.empty())
12277     return CUIDHash;
12278   if (LangOpts.CUID.empty())
12279     return StringRef();
12280   CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
12281   return CUIDHash;
12282 }
12283