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