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