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