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