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