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