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