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