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