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