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