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