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