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