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