1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclContextInternals.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/VTableBuilder.h"
34 #include "clang/Basic/Builtins.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/Triple.h"
39 #include "llvm/Support/Capacity.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
46 unsigned ASTContext::NumImplicitDefaultConstructors;
47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyConstructors;
49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50 unsigned ASTContext::NumImplicitMoveConstructors;
51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56 unsigned ASTContext::NumImplicitDestructors;
57 unsigned ASTContext::NumImplicitDestructorsDeclared;
60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
73 CommentsLoaded = true;
78 // User can not attach documentation to implicit declarations.
82 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
121 // TODO: we could look up template parameter documentation in the template
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
128 ArrayRef<RawComment *> RawComments = Comments.getComments();
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142 isa<ObjCPropertyDecl>(D) ||
143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
145 DeclLoc = D->getLocStart();
147 DeclLoc = D->getLocation();
148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
172 // Find the comment that occurs just after this declaration.
173 ArrayRef<RawComment *>::iterator Comment;
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
200 // Decompose the location for the declaration and find the beginning of the
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209 std::pair<FileID, unsigned> CommentBeginDecomp
210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
227 // Check that we actually have a non-member Doxygen comment.
228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
235 // If the comment and the declaration aren't in the same file, then they
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
253 if (Text.find_first_of(";{}#@") != StringRef::npos)
260 /// If we have a 'templated' declaration for a template, adjust 'D' to
261 /// refer to the actual template.
262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
263 const Decl *adjustDeclToTemplate(const Decl *D) {
264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // Is this function declaration part of a function template?
266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
298 // Class is an implicit instantiation of a class template or partial
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
327 // FIXME: Adjust alias templates?
330 } // anonymous namespace
332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl **OriginalDecl) const {
335 D = adjustDeclToTemplate(D);
337 // Check whether we have cached a comment for this declaration already.
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345 *OriginalDecl = Raw.getOriginalDecl();
351 // Search for comments attached to declarations in the redeclaration chain.
352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
354 for (auto I : D->redecls()) {
355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356 RedeclComments.find(I);
357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361 OriginalDeclForRC = Raw.getOriginalDecl();
365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
367 RawCommentAndCacheFlags Raw;
369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
386 *OriginalDecl = OriginalDeclForRC;
388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
392 Raw.setOriginalDecl(OriginalDeclForRC);
394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
403 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
410 // Add redeclared method here.
411 for (const auto *Ext : ID->known_extensions()) {
412 if (ObjCMethodDecl *RedeclaredMethod =
413 Ext->getMethod(ObjCMethod->getSelector(),
414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
420 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
440 comments::FullComment *ASTContext::getCommentForDecl(
442 const Preprocessor *PP) const {
443 if (D->isInvalidDecl())
445 D = adjustDeclToTemplate(D);
447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
451 if (Pos != ParsedComments.end()) {
452 if (Canonical != D) {
453 comments::FullComment *FC = Pos->second;
454 comments::FullComment *CFC = cloneFullComment(FC, D);
460 const Decl *OriginalDecl;
462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
465 SmallVector<const NamedDecl*, 8> Overridden;
466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
479 // Attach any tag type's documentation to its typedef if latter
480 // does not have one of its own.
481 QualType QT = TD->getUnderlyingType();
482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
485 return cloneFullComment(FC, D);
487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
502 // Check non-virtual bases.
503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
506 QualType Ty = I.getType();
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
517 // Check virtual bases.
518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
521 QualType Ty = I.getType();
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
539 if (D != OriginalDecl)
540 return getCommentForDecl(OriginalDecl, PP);
542 comments::FullComment *FC = RC->parse(*this, PP, D);
543 ParsedComments[Canonical] = FC;
548 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
552 ID.AddBoolean(Parm->isParameterPack());
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddBoolean(TTP->isParameterPack());
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddBoolean(NTTP->isParameterPack());
568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
569 if (NTTP->isExpandedParameterPack()) {
571 ID.AddInteger(NTTP->getNumExpansionTypes());
572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
577 ID.AddBoolean(false);
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
587 TemplateTemplateParmDecl *
588 ASTContext::getCanonicalTemplateTemplateParmDecl(
589 TemplateTemplateParmDecl *TTP) const {
590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
593 void *InsertPos = nullptr;
594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597 return Canonical->getParam();
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
601 SmallVector<NamedDecl *, 4> CanonParams;
602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
612 TTP->getIndex(), nullptr, false,
613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
632 NTTP->getPosition(), nullptr,
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 NTTP->getPosition(), nullptr,
644 NTTP->isParameterPack(),
647 CanonParams.push_back(Param);
650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
656 Expr *const CanonRequiresClause = nullptr;
658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
662 TTP->isParameterPack(),
664 TemplateParameterList::Create(*this, SourceLocation(),
668 CanonRequiresClause));
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
672 assert(!Canonical && "Shouldn't be in the map!");
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
681 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
682 if (!LangOpts.CPlusPlus) return nullptr;
684 switch (T.getCXXABI().getKind()) {
685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
686 case TargetCXXABI::iOS:
687 case TargetCXXABI::iOS64:
688 case TargetCXXABI::WatchOS:
689 case TargetCXXABI::GenericAArch64:
690 case TargetCXXABI::GenericMIPS:
691 case TargetCXXABI::GenericItanium:
692 case TargetCXXABI::WebAssembly:
693 return CreateItaniumCXXABI(*this);
694 case TargetCXXABI::Microsoft:
695 return CreateMicrosoftCXXABI(*this);
697 llvm_unreachable("Invalid CXXABI type!");
700 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
708 2, // opencl_constant
714 return &FakeAddrSpaceMap;
716 return &T.getAddressSpaceMap();
720 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
721 const LangOptions &LangOpts) {
722 switch (LangOpts.getAddressSpaceMapMangling()) {
723 case LangOptions::ASMM_Target:
724 return TI.useAddressSpaceMapMangling();
725 case LangOptions::ASMM_On:
727 case LangOptions::ASMM_Off:
730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
733 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
734 IdentifierTable &idents, SelectorTable &sels,
735 Builtin::Context &builtins)
736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
737 DependentTemplateSpecializationTypes(this_()),
738 SubstTemplateTemplateParmPacks(this_()),
739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
754 Listener(nullptr), Comments(SM), CommentsLoaded(false),
755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
756 TUDecl = TranslationUnitDecl::Create(*this);
759 ASTContext::~ASTContext() {
760 ReleaseParentMapEntries();
762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
766 // Call all of the deallocation functions on all of their targets.
767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
789 A->second->~AttrVec();
791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
799 void ASTContext::ReleaseParentMapEntries() {
800 if (!PointerParents) return;
801 for (const auto &Entry : *PointerParents) {
802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
803 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
804 } else if (Entry.second.is<ParentVector *>()) {
805 delete Entry.second.get<ParentVector *>();
808 for (const auto &Entry : *OtherParents) {
809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
810 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
811 } else if (Entry.second.is<ParentVector *>()) {
812 delete Entry.second.get<ParentVector *>();
817 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
818 Deallocations.push_back({Callback, Data});
822 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
823 ExternalSource = std::move(Source);
826 void ASTContext::PrintStats() const {
827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
830 unsigned counts[] = {
831 #define TYPE(Name, Parent) 0,
832 #define ABSTRACT_TYPE(Name, Parent)
833 #include "clang/AST/TypeNodes.def"
837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
839 counts[(unsigned)T->getTypeClass()]++;
843 unsigned TotalBytes = 0;
844 #define TYPE(Name, Parent) \
846 llvm::errs() << " " << counts[Idx] << " " << #Name \
848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
850 #define ABSTRACT_TYPE(Name, Parent)
851 #include "clang/AST/TypeNodes.def"
853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
855 // Implicit special member functions.
856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
857 << NumImplicitDefaultConstructors
858 << " implicit default constructors created\n";
859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
860 << NumImplicitCopyConstructors
861 << " implicit copy constructors created\n";
862 if (getLangOpts().CPlusPlus)
863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
864 << NumImplicitMoveConstructors
865 << " implicit move constructors created\n";
866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
867 << NumImplicitCopyAssignmentOperators
868 << " implicit copy assignment operators created\n";
869 if (getLangOpts().CPlusPlus)
870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
871 << NumImplicitMoveAssignmentOperators
872 << " implicit move assignment operators created\n";
873 llvm::errs() << NumImplicitDestructorsDeclared << "/"
874 << NumImplicitDestructors
875 << " implicit destructors created\n";
877 if (ExternalSource) {
878 llvm::errs() << "\n";
879 ExternalSource->PrintStats();
882 BumpAlloc.PrintStats();
885 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
894 ND->setHidden(false);
897 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
902 auto &Merged = It->second;
903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
910 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
927 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
928 // One special case: if we add a module initializer that imports another
929 // module, and that module's only initializer is an ImportDecl, simplify.
930 if (auto *ID = dyn_cast<ImportDecl>(D)) {
931 auto It = ModuleInitializers.find(ID->getImportedModule());
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
937 // Maybe the ImportDecl only imports another ImportDecl.
938 auto &Imported = *It->second;
939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
940 Imported.resolve(*this);
941 auto *OnlyDecl = Imported.Initializers.front();
942 if (isa<ImportDecl>(OnlyDecl))
947 auto *&Inits = ModuleInitializers[M];
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
953 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
961 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
971 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
975 return ExternCContext;
978 BuiltinTemplateDecl *
979 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
980 const IdentifierInfo *II) const {
981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
982 BuiltinTemplate->setImplicit();
983 TUDecl->addDecl(BuiltinTemplate);
985 return BuiltinTemplate;
988 BuiltinTemplateDecl *
989 ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
996 BuiltinTemplateDecl *
997 ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1004 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
1007 RecordDecl *NewDecl;
1008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
1012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1014 NewDecl->setImplicit();
1015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1020 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1021 StringRef Name) const {
1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1023 TypedefDecl *NewDecl = TypedefDecl::Create(
1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1026 NewDecl->setImplicit();
1030 TypedefDecl *ASTContext::getInt128Decl() const {
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1036 TypedefDecl *ASTContext::getUInt128Decl() const {
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1042 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1044 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1045 Types.push_back(Ty);
1048 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1049 const TargetInfo *AuxTarget) {
1050 assert((!this->Target || this->Target == &Target) &&
1051 "Incorrect target reinitialization");
1052 assert(VoidTy.isNull() && "Context reinitialized?");
1054 this->Target = &Target;
1055 this->AuxTarget = AuxTarget;
1057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1062 InitBuiltinType(VoidTy, BuiltinType::Void);
1065 InitBuiltinType(BoolTy, BuiltinType::Bool);
1067 if (LangOpts.CharIsSigned)
1068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
1072 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1073 InitBuiltinType(ShortTy, BuiltinType::Short);
1074 InitBuiltinType(IntTy, BuiltinType::Int);
1075 InitBuiltinType(LongTy, BuiltinType::Long);
1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1098 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1100 else // -fshort-wchar makes wchar_t be unsigned.
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1102 if (LangOpts.CPlusPlus && LangOpts.WChar)
1103 WideCharTy = WCharTy;
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1109 WIntTy = getFromTargetType(Target.getWIntType());
1111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
1121 // Placeholder type for type-dependent expressions whose type is
1122 // completely unknown. No code should ever check a type against
1123 // DependentTy and users should never see it; however, it is here to
1124 // help diagnose failures to properly check for type-dependent
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1154 Float128ComplexTy = getComplexType(Float128Ty);
1156 // Builtin types for 'id', 'Class', and 'SEL'.
1157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1161 if (LangOpts.OpenCL) {
1162 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
1164 #include "clang/Basic/OpenCLImageTypes.def"
1166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1174 // Builtin type for __objc_yes and __objc_no
1175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
1178 ObjCConstantStringType = QualType();
1180 ObjCSuperType = QualType();
1183 VoidPtrTy = getPointerType(VoidTy);
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
1191 // Builtin type used to help define __builtin_va_list.
1192 VaListTagDecl = nullptr;
1195 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1196 return SourceMgr.getDiagnostics();
1199 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
1209 /// \brief Erase the attributes corresponding to the given declaration.
1210 void ASTContext::eraseDeclAttrs(const Decl *D) {
1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1212 if (Pos != DeclAttrs.end()) {
1213 Pos->second->~AttrVec();
1214 DeclAttrs.erase(Pos);
1219 MemberSpecializationInfo *
1220 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1221 assert(Var->isStaticDataMember() && "Not a static data member");
1222 return getTemplateOrSpecializationInfo(Var)
1223 .dyn_cast<MemberSpecializationInfo *>();
1226 ASTContext::TemplateOrSpecializationInfo
1227 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1229 TemplateOrInstantiation.find(Var);
1230 if (Pos == TemplateOrInstantiation.end())
1231 return TemplateOrSpecializationInfo();
1237 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1238 TemplateSpecializationKind TSK,
1239 SourceLocation PointOfInstantiation) {
1240 assert(Inst->isStaticDataMember() && "Not a static data member");
1241 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1243 Tmpl, TSK, PointOfInstantiation));
1247 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1248 TemplateOrSpecializationInfo TSI) {
1249 assert(!TemplateOrInstantiation[Inst] &&
1250 "Already noted what the variable was instantiated from");
1251 TemplateOrInstantiation[Inst] = TSI;
1254 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1255 const FunctionDecl *FD){
1256 assert(FD && "Specialization is 0");
1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1258 = ClassScopeSpecializationPattern.find(FD);
1259 if (Pos == ClassScopeSpecializationPattern.end())
1265 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1266 FunctionDecl *Pattern) {
1267 assert(FD && "Specialization is 0");
1268 assert(Pattern && "Class scope specialization pattern is 0");
1269 ClassScopeSpecializationPattern[FD] = Pattern;
1273 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1274 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1275 if (Pos == InstantiatedFromUsingDecl.end())
1282 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1283 assert((isa<UsingDecl>(Pattern) ||
1284 isa<UnresolvedUsingValueDecl>(Pattern) ||
1285 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1286 "pattern decl is not a using decl");
1287 assert((isa<UsingDecl>(Inst) ||
1288 isa<UnresolvedUsingValueDecl>(Inst) ||
1289 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1290 "instantiation did not produce a using decl");
1291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1292 InstantiatedFromUsingDecl[Inst] = Pattern;
1296 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1298 = InstantiatedFromUsingShadowDecl.find(Inst);
1299 if (Pos == InstantiatedFromUsingShadowDecl.end())
1306 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1307 UsingShadowDecl *Pattern) {
1308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1312 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1314 = InstantiatedFromUnnamedFieldDecl.find(Field);
1315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1321 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1326 "Already noted what unnamed field was instantiated from");
1328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1331 ASTContext::overridden_cxx_method_iterator
1332 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
1335 if (Pos == OverriddenMethods.end())
1337 return Pos->second.begin();
1340 ASTContext::overridden_cxx_method_iterator
1341 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
1344 if (Pos == OverriddenMethods.end())
1346 return Pos->second.end();
1350 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
1353 if (Pos == OverriddenMethods.end())
1355 return Pos->second.size();
1358 ASTContext::overridden_method_range
1359 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1360 return overridden_method_range(overridden_methods_begin(Method),
1361 overridden_methods_end(Method));
1364 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1365 const CXXMethodDecl *Overridden) {
1366 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1367 OverriddenMethods[Method].push_back(Overridden);
1370 void ASTContext::getOverriddenMethods(
1372 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1375 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1376 Overridden.append(overridden_methods_begin(CXXMethod),
1377 overridden_methods_end(CXXMethod));
1381 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1385 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1386 Method->getOverriddenMethods(OverDecls);
1387 Overridden.append(OverDecls.begin(), OverDecls.end());
1390 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1391 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1392 assert(!Import->isFromASTFile() && "Non-local import declaration");
1393 if (!FirstLocalImport) {
1394 FirstLocalImport = Import;
1395 LastLocalImport = Import;
1399 LastLocalImport->NextLocalImport = Import;
1400 LastLocalImport = Import;
1403 //===----------------------------------------------------------------------===//
1404 // Type Sizing and Analysis
1405 //===----------------------------------------------------------------------===//
1407 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1408 /// scalar floating point type.
1409 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1410 const BuiltinType *BT = T->getAs<BuiltinType>();
1411 assert(BT && "Not a floating point type!");
1412 switch (BT->getKind()) {
1413 default: llvm_unreachable("Not a floating point type!");
1414 case BuiltinType::Half: return Target->getHalfFormat();
1415 case BuiltinType::Float: return Target->getFloatFormat();
1416 case BuiltinType::Double: return Target->getDoubleFormat();
1417 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1418 case BuiltinType::Float128: return Target->getFloat128Format();
1422 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1423 unsigned Align = Target->getCharWidth();
1425 bool UseAlignAttrOnly = false;
1426 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1427 Align = AlignFromAttr;
1429 // __attribute__((aligned)) can increase or decrease alignment
1430 // *except* on a struct or struct member, where it only increases
1431 // alignment unless 'packed' is also specified.
1433 // It is an error for alignas to decrease alignment, so we can
1434 // ignore that possibility; Sema should diagnose it.
1435 if (isa<FieldDecl>(D)) {
1436 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1437 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1439 UseAlignAttrOnly = true;
1442 else if (isa<FieldDecl>(D))
1444 D->hasAttr<PackedAttr>() ||
1445 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1447 // If we're using the align attribute only, just ignore everything
1448 // else about the declaration and its type.
1449 if (UseAlignAttrOnly) {
1452 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1453 QualType T = VD->getType();
1454 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1456 T = RT->getPointeeType();
1458 T = getPointerType(RT->getPointeeType());
1460 QualType BaseT = getBaseElementType(T);
1461 if (T->isFunctionType())
1462 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1463 else if (!BaseT->isIncompleteType()) {
1464 // Adjust alignments of declarations with array type by the
1465 // large-array alignment on the target.
1466 if (const ArrayType *arrayType = getAsArrayType(T)) {
1467 unsigned MinWidth = Target->getLargeArrayMinWidth();
1468 if (!ForAlignof && MinWidth) {
1469 if (isa<VariableArrayType>(arrayType))
1470 Align = std::max(Align, Target->getLargeArrayAlign());
1471 else if (isa<ConstantArrayType>(arrayType) &&
1472 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1473 Align = std::max(Align, Target->getLargeArrayAlign());
1476 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1478 if (VD->hasGlobalStorage() && !ForAlignof)
1479 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1483 // Fields can be subject to extra alignment constraints, like if
1484 // the field is packed, the struct is packed, or the struct has a
1485 // a max-field-alignment constraint (#pragma pack). So calculate
1486 // the actual alignment of the field within the struct, and then
1487 // (as we're expected to) constrain that by the alignment of the type.
1488 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1489 const RecordDecl *Parent = Field->getParent();
1490 // We can only produce a sensible answer if the record is valid.
1491 if (!Parent->isInvalidDecl()) {
1492 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1494 // Start with the record's overall alignment.
1495 unsigned FieldAlign = toBits(Layout.getAlignment());
1497 // Use the GCD of that and the offset within the record.
1498 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1500 // Alignment is always a power of 2, so the GCD will be a power of 2,
1501 // which means we get to do this crazy thing instead of Euclid's.
1502 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1503 if (LowBitOfOffset < FieldAlign)
1504 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1507 Align = std::min(Align, FieldAlign);
1512 return toCharUnitsFromBits(Align);
1515 // getTypeInfoDataSizeInChars - Return the size of a type, in
1516 // chars. If the type is a record, its data size is returned. This is
1517 // the size of the memcpy that's performed when assigning this type
1518 // using a trivial copy/move assignment operator.
1519 std::pair<CharUnits, CharUnits>
1520 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1521 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1523 // In C++, objects can sometimes be allocated into the tail padding
1524 // of a base-class subobject. We decide whether that's possible
1525 // during class layout, so here we can just trust the layout results.
1526 if (getLangOpts().CPlusPlus) {
1527 if (const RecordType *RT = T->getAs<RecordType>()) {
1528 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1529 sizeAndAlign.first = layout.getDataSize();
1533 return sizeAndAlign;
1536 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1537 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1538 std::pair<CharUnits, CharUnits>
1539 static getConstantArrayInfoInChars(const ASTContext &Context,
1540 const ConstantArrayType *CAT) {
1541 std::pair<CharUnits, CharUnits> EltInfo =
1542 Context.getTypeInfoInChars(CAT->getElementType());
1543 uint64_t Size = CAT->getSize().getZExtValue();
1544 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1545 (uint64_t)(-1)/Size) &&
1546 "Overflow in array type char size evaluation");
1547 uint64_t Width = EltInfo.first.getQuantity() * Size;
1548 unsigned Align = EltInfo.second.getQuantity();
1549 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1550 Context.getTargetInfo().getPointerWidth(0) == 64)
1551 Width = llvm::alignTo(Width, Align);
1552 return std::make_pair(CharUnits::fromQuantity(Width),
1553 CharUnits::fromQuantity(Align));
1556 std::pair<CharUnits, CharUnits>
1557 ASTContext::getTypeInfoInChars(const Type *T) const {
1558 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1559 return getConstantArrayInfoInChars(*this, CAT);
1560 TypeInfo Info = getTypeInfo(T);
1561 return std::make_pair(toCharUnitsFromBits(Info.Width),
1562 toCharUnitsFromBits(Info.Align));
1565 std::pair<CharUnits, CharUnits>
1566 ASTContext::getTypeInfoInChars(QualType T) const {
1567 return getTypeInfoInChars(T.getTypePtr());
1570 bool ASTContext::isAlignmentRequired(const Type *T) const {
1571 return getTypeInfo(T).AlignIsRequired;
1574 bool ASTContext::isAlignmentRequired(QualType T) const {
1575 return isAlignmentRequired(T.getTypePtr());
1578 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1579 // An alignment on a typedef overrides anything else.
1580 if (auto *TT = T->getAs<TypedefType>())
1581 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1584 // If we have an (array of) complete type, we're done.
1585 T = getBaseElementType(T);
1586 if (!T->isIncompleteType())
1587 return getTypeAlign(T);
1589 // If we had an array type, its element type might be a typedef
1590 // type with an alignment attribute.
1591 if (auto *TT = T->getAs<TypedefType>())
1592 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1595 // Otherwise, see if the declaration of the type had an attribute.
1596 if (auto *TT = T->getAs<TagType>())
1597 return TT->getDecl()->getMaxAlignment();
1602 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1603 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1604 if (I != MemoizedTypeInfo.end())
1607 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1608 TypeInfo TI = getTypeInfoImpl(T);
1609 MemoizedTypeInfo[T] = TI;
1613 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1614 /// method does not work on incomplete types.
1616 /// FIXME: Pointers into different addr spaces could have different sizes and
1617 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1618 /// should take a QualType, &c.
1619 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1622 bool AlignIsRequired = false;
1623 switch (T->getTypeClass()) {
1624 #define TYPE(Class, Base)
1625 #define ABSTRACT_TYPE(Class, Base)
1626 #define NON_CANONICAL_TYPE(Class, Base)
1627 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1628 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1630 assert(!T->isDependentType() && "should not see dependent types here"); \
1631 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1632 #include "clang/AST/TypeNodes.def"
1633 llvm_unreachable("Should not see dependent types");
1635 case Type::FunctionNoProto:
1636 case Type::FunctionProto:
1637 // GCC extension: alignof(function) = 32 bits
1642 case Type::IncompleteArray:
1643 case Type::VariableArray:
1645 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1648 case Type::ConstantArray: {
1649 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1651 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1652 uint64_t Size = CAT->getSize().getZExtValue();
1653 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1654 "Overflow in array type bit size evaluation");
1655 Width = EltInfo.Width * Size;
1656 Align = EltInfo.Align;
1657 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1658 getTargetInfo().getPointerWidth(0) == 64)
1659 Width = llvm::alignTo(Width, Align);
1662 case Type::ExtVector:
1663 case Type::Vector: {
1664 const VectorType *VT = cast<VectorType>(T);
1665 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1666 Width = EltInfo.Width * VT->getNumElements();
1668 // If the alignment is not a power of 2, round up to the next power of 2.
1669 // This happens for non-power-of-2 length vectors.
1670 if (Align & (Align-1)) {
1671 Align = llvm::NextPowerOf2(Align);
1672 Width = llvm::alignTo(Width, Align);
1674 // Adjust the alignment based on the target max.
1675 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1676 if (TargetVectorAlign && TargetVectorAlign < Align)
1677 Align = TargetVectorAlign;
1682 switch (cast<BuiltinType>(T)->getKind()) {
1683 default: llvm_unreachable("Unknown builtin type!");
1684 case BuiltinType::Void:
1685 // GCC extension: alignof(void) = 8 bits.
1690 case BuiltinType::Bool:
1691 Width = Target->getBoolWidth();
1692 Align = Target->getBoolAlign();
1694 case BuiltinType::Char_S:
1695 case BuiltinType::Char_U:
1696 case BuiltinType::UChar:
1697 case BuiltinType::SChar:
1698 Width = Target->getCharWidth();
1699 Align = Target->getCharAlign();
1701 case BuiltinType::WChar_S:
1702 case BuiltinType::WChar_U:
1703 Width = Target->getWCharWidth();
1704 Align = Target->getWCharAlign();
1706 case BuiltinType::Char16:
1707 Width = Target->getChar16Width();
1708 Align = Target->getChar16Align();
1710 case BuiltinType::Char32:
1711 Width = Target->getChar32Width();
1712 Align = Target->getChar32Align();
1714 case BuiltinType::UShort:
1715 case BuiltinType::Short:
1716 Width = Target->getShortWidth();
1717 Align = Target->getShortAlign();
1719 case BuiltinType::UInt:
1720 case BuiltinType::Int:
1721 Width = Target->getIntWidth();
1722 Align = Target->getIntAlign();
1724 case BuiltinType::ULong:
1725 case BuiltinType::Long:
1726 Width = Target->getLongWidth();
1727 Align = Target->getLongAlign();
1729 case BuiltinType::ULongLong:
1730 case BuiltinType::LongLong:
1731 Width = Target->getLongLongWidth();
1732 Align = Target->getLongLongAlign();
1734 case BuiltinType::Int128:
1735 case BuiltinType::UInt128:
1737 Align = 128; // int128_t is 128-bit aligned on all targets.
1739 case BuiltinType::Half:
1740 Width = Target->getHalfWidth();
1741 Align = Target->getHalfAlign();
1743 case BuiltinType::Float:
1744 Width = Target->getFloatWidth();
1745 Align = Target->getFloatAlign();
1747 case BuiltinType::Double:
1748 Width = Target->getDoubleWidth();
1749 Align = Target->getDoubleAlign();
1751 case BuiltinType::LongDouble:
1752 Width = Target->getLongDoubleWidth();
1753 Align = Target->getLongDoubleAlign();
1755 case BuiltinType::Float128:
1756 Width = Target->getFloat128Width();
1757 Align = Target->getFloat128Align();
1759 case BuiltinType::NullPtr:
1760 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1761 Align = Target->getPointerAlign(0); // == sizeof(void*)
1763 case BuiltinType::ObjCId:
1764 case BuiltinType::ObjCClass:
1765 case BuiltinType::ObjCSel:
1766 Width = Target->getPointerWidth(0);
1767 Align = Target->getPointerAlign(0);
1769 case BuiltinType::OCLSampler: {
1770 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1771 Width = Target->getPointerWidth(AS);
1772 Align = Target->getPointerAlign(AS);
1775 case BuiltinType::OCLEvent:
1776 case BuiltinType::OCLClkEvent:
1777 case BuiltinType::OCLQueue:
1778 case BuiltinType::OCLNDRange:
1779 case BuiltinType::OCLReserveID:
1780 // Currently these types are pointers to opaque types.
1781 Width = Target->getPointerWidth(0);
1782 Align = Target->getPointerAlign(0);
1784 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1785 case BuiltinType::Id:
1786 #include "clang/Basic/OpenCLImageTypes.def"
1788 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1789 Width = Target->getPointerWidth(AS);
1790 Align = Target->getPointerAlign(AS);
1794 case Type::ObjCObjectPointer:
1795 Width = Target->getPointerWidth(0);
1796 Align = Target->getPointerAlign(0);
1798 case Type::BlockPointer: {
1799 unsigned AS = getTargetAddressSpace(
1800 cast<BlockPointerType>(T)->getPointeeType());
1801 Width = Target->getPointerWidth(AS);
1802 Align = Target->getPointerAlign(AS);
1805 case Type::LValueReference:
1806 case Type::RValueReference: {
1807 // alignof and sizeof should never enter this code path here, so we go
1808 // the pointer route.
1809 unsigned AS = getTargetAddressSpace(
1810 cast<ReferenceType>(T)->getPointeeType());
1811 Width = Target->getPointerWidth(AS);
1812 Align = Target->getPointerAlign(AS);
1815 case Type::Pointer: {
1816 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1817 Width = Target->getPointerWidth(AS);
1818 Align = Target->getPointerAlign(AS);
1821 case Type::MemberPointer: {
1822 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1823 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1826 case Type::Complex: {
1827 // Complex types have the same alignment as their elements, but twice the
1829 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1830 Width = EltInfo.Width * 2;
1831 Align = EltInfo.Align;
1834 case Type::ObjCObject:
1835 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1836 case Type::Adjusted:
1838 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1839 case Type::ObjCInterface: {
1840 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1841 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1842 Width = toBits(Layout.getSize());
1843 Align = toBits(Layout.getAlignment());
1848 const TagType *TT = cast<TagType>(T);
1850 if (TT->getDecl()->isInvalidDecl()) {
1856 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1857 const EnumDecl *ED = ET->getDecl();
1859 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1860 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1861 Info.Align = AttrAlign;
1862 Info.AlignIsRequired = true;
1867 const RecordType *RT = cast<RecordType>(TT);
1868 const RecordDecl *RD = RT->getDecl();
1869 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1870 Width = toBits(Layout.getSize());
1871 Align = toBits(Layout.getAlignment());
1872 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1876 case Type::SubstTemplateTypeParm:
1877 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1878 getReplacementType().getTypePtr());
1881 const AutoType *A = cast<AutoType>(T);
1882 assert(!A->getDeducedType().isNull() &&
1883 "cannot request the size of an undeduced or dependent auto type");
1884 return getTypeInfo(A->getDeducedType().getTypePtr());
1888 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1890 case Type::ObjCTypeParam:
1891 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1893 case Type::Typedef: {
1894 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1895 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1896 // If the typedef has an aligned attribute on it, it overrides any computed
1897 // alignment we have. This violates the GCC documentation (which says that
1898 // attribute(aligned) can only round up) but matches its implementation.
1899 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1901 AlignIsRequired = true;
1904 AlignIsRequired = Info.AlignIsRequired;
1910 case Type::Elaborated:
1911 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1913 case Type::Attributed:
1915 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1917 case Type::Atomic: {
1918 // Start with the base type information.
1919 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1923 // If the size of the type doesn't exceed the platform's max
1924 // atomic promotion width, make the size and alignment more
1925 // favorable to atomic operations:
1926 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1927 // Round the size up to a power of 2.
1928 if (!llvm::isPowerOf2_64(Width))
1929 Width = llvm::NextPowerOf2(Width);
1931 // Set the alignment equal to the size.
1932 Align = static_cast<unsigned>(Width);
1938 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1945 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1946 return TypeInfo(Width, Align, AlignIsRequired);
1949 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1950 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1951 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1952 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1953 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1954 getTargetInfo().getABI() == "elfv1-qpx" &&
1955 T->isSpecificBuiltinType(BuiltinType::Double))
1960 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1961 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1962 return CharUnits::fromQuantity(BitSize / getCharWidth());
1965 /// toBits - Convert a size in characters to a size in characters.
1966 int64_t ASTContext::toBits(CharUnits CharSize) const {
1967 return CharSize.getQuantity() * getCharWidth();
1970 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1971 /// This method does not work on incomplete types.
1972 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1973 return getTypeInfoInChars(T).first;
1975 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1976 return getTypeInfoInChars(T).first;
1979 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1980 /// characters. This method does not work on incomplete types.
1981 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1982 return toCharUnitsFromBits(getTypeAlign(T));
1984 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1985 return toCharUnitsFromBits(getTypeAlign(T));
1988 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1989 /// type for the current target in bits. This can be different than the ABI
1990 /// alignment in cases where it is beneficial for performance to overalign
1992 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1993 TypeInfo TI = getTypeInfo(T);
1994 unsigned ABIAlign = TI.Align;
1996 T = T->getBaseElementTypeUnsafe();
1998 // The preferred alignment of member pointers is that of a pointer.
1999 if (T->isMemberPointerType())
2000 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2002 if (!Target->allowsLargerPreferedTypeAlignment())
2005 // Double and long long should be naturally aligned if possible.
2006 if (const ComplexType *CT = T->getAs<ComplexType>())
2007 T = CT->getElementType().getTypePtr();
2008 if (const EnumType *ET = T->getAs<EnumType>())
2009 T = ET->getDecl()->getIntegerType().getTypePtr();
2010 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2011 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2012 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2013 // Don't increase the alignment if an alignment attribute was specified on a
2014 // typedef declaration.
2015 if (!TI.AlignIsRequired)
2016 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2021 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2022 /// for __attribute__((aligned)) on this target, to be used if no alignment
2023 /// value is specified.
2024 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2025 return getTargetInfo().getDefaultAlignForAttributeAligned();
2028 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2029 /// to a global variable of the specified type.
2030 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2031 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2034 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2035 /// should be given to a global variable of the specified type.
2036 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2037 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2040 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2041 CharUnits Offset = CharUnits::Zero();
2042 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2043 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2044 Offset += Layout->getBaseClassOffset(Base);
2045 Layout = &getASTRecordLayout(Base);
2050 /// DeepCollectObjCIvars -
2051 /// This routine first collects all declared, but not synthesized, ivars in
2052 /// super class and then collects all ivars, including those synthesized for
2053 /// current class. This routine is used for implementation of current class
2054 /// when all ivars, declared and synthesized are known.
2056 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2058 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2059 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2060 DeepCollectObjCIvars(SuperClass, false, Ivars);
2062 for (const auto *I : OI->ivars())
2065 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2066 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2067 Iv= Iv->getNextIvar())
2068 Ivars.push_back(Iv);
2072 /// CollectInheritedProtocols - Collect all protocols in current class and
2073 /// those inherited by it.
2074 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2075 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2076 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2077 // We can use protocol_iterator here instead of
2078 // all_referenced_protocol_iterator since we are walking all categories.
2079 for (auto *Proto : OI->all_referenced_protocols()) {
2080 CollectInheritedProtocols(Proto, Protocols);
2083 // Categories of this Interface.
2084 for (const auto *Cat : OI->visible_categories())
2085 CollectInheritedProtocols(Cat, Protocols);
2087 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2089 CollectInheritedProtocols(SD, Protocols);
2090 SD = SD->getSuperClass();
2092 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2093 for (auto *Proto : OC->protocols()) {
2094 CollectInheritedProtocols(Proto, Protocols);
2096 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2097 // Insert the protocol.
2098 if (!Protocols.insert(
2099 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2102 for (auto *Proto : OP->protocols())
2103 CollectInheritedProtocols(Proto, Protocols);
2107 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2109 // Count ivars declared in class extension.
2110 for (const auto *Ext : OI->known_extensions())
2111 count += Ext->ivar_size();
2113 // Count ivar defined in this class's implementation. This
2114 // includes synthesized ivars.
2115 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2116 count += ImplDecl->ivar_size();
2121 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2125 // nullptr_t is always treated as null.
2126 if (E->getType()->isNullPtrType()) return true;
2128 if (E->getType()->isAnyPointerType() &&
2129 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2130 Expr::NPC_ValueDependentIsNull))
2133 // Unfortunately, __null has type 'int'.
2134 if (isa<GNUNullExpr>(E)) return true;
2139 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2140 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2141 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2142 I = ObjCImpls.find(D);
2143 if (I != ObjCImpls.end())
2144 return cast<ObjCImplementationDecl>(I->second);
2147 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2148 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2149 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2150 I = ObjCImpls.find(D);
2151 if (I != ObjCImpls.end())
2152 return cast<ObjCCategoryImplDecl>(I->second);
2156 /// \brief Set the implementation of ObjCInterfaceDecl.
2157 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2158 ObjCImplementationDecl *ImplD) {
2159 assert(IFaceD && ImplD && "Passed null params");
2160 ObjCImpls[IFaceD] = ImplD;
2162 /// \brief Set the implementation of ObjCCategoryDecl.
2163 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2164 ObjCCategoryImplDecl *ImplD) {
2165 assert(CatD && ImplD && "Passed null params");
2166 ObjCImpls[CatD] = ImplD;
2169 const ObjCMethodDecl *
2170 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2171 return ObjCMethodRedecls.lookup(MD);
2174 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2175 const ObjCMethodDecl *Redecl) {
2176 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2177 ObjCMethodRedecls[MD] = Redecl;
2180 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2181 const NamedDecl *ND) const {
2182 if (const ObjCInterfaceDecl *ID =
2183 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2185 if (const ObjCCategoryDecl *CD =
2186 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2187 return CD->getClassInterface();
2188 if (const ObjCImplDecl *IMD =
2189 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2190 return IMD->getClassInterface();
2195 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2197 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2198 assert(VD && "Passed null params");
2199 assert(VD->hasAttr<BlocksAttr>() &&
2200 "getBlockVarCopyInits - not __block var");
2201 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2202 I = BlockVarCopyInits.find(VD);
2203 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2206 /// \brief Set the copy inialization expression of a block var decl.
2207 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2208 assert(VD && Init && "Passed null params");
2209 assert(VD->hasAttr<BlocksAttr>() &&
2210 "setBlockVarCopyInits - not __block var");
2211 BlockVarCopyInits[VD] = Init;
2214 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2215 unsigned DataSize) const {
2217 DataSize = TypeLoc::getFullDataSizeForType(T);
2219 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2220 "incorrect data size provided to CreateTypeSourceInfo!");
2222 TypeSourceInfo *TInfo =
2223 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2224 new (TInfo) TypeSourceInfo(T);
2228 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2229 SourceLocation L) const {
2230 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2231 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2235 const ASTRecordLayout &
2236 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2237 return getObjCLayout(D, nullptr);
2240 const ASTRecordLayout &
2241 ASTContext::getASTObjCImplementationLayout(
2242 const ObjCImplementationDecl *D) const {
2243 return getObjCLayout(D->getClassInterface(), D);
2246 //===----------------------------------------------------------------------===//
2247 // Type creation/memoization methods
2248 //===----------------------------------------------------------------------===//
2251 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2252 unsigned fastQuals = quals.getFastQualifiers();
2253 quals.removeFastQualifiers();
2255 // Check if we've already instantiated this type.
2256 llvm::FoldingSetNodeID ID;
2257 ExtQuals::Profile(ID, baseType, quals);
2258 void *insertPos = nullptr;
2259 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2260 assert(eq->getQualifiers() == quals);
2261 return QualType(eq, fastQuals);
2264 // If the base type is not canonical, make the appropriate canonical type.
2266 if (!baseType->isCanonicalUnqualified()) {
2267 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2268 canonSplit.Quals.addConsistentQualifiers(quals);
2269 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2271 // Re-find the insert position.
2272 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2275 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2276 ExtQualNodes.InsertNode(eq, insertPos);
2277 return QualType(eq, fastQuals);
2281 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2282 QualType CanT = getCanonicalType(T);
2283 if (CanT.getAddressSpace() == AddressSpace)
2286 // If we are composing extended qualifiers together, merge together
2287 // into one ExtQuals node.
2288 QualifierCollector Quals;
2289 const Type *TypeNode = Quals.strip(T);
2291 // If this type already has an address space specified, it cannot get
2293 assert(!Quals.hasAddressSpace() &&
2294 "Type cannot be in multiple addr spaces!");
2295 Quals.addAddressSpace(AddressSpace);
2297 return getExtQualType(TypeNode, Quals);
2300 QualType ASTContext::getObjCGCQualType(QualType T,
2301 Qualifiers::GC GCAttr) const {
2302 QualType CanT = getCanonicalType(T);
2303 if (CanT.getObjCGCAttr() == GCAttr)
2306 if (const PointerType *ptr = T->getAs<PointerType>()) {
2307 QualType Pointee = ptr->getPointeeType();
2308 if (Pointee->isAnyPointerType()) {
2309 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2310 return getPointerType(ResultType);
2314 // If we are composing extended qualifiers together, merge together
2315 // into one ExtQuals node.
2316 QualifierCollector Quals;
2317 const Type *TypeNode = Quals.strip(T);
2319 // If this type already has an ObjCGC specified, it cannot get
2321 assert(!Quals.hasObjCGCAttr() &&
2322 "Type cannot have multiple ObjCGCs!");
2323 Quals.addObjCGCAttr(GCAttr);
2325 return getExtQualType(TypeNode, Quals);
2328 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2329 FunctionType::ExtInfo Info) {
2330 if (T->getExtInfo() == Info)
2334 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2335 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2337 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2338 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2340 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2343 return cast<FunctionType>(Result.getTypePtr());
2346 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2347 QualType ResultType) {
2348 FD = FD->getMostRecentDecl();
2350 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2351 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2352 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2353 if (FunctionDecl *Next = FD->getPreviousDecl())
2358 if (ASTMutationListener *L = getASTMutationListener())
2359 L->DeducedReturnType(FD, ResultType);
2362 /// Get a function type and produce the equivalent function type with the
2363 /// specified exception specification. Type sugar that can be present on a
2364 /// declaration of a function with an exception specification is permitted
2365 /// and preserved. Other type sugar (for instance, typedefs) is not.
2366 static QualType getFunctionTypeWithExceptionSpec(
2367 ASTContext &Context, QualType Orig,
2368 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2369 // Might have some parens.
2370 if (auto *PT = dyn_cast<ParenType>(Orig))
2371 return Context.getParenType(
2372 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2374 // Might have a calling-convention attribute.
2375 if (auto *AT = dyn_cast<AttributedType>(Orig))
2376 return Context.getAttributedType(
2378 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2379 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2382 // Anything else must be a function type. Rebuild it with the new exception
2384 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2385 return Context.getFunctionType(
2386 Proto->getReturnType(), Proto->getParamTypes(),
2387 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2390 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2392 return hasSameType(T, U) ||
2393 (getLangOpts().CPlusPlus1z &&
2394 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2395 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2398 void ASTContext::adjustExceptionSpec(
2399 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2403 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2404 FD->setType(Updated);
2409 // Update the type in the type source information too.
2410 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2411 // If the type and the type-as-written differ, we may need to update
2412 // the type-as-written too.
2413 if (TSInfo->getType() != FD->getType())
2414 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2416 // FIXME: When we get proper type location information for exceptions,
2417 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2418 // up the TypeSourceInfo;
2419 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2420 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2421 "TypeLoc size mismatch from updating exception specification");
2422 TSInfo->overrideType(Updated);
2426 /// getComplexType - Return the uniqued reference to the type for a complex
2427 /// number with the specified element type.
2428 QualType ASTContext::getComplexType(QualType T) const {
2429 // Unique pointers, to guarantee there is only one pointer of a particular
2431 llvm::FoldingSetNodeID ID;
2432 ComplexType::Profile(ID, T);
2434 void *InsertPos = nullptr;
2435 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2436 return QualType(CT, 0);
2438 // If the pointee type isn't canonical, this won't be a canonical type either,
2439 // so fill in the canonical type field.
2441 if (!T.isCanonical()) {
2442 Canonical = getComplexType(getCanonicalType(T));
2444 // Get the new insert position for the node we care about.
2445 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2446 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2448 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2449 Types.push_back(New);
2450 ComplexTypes.InsertNode(New, InsertPos);
2451 return QualType(New, 0);
2454 /// getPointerType - Return the uniqued reference to the type for a pointer to
2455 /// the specified type.
2456 QualType ASTContext::getPointerType(QualType T) const {
2457 // Unique pointers, to guarantee there is only one pointer of a particular
2459 llvm::FoldingSetNodeID ID;
2460 PointerType::Profile(ID, T);
2462 void *InsertPos = nullptr;
2463 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2464 return QualType(PT, 0);
2466 // If the pointee type isn't canonical, this won't be a canonical type either,
2467 // so fill in the canonical type field.
2469 if (!T.isCanonical()) {
2470 Canonical = getPointerType(getCanonicalType(T));
2472 // Get the new insert position for the node we care about.
2473 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2474 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2476 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2477 Types.push_back(New);
2478 PointerTypes.InsertNode(New, InsertPos);
2479 return QualType(New, 0);
2482 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2483 llvm::FoldingSetNodeID ID;
2484 AdjustedType::Profile(ID, Orig, New);
2485 void *InsertPos = nullptr;
2486 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 return QualType(AT, 0);
2490 QualType Canonical = getCanonicalType(New);
2492 // Get the new insert position for the node we care about.
2493 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2494 assert(!AT && "Shouldn't be in the map!");
2496 AT = new (*this, TypeAlignment)
2497 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2498 Types.push_back(AT);
2499 AdjustedTypes.InsertNode(AT, InsertPos);
2500 return QualType(AT, 0);
2503 QualType ASTContext::getDecayedType(QualType T) const {
2504 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2509 // A declaration of a parameter as "array of type" shall be
2510 // adjusted to "qualified pointer to type", where the type
2511 // qualifiers (if any) are those specified within the [ and ] of
2512 // the array type derivation.
2513 if (T->isArrayType())
2514 Decayed = getArrayDecayedType(T);
2517 // A declaration of a parameter as "function returning type"
2518 // shall be adjusted to "pointer to function returning type", as
2520 if (T->isFunctionType())
2521 Decayed = getPointerType(T);
2523 llvm::FoldingSetNodeID ID;
2524 AdjustedType::Profile(ID, T, Decayed);
2525 void *InsertPos = nullptr;
2526 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2528 return QualType(AT, 0);
2530 QualType Canonical = getCanonicalType(Decayed);
2532 // Get the new insert position for the node we care about.
2533 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2534 assert(!AT && "Shouldn't be in the map!");
2536 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2537 Types.push_back(AT);
2538 AdjustedTypes.InsertNode(AT, InsertPos);
2539 return QualType(AT, 0);
2542 /// getBlockPointerType - Return the uniqued reference to the type for
2543 /// a pointer to the specified block.
2544 QualType ASTContext::getBlockPointerType(QualType T) const {
2545 assert(T->isFunctionType() && "block of function types only");
2546 // Unique pointers, to guarantee there is only one block of a particular
2548 llvm::FoldingSetNodeID ID;
2549 BlockPointerType::Profile(ID, T);
2551 void *InsertPos = nullptr;
2552 if (BlockPointerType *PT =
2553 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2554 return QualType(PT, 0);
2556 // If the block pointee type isn't canonical, this won't be a canonical
2557 // type either so fill in the canonical type field.
2559 if (!T.isCanonical()) {
2560 Canonical = getBlockPointerType(getCanonicalType(T));
2562 // Get the new insert position for the node we care about.
2563 BlockPointerType *NewIP =
2564 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2567 BlockPointerType *New
2568 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2569 Types.push_back(New);
2570 BlockPointerTypes.InsertNode(New, InsertPos);
2571 return QualType(New, 0);
2574 /// getLValueReferenceType - Return the uniqued reference to the type for an
2575 /// lvalue reference to the specified type.
2577 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2578 assert(getCanonicalType(T) != OverloadTy &&
2579 "Unresolved overloaded function type");
2581 // Unique pointers, to guarantee there is only one pointer of a particular
2583 llvm::FoldingSetNodeID ID;
2584 ReferenceType::Profile(ID, T, SpelledAsLValue);
2586 void *InsertPos = nullptr;
2587 if (LValueReferenceType *RT =
2588 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2589 return QualType(RT, 0);
2591 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2593 // If the referencee type isn't canonical, this won't be a canonical type
2594 // either, so fill in the canonical type field.
2596 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2597 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2598 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2600 // Get the new insert position for the node we care about.
2601 LValueReferenceType *NewIP =
2602 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2603 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2606 LValueReferenceType *New
2607 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2609 Types.push_back(New);
2610 LValueReferenceTypes.InsertNode(New, InsertPos);
2612 return QualType(New, 0);
2615 /// getRValueReferenceType - Return the uniqued reference to the type for an
2616 /// rvalue reference to the specified type.
2617 QualType ASTContext::getRValueReferenceType(QualType T) const {
2618 // Unique pointers, to guarantee there is only one pointer of a particular
2620 llvm::FoldingSetNodeID ID;
2621 ReferenceType::Profile(ID, T, false);
2623 void *InsertPos = nullptr;
2624 if (RValueReferenceType *RT =
2625 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2626 return QualType(RT, 0);
2628 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2630 // If the referencee type isn't canonical, this won't be a canonical type
2631 // either, so fill in the canonical type field.
2633 if (InnerRef || !T.isCanonical()) {
2634 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2635 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2637 // Get the new insert position for the node we care about.
2638 RValueReferenceType *NewIP =
2639 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2640 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2643 RValueReferenceType *New
2644 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2645 Types.push_back(New);
2646 RValueReferenceTypes.InsertNode(New, InsertPos);
2647 return QualType(New, 0);
2650 /// getMemberPointerType - Return the uniqued reference to the type for a
2651 /// member pointer to the specified type, in the specified class.
2652 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2653 // Unique pointers, to guarantee there is only one pointer of a particular
2655 llvm::FoldingSetNodeID ID;
2656 MemberPointerType::Profile(ID, T, Cls);
2658 void *InsertPos = nullptr;
2659 if (MemberPointerType *PT =
2660 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2661 return QualType(PT, 0);
2663 // If the pointee or class type isn't canonical, this won't be a canonical
2664 // type either, so fill in the canonical type field.
2666 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2667 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2669 // Get the new insert position for the node we care about.
2670 MemberPointerType *NewIP =
2671 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2672 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2674 MemberPointerType *New
2675 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2676 Types.push_back(New);
2677 MemberPointerTypes.InsertNode(New, InsertPos);
2678 return QualType(New, 0);
2681 /// getConstantArrayType - Return the unique reference to the type for an
2682 /// array of the specified element type.
2683 QualType ASTContext::getConstantArrayType(QualType EltTy,
2684 const llvm::APInt &ArySizeIn,
2685 ArrayType::ArraySizeModifier ASM,
2686 unsigned IndexTypeQuals) const {
2687 assert((EltTy->isDependentType() ||
2688 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2689 "Constant array of VLAs is illegal!");
2691 // Convert the array size into a canonical width matching the pointer size for
2693 llvm::APInt ArySize(ArySizeIn);
2695 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2697 llvm::FoldingSetNodeID ID;
2698 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2700 void *InsertPos = nullptr;
2701 if (ConstantArrayType *ATP =
2702 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2703 return QualType(ATP, 0);
2705 // If the element type isn't canonical or has qualifiers, this won't
2706 // be a canonical type either, so fill in the canonical type field.
2708 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2709 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2710 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2711 ASM, IndexTypeQuals);
2712 Canon = getQualifiedType(Canon, canonSplit.Quals);
2714 // Get the new insert position for the node we care about.
2715 ConstantArrayType *NewIP =
2716 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2717 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2720 ConstantArrayType *New = new(*this,TypeAlignment)
2721 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2722 ConstantArrayTypes.InsertNode(New, InsertPos);
2723 Types.push_back(New);
2724 return QualType(New, 0);
2727 /// getVariableArrayDecayedType - Turns the given type, which may be
2728 /// variably-modified, into the corresponding type with all the known
2729 /// sizes replaced with [*].
2730 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2731 // Vastly most common case.
2732 if (!type->isVariablyModifiedType()) return type;
2736 SplitQualType split = type.getSplitDesugaredType();
2737 const Type *ty = split.Ty;
2738 switch (ty->getTypeClass()) {
2739 #define TYPE(Class, Base)
2740 #define ABSTRACT_TYPE(Class, Base)
2741 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2742 #include "clang/AST/TypeNodes.def"
2743 llvm_unreachable("didn't desugar past all non-canonical types?");
2745 // These types should never be variably-modified.
2749 case Type::ExtVector:
2750 case Type::DependentSizedExtVector:
2751 case Type::ObjCObject:
2752 case Type::ObjCInterface:
2753 case Type::ObjCObjectPointer:
2756 case Type::UnresolvedUsing:
2757 case Type::TypeOfExpr:
2759 case Type::Decltype:
2760 case Type::UnaryTransform:
2761 case Type::DependentName:
2762 case Type::InjectedClassName:
2763 case Type::TemplateSpecialization:
2764 case Type::DependentTemplateSpecialization:
2765 case Type::TemplateTypeParm:
2766 case Type::SubstTemplateTypeParmPack:
2768 case Type::PackExpansion:
2769 llvm_unreachable("type should never be variably-modified");
2771 // These types can be variably-modified but should never need to
2773 case Type::FunctionNoProto:
2774 case Type::FunctionProto:
2775 case Type::BlockPointer:
2776 case Type::MemberPointer:
2780 // These types can be variably-modified. All these modifications
2781 // preserve structure except as noted by comments.
2782 // TODO: if we ever care about optimizing VLAs, there are no-op
2783 // optimizations available here.
2785 result = getPointerType(getVariableArrayDecayedType(
2786 cast<PointerType>(ty)->getPointeeType()));
2789 case Type::LValueReference: {
2790 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2791 result = getLValueReferenceType(
2792 getVariableArrayDecayedType(lv->getPointeeType()),
2793 lv->isSpelledAsLValue());
2797 case Type::RValueReference: {
2798 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2799 result = getRValueReferenceType(
2800 getVariableArrayDecayedType(lv->getPointeeType()));
2804 case Type::Atomic: {
2805 const AtomicType *at = cast<AtomicType>(ty);
2806 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2810 case Type::ConstantArray: {
2811 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2812 result = getConstantArrayType(
2813 getVariableArrayDecayedType(cat->getElementType()),
2815 cat->getSizeModifier(),
2816 cat->getIndexTypeCVRQualifiers());
2820 case Type::DependentSizedArray: {
2821 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2822 result = getDependentSizedArrayType(
2823 getVariableArrayDecayedType(dat->getElementType()),
2825 dat->getSizeModifier(),
2826 dat->getIndexTypeCVRQualifiers(),
2827 dat->getBracketsRange());
2831 // Turn incomplete types into [*] types.
2832 case Type::IncompleteArray: {
2833 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2834 result = getVariableArrayType(
2835 getVariableArrayDecayedType(iat->getElementType()),
2838 iat->getIndexTypeCVRQualifiers(),
2843 // Turn VLA types into [*] types.
2844 case Type::VariableArray: {
2845 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2846 result = getVariableArrayType(
2847 getVariableArrayDecayedType(vat->getElementType()),
2850 vat->getIndexTypeCVRQualifiers(),
2851 vat->getBracketsRange());
2856 // Apply the top-level qualifiers from the original.
2857 return getQualifiedType(result, split.Quals);
2860 /// getVariableArrayType - Returns a non-unique reference to the type for a
2861 /// variable array of the specified element type.
2862 QualType ASTContext::getVariableArrayType(QualType EltTy,
2864 ArrayType::ArraySizeModifier ASM,
2865 unsigned IndexTypeQuals,
2866 SourceRange Brackets) const {
2867 // Since we don't unique expressions, it isn't possible to unique VLA's
2868 // that have an expression provided for their size.
2871 // Be sure to pull qualifiers off the element type.
2872 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2873 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2874 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2875 IndexTypeQuals, Brackets);
2876 Canon = getQualifiedType(Canon, canonSplit.Quals);
2879 VariableArrayType *New = new(*this, TypeAlignment)
2880 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2882 VariableArrayTypes.push_back(New);
2883 Types.push_back(New);
2884 return QualType(New, 0);
2887 /// getDependentSizedArrayType - Returns a non-unique reference to
2888 /// the type for a dependently-sized array of the specified element
2890 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2892 ArrayType::ArraySizeModifier ASM,
2893 unsigned elementTypeQuals,
2894 SourceRange brackets) const {
2895 assert((!numElements || numElements->isTypeDependent() ||
2896 numElements->isValueDependent()) &&
2897 "Size must be type- or value-dependent!");
2899 // Dependently-sized array types that do not have a specified number
2900 // of elements will have their sizes deduced from a dependent
2901 // initializer. We do no canonicalization here at all, which is okay
2902 // because they can't be used in most locations.
2904 DependentSizedArrayType *newType
2905 = new (*this, TypeAlignment)
2906 DependentSizedArrayType(*this, elementType, QualType(),
2907 numElements, ASM, elementTypeQuals,
2909 Types.push_back(newType);
2910 return QualType(newType, 0);
2913 // Otherwise, we actually build a new type every time, but we
2914 // also build a canonical type.
2916 SplitQualType canonElementType = getCanonicalType(elementType).split();
2918 void *insertPos = nullptr;
2919 llvm::FoldingSetNodeID ID;
2920 DependentSizedArrayType::Profile(ID, *this,
2921 QualType(canonElementType.Ty, 0),
2922 ASM, elementTypeQuals, numElements);
2924 // Look for an existing type with these properties.
2925 DependentSizedArrayType *canonTy =
2926 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2928 // If we don't have one, build one.
2930 canonTy = new (*this, TypeAlignment)
2931 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2932 QualType(), numElements, ASM, elementTypeQuals,
2934 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2935 Types.push_back(canonTy);
2938 // Apply qualifiers from the element type to the array.
2939 QualType canon = getQualifiedType(QualType(canonTy,0),
2940 canonElementType.Quals);
2942 // If we didn't need extra canonicalization for the element type or the size
2943 // expression, then just use that as our result.
2944 if (QualType(canonElementType.Ty, 0) == elementType &&
2945 canonTy->getSizeExpr() == numElements)
2948 // Otherwise, we need to build a type which follows the spelling
2949 // of the element type.
2950 DependentSizedArrayType *sugaredType
2951 = new (*this, TypeAlignment)
2952 DependentSizedArrayType(*this, elementType, canon, numElements,
2953 ASM, elementTypeQuals, brackets);
2954 Types.push_back(sugaredType);
2955 return QualType(sugaredType, 0);
2958 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2959 ArrayType::ArraySizeModifier ASM,
2960 unsigned elementTypeQuals) const {
2961 llvm::FoldingSetNodeID ID;
2962 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2964 void *insertPos = nullptr;
2965 if (IncompleteArrayType *iat =
2966 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2967 return QualType(iat, 0);
2969 // If the element type isn't canonical, this won't be a canonical type
2970 // either, so fill in the canonical type field. We also have to pull
2971 // qualifiers off the element type.
2974 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2975 SplitQualType canonSplit = getCanonicalType(elementType).split();
2976 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2977 ASM, elementTypeQuals);
2978 canon = getQualifiedType(canon, canonSplit.Quals);
2980 // Get the new insert position for the node we care about.
2981 IncompleteArrayType *existing =
2982 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2983 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2986 IncompleteArrayType *newType = new (*this, TypeAlignment)
2987 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2989 IncompleteArrayTypes.InsertNode(newType, insertPos);
2990 Types.push_back(newType);
2991 return QualType(newType, 0);
2994 /// getVectorType - Return the unique reference to a vector type of
2995 /// the specified element type and size. VectorType must be a built-in type.
2996 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2997 VectorType::VectorKind VecKind) const {
2998 assert(vecType->isBuiltinType());
3000 // Check if we've already instantiated a vector of this type.
3001 llvm::FoldingSetNodeID ID;
3002 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3004 void *InsertPos = nullptr;
3005 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3006 return QualType(VTP, 0);
3008 // If the element type isn't canonical, this won't be a canonical type either,
3009 // so fill in the canonical type field.
3011 if (!vecType.isCanonical()) {
3012 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3014 // Get the new insert position for the node we care about.
3015 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3016 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3018 VectorType *New = new (*this, TypeAlignment)
3019 VectorType(vecType, NumElts, Canonical, VecKind);
3020 VectorTypes.InsertNode(New, InsertPos);
3021 Types.push_back(New);
3022 return QualType(New, 0);
3025 /// getExtVectorType - Return the unique reference to an extended vector type of
3026 /// the specified element type and size. VectorType must be a built-in type.
3028 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3029 assert(vecType->isBuiltinType() || vecType->isDependentType());
3031 // Check if we've already instantiated a vector of this type.
3032 llvm::FoldingSetNodeID ID;
3033 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3034 VectorType::GenericVector);
3035 void *InsertPos = nullptr;
3036 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3037 return QualType(VTP, 0);
3039 // If the element type isn't canonical, this won't be a canonical type either,
3040 // so fill in the canonical type field.
3042 if (!vecType.isCanonical()) {
3043 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3045 // Get the new insert position for the node we care about.
3046 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3047 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3049 ExtVectorType *New = new (*this, TypeAlignment)
3050 ExtVectorType(vecType, NumElts, Canonical);
3051 VectorTypes.InsertNode(New, InsertPos);
3052 Types.push_back(New);
3053 return QualType(New, 0);
3057 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3059 SourceLocation AttrLoc) const {
3060 llvm::FoldingSetNodeID ID;
3061 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3064 void *InsertPos = nullptr;
3065 DependentSizedExtVectorType *Canon
3066 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 DependentSizedExtVectorType *New;
3069 // We already have a canonical version of this array type; use it as
3070 // the canonical type for a newly-built type.
3071 New = new (*this, TypeAlignment)
3072 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3075 QualType CanonVecTy = getCanonicalType(vecType);
3076 if (CanonVecTy == vecType) {
3077 New = new (*this, TypeAlignment)
3078 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3081 DependentSizedExtVectorType *CanonCheck
3082 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3083 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3085 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3087 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3089 New = new (*this, TypeAlignment)
3090 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3094 Types.push_back(New);
3095 return QualType(New, 0);
3098 /// \brief Determine whether \p T is canonical as the result type of a function.
3099 static bool isCanonicalResultType(QualType T) {
3100 return T.isCanonical() &&
3101 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3102 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3105 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3108 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3109 const FunctionType::ExtInfo &Info) const {
3110 // Unique functions, to guarantee there is only one function of a particular
3112 llvm::FoldingSetNodeID ID;
3113 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3115 void *InsertPos = nullptr;
3116 if (FunctionNoProtoType *FT =
3117 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3118 return QualType(FT, 0);
3121 if (!isCanonicalResultType(ResultTy)) {
3123 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3125 // Get the new insert position for the node we care about.
3126 FunctionNoProtoType *NewIP =
3127 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3128 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3131 FunctionNoProtoType *New = new (*this, TypeAlignment)
3132 FunctionNoProtoType(ResultTy, Canonical, Info);
3133 Types.push_back(New);
3134 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3135 return QualType(New, 0);
3139 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3140 CanQualType CanResultType = getCanonicalType(ResultType);
3142 // Canonical result types do not have ARC lifetime qualifiers.
3143 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3144 Qualifiers Qs = CanResultType.getQualifiers();
3145 Qs.removeObjCLifetime();
3146 return CanQualType::CreateUnsafe(
3147 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3150 return CanResultType;
3153 static bool isCanonicalExceptionSpecification(
3154 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3155 if (ESI.Type == EST_None)
3157 if (!NoexceptInType)
3160 // C++17 onwards: exception specification is part of the type, as a simple
3161 // boolean "can this function type throw".
3162 if (ESI.Type == EST_BasicNoexcept)
3165 // A dynamic exception specification is canonical if it only contains pack
3166 // expansions (so we can't tell whether it's non-throwing) and all its
3167 // contained types are canonical.
3168 if (ESI.Type == EST_Dynamic) {
3169 bool AnyPackExpansions = false;
3170 for (QualType ET : ESI.Exceptions) {
3171 if (!ET.isCanonical())
3173 if (ET->getAs<PackExpansionType>())
3174 AnyPackExpansions = true;
3176 return AnyPackExpansions;
3179 // A noexcept(expr) specification is (possibly) canonical if expr is
3181 if (ESI.Type == EST_ComputedNoexcept)
3182 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3187 QualType ASTContext::getFunctionTypeInternal(
3188 QualType ResultTy, ArrayRef<QualType> ArgArray,
3189 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3190 size_t NumArgs = ArgArray.size();
3192 // Unique functions, to guarantee there is only one function of a particular
3194 llvm::FoldingSetNodeID ID;
3195 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3199 bool Unique = false;
3201 void *InsertPos = nullptr;
3202 if (FunctionProtoType *FPT =
3203 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3204 QualType Existing = QualType(FPT, 0);
3206 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3207 // it so long as our exception specification doesn't contain a dependent
3208 // noexcept expression, or we're just looking for a canonical type.
3209 // Otherwise, we're going to need to create a type
3210 // sugar node to hold the concrete expression.
3211 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
3212 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3215 // We need a new type sugar node for this one, to hold the new noexcept
3216 // expression. We do no canonicalization here, but that's OK since we don't
3217 // expect to see the same noexcept expression much more than once.
3218 Canonical = getCanonicalType(Existing);
3222 bool NoexceptInType = getLangOpts().CPlusPlus1z;
3223 bool IsCanonicalExceptionSpec =
3224 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3226 // Determine whether the type being created is already canonical or not.
3227 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3228 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3229 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3230 if (!ArgArray[i].isCanonicalAsParam())
3231 isCanonical = false;
3233 if (OnlyWantCanonical)
3234 assert(isCanonical &&
3235 "given non-canonical parameters constructing canonical type");
3237 // If this type isn't canonical, get the canonical version of it if we don't
3238 // already have it. The exception spec is only partially part of the
3239 // canonical type, and only in C++17 onwards.
3240 if (!isCanonical && Canonical.isNull()) {
3241 SmallVector<QualType, 16> CanonicalArgs;
3242 CanonicalArgs.reserve(NumArgs);
3243 for (unsigned i = 0; i != NumArgs; ++i)
3244 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3246 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3247 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3248 CanonicalEPI.HasTrailingReturn = false;
3250 if (IsCanonicalExceptionSpec) {
3251 // Exception spec is already OK.
3252 } else if (NoexceptInType) {
3253 switch (EPI.ExceptionSpec.Type) {
3254 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3255 // We don't know yet. It shouldn't matter what we pick here; no-one
3256 // should ever look at this.
3258 case EST_None: case EST_MSAny:
3259 CanonicalEPI.ExceptionSpec.Type = EST_None;
3262 // A dynamic exception specification is almost always "not noexcept",
3263 // with the exception that a pack expansion might expand to no types.
3265 bool AnyPacks = false;
3266 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3267 if (ET->getAs<PackExpansionType>())
3269 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3272 CanonicalEPI.ExceptionSpec.Type = EST_None;
3274 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3275 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3280 case EST_DynamicNone: case EST_BasicNoexcept:
3281 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3284 case EST_ComputedNoexcept:
3285 llvm::APSInt Value(1);
3286 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3287 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3288 /*IsEvaluated*/false)) {
3289 // This noexcept specification is invalid.
3290 // FIXME: Should this be able to happen?
3291 CanonicalEPI.ExceptionSpec.Type = EST_None;
3295 CanonicalEPI.ExceptionSpec.Type =
3296 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3300 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3303 // Adjust the canonical function result type.
3304 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3306 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3308 // Get the new insert position for the node we care about.
3309 FunctionProtoType *NewIP =
3310 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3311 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3314 // FunctionProtoType objects are allocated with extra bytes after
3315 // them for three variable size arrays at the end:
3316 // - parameter types
3317 // - exception types
3318 // - extended parameter information
3319 // Instead of the exception types, there could be a noexcept
3320 // expression, or information used to resolve the exception
3322 size_t Size = sizeof(FunctionProtoType) +
3323 NumArgs * sizeof(QualType);
3325 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3326 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3327 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3328 Size += sizeof(Expr*);
3329 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3330 Size += 2 * sizeof(FunctionDecl*);
3331 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3332 Size += sizeof(FunctionDecl*);
3335 // Put the ExtParameterInfos last. If all were equal, it would make
3336 // more sense to put these before the exception specification, because
3337 // it's much easier to skip past them compared to the elaborate switch
3338 // required to skip the exception specification. However, all is not
3339 // equal; ExtParameterInfos are used to model very uncommon features,
3340 // and it's better not to burden the more common paths.
3341 if (EPI.ExtParameterInfos) {
3342 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3345 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3346 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3347 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3348 Types.push_back(FTP);
3350 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3351 return QualType(FTP, 0);
3354 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3355 llvm::FoldingSetNodeID ID;
3356 PipeType::Profile(ID, T, ReadOnly);
3358 void *InsertPos = 0;
3359 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3360 return QualType(PT, 0);
3362 // If the pipe element type isn't canonical, this won't be a canonical type
3363 // either, so fill in the canonical type field.
3365 if (!T.isCanonical()) {
3366 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3368 // Get the new insert position for the node we care about.
3369 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3370 assert(!NewIP && "Shouldn't be in the map!");
3373 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3374 Types.push_back(New);
3375 PipeTypes.InsertNode(New, InsertPos);
3376 return QualType(New, 0);
3379 QualType ASTContext::getReadPipeType(QualType T) const {
3380 return getPipeType(T, true);
3383 QualType ASTContext::getWritePipeType(QualType T) const {
3384 return getPipeType(T, false);
3388 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3389 if (!isa<CXXRecordDecl>(D)) return false;
3390 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3391 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3393 if (RD->getDescribedClassTemplate() &&
3394 !isa<ClassTemplateSpecializationDecl>(RD))
3400 /// getInjectedClassNameType - Return the unique reference to the
3401 /// injected class name type for the specified templated declaration.
3402 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3403 QualType TST) const {
3404 assert(NeedsInjectedClassNameType(Decl));
3405 if (Decl->TypeForDecl) {
3406 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3407 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3408 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3409 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3410 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3413 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3414 Decl->TypeForDecl = newType;
3415 Types.push_back(newType);
3417 return QualType(Decl->TypeForDecl, 0);
3420 /// getTypeDeclType - Return the unique reference to the type for the
3421 /// specified type declaration.
3422 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3423 assert(Decl && "Passed null for Decl param");
3424 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3426 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3427 return getTypedefType(Typedef);
3429 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3430 "Template type parameter types are always available.");
3432 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3433 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3434 assert(!NeedsInjectedClassNameType(Record));
3435 return getRecordType(Record);
3436 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3437 assert(Enum->isFirstDecl() && "enum has previous declaration");
3438 return getEnumType(Enum);
3439 } else if (const UnresolvedUsingTypenameDecl *Using =
3440 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3441 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3442 Decl->TypeForDecl = newType;
3443 Types.push_back(newType);
3445 llvm_unreachable("TypeDecl without a type?");
3447 return QualType(Decl->TypeForDecl, 0);
3450 /// getTypedefType - Return the unique reference to the type for the
3451 /// specified typedef name decl.
3453 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3454 QualType Canonical) const {
3455 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3457 if (Canonical.isNull())
3458 Canonical = getCanonicalType(Decl->getUnderlyingType());
3459 TypedefType *newType = new(*this, TypeAlignment)
3460 TypedefType(Type::Typedef, Decl, Canonical);
3461 Decl->TypeForDecl = newType;
3462 Types.push_back(newType);
3463 return QualType(newType, 0);
3466 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3467 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3469 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3470 if (PrevDecl->TypeForDecl)
3471 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3473 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3474 Decl->TypeForDecl = newType;
3475 Types.push_back(newType);
3476 return QualType(newType, 0);
3479 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3480 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3482 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3483 if (PrevDecl->TypeForDecl)
3484 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3486 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3487 Decl->TypeForDecl = newType;
3488 Types.push_back(newType);
3489 return QualType(newType, 0);
3492 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3493 QualType modifiedType,
3494 QualType equivalentType) {
3495 llvm::FoldingSetNodeID id;
3496 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3498 void *insertPos = nullptr;
3499 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3500 if (type) return QualType(type, 0);
3502 QualType canon = getCanonicalType(equivalentType);
3503 type = new (*this, TypeAlignment)
3504 AttributedType(canon, attrKind, modifiedType, equivalentType);
3506 Types.push_back(type);
3507 AttributedTypes.InsertNode(type, insertPos);
3509 return QualType(type, 0);
3512 /// \brief Retrieve a substitution-result type.
3514 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3515 QualType Replacement) const {
3516 assert(Replacement.isCanonical()
3517 && "replacement types must always be canonical");
3519 llvm::FoldingSetNodeID ID;
3520 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3521 void *InsertPos = nullptr;
3522 SubstTemplateTypeParmType *SubstParm
3523 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3526 SubstParm = new (*this, TypeAlignment)
3527 SubstTemplateTypeParmType(Parm, Replacement);
3528 Types.push_back(SubstParm);
3529 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3532 return QualType(SubstParm, 0);
3535 /// \brief Retrieve a
3536 QualType ASTContext::getSubstTemplateTypeParmPackType(
3537 const TemplateTypeParmType *Parm,
3538 const TemplateArgument &ArgPack) {
3540 for (const auto &P : ArgPack.pack_elements()) {
3541 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3542 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3546 llvm::FoldingSetNodeID ID;
3547 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3548 void *InsertPos = nullptr;
3549 if (SubstTemplateTypeParmPackType *SubstParm
3550 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3551 return QualType(SubstParm, 0);
3554 if (!Parm->isCanonicalUnqualified()) {
3555 Canon = getCanonicalType(QualType(Parm, 0));
3556 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3558 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3561 SubstTemplateTypeParmPackType *SubstParm
3562 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3564 Types.push_back(SubstParm);
3565 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3566 return QualType(SubstParm, 0);
3569 /// \brief Retrieve the template type parameter type for a template
3570 /// parameter or parameter pack with the given depth, index, and (optionally)
3572 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3574 TemplateTypeParmDecl *TTPDecl) const {
3575 llvm::FoldingSetNodeID ID;
3576 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3577 void *InsertPos = nullptr;
3578 TemplateTypeParmType *TypeParm
3579 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3582 return QualType(TypeParm, 0);
3585 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3586 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3588 TemplateTypeParmType *TypeCheck
3589 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3590 assert(!TypeCheck && "Template type parameter canonical type broken");
3593 TypeParm = new (*this, TypeAlignment)
3594 TemplateTypeParmType(Depth, Index, ParameterPack);
3596 Types.push_back(TypeParm);
3597 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3599 return QualType(TypeParm, 0);
3603 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3604 SourceLocation NameLoc,
3605 const TemplateArgumentListInfo &Args,
3606 QualType Underlying) const {
3607 assert(!Name.getAsDependentTemplateName() &&
3608 "No dependent template names here!");
3609 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3611 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3612 TemplateSpecializationTypeLoc TL =
3613 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3614 TL.setTemplateKeywordLoc(SourceLocation());
3615 TL.setTemplateNameLoc(NameLoc);
3616 TL.setLAngleLoc(Args.getLAngleLoc());
3617 TL.setRAngleLoc(Args.getRAngleLoc());
3618 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3619 TL.setArgLocInfo(i, Args[i].getLocInfo());
3624 ASTContext::getTemplateSpecializationType(TemplateName Template,
3625 const TemplateArgumentListInfo &Args,
3626 QualType Underlying) const {
3627 assert(!Template.getAsDependentTemplateName() &&
3628 "No dependent template names here!");
3630 SmallVector<TemplateArgument, 4> ArgVec;
3631 ArgVec.reserve(Args.size());
3632 for (const TemplateArgumentLoc &Arg : Args.arguments())
3633 ArgVec.push_back(Arg.getArgument());
3635 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3639 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3640 for (const TemplateArgument &Arg : Args)
3641 if (Arg.isPackExpansion())
3649 ASTContext::getTemplateSpecializationType(TemplateName Template,
3650 ArrayRef<TemplateArgument> Args,
3651 QualType Underlying) const {
3652 assert(!Template.getAsDependentTemplateName() &&
3653 "No dependent template names here!");
3654 // Look through qualified template names.
3655 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3656 Template = TemplateName(QTN->getTemplateDecl());
3659 Template.getAsTemplateDecl() &&
3660 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3662 if (!Underlying.isNull())
3663 CanonType = getCanonicalType(Underlying);
3665 // We can get here with an alias template when the specialization contains
3666 // a pack expansion that does not match up with a parameter pack.
3667 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3668 "Caller must compute aliased type");
3669 IsTypeAlias = false;
3670 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3673 // Allocate the (non-canonical) template specialization type, but don't
3674 // try to unique it: these types typically have location information that
3675 // we don't unique and don't want to lose.
3676 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3677 sizeof(TemplateArgument) * Args.size() +
3678 (IsTypeAlias? sizeof(QualType) : 0),
3680 TemplateSpecializationType *Spec
3681 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3682 IsTypeAlias ? Underlying : QualType());
3684 Types.push_back(Spec);
3685 return QualType(Spec, 0);
3688 QualType ASTContext::getCanonicalTemplateSpecializationType(
3689 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3690 assert(!Template.getAsDependentTemplateName() &&
3691 "No dependent template names here!");
3693 // Look through qualified template names.
3694 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3695 Template = TemplateName(QTN->getTemplateDecl());
3697 // Build the canonical template specialization type.
3698 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3699 SmallVector<TemplateArgument, 4> CanonArgs;
3700 unsigned NumArgs = Args.size();
3701 CanonArgs.reserve(NumArgs);
3702 for (const TemplateArgument &Arg : Args)
3703 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3705 // Determine whether this canonical template specialization type already
3707 llvm::FoldingSetNodeID ID;
3708 TemplateSpecializationType::Profile(ID, CanonTemplate,
3711 void *InsertPos = nullptr;
3712 TemplateSpecializationType *Spec
3713 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3716 // Allocate a new canonical template specialization type.
3717 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3718 sizeof(TemplateArgument) * NumArgs),
3720 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3722 QualType(), QualType());
3723 Types.push_back(Spec);
3724 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3727 assert(Spec->isDependentType() &&
3728 "Non-dependent template-id type must have a canonical type");
3729 return QualType(Spec, 0);
3733 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3734 NestedNameSpecifier *NNS,
3735 QualType NamedType) const {
3736 llvm::FoldingSetNodeID ID;
3737 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3739 void *InsertPos = nullptr;
3740 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3742 return QualType(T, 0);
3744 QualType Canon = NamedType;
3745 if (!Canon.isCanonical()) {
3746 Canon = getCanonicalType(NamedType);
3747 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3748 assert(!CheckT && "Elaborated canonical type broken");
3752 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3754 ElaboratedTypes.InsertNode(T, InsertPos);
3755 return QualType(T, 0);
3759 ASTContext::getParenType(QualType InnerType) const {
3760 llvm::FoldingSetNodeID ID;
3761 ParenType::Profile(ID, InnerType);
3763 void *InsertPos = nullptr;
3764 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3766 return QualType(T, 0);
3768 QualType Canon = InnerType;
3769 if (!Canon.isCanonical()) {
3770 Canon = getCanonicalType(InnerType);
3771 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3772 assert(!CheckT && "Paren canonical type broken");
3776 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3778 ParenTypes.InsertNode(T, InsertPos);
3779 return QualType(T, 0);
3782 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3783 NestedNameSpecifier *NNS,
3784 const IdentifierInfo *Name,
3785 QualType Canon) const {
3786 if (Canon.isNull()) {
3787 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3788 ElaboratedTypeKeyword CanonKeyword = Keyword;
3789 if (Keyword == ETK_None)
3790 CanonKeyword = ETK_Typename;
3792 if (CanonNNS != NNS || CanonKeyword != Keyword)
3793 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3796 llvm::FoldingSetNodeID ID;
3797 DependentNameType::Profile(ID, Keyword, NNS, Name);
3799 void *InsertPos = nullptr;
3800 DependentNameType *T
3801 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3803 return QualType(T, 0);
3805 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3807 DependentNameTypes.InsertNode(T, InsertPos);
3808 return QualType(T, 0);
3812 ASTContext::getDependentTemplateSpecializationType(
3813 ElaboratedTypeKeyword Keyword,
3814 NestedNameSpecifier *NNS,
3815 const IdentifierInfo *Name,
3816 const TemplateArgumentListInfo &Args) const {
3817 // TODO: avoid this copy
3818 SmallVector<TemplateArgument, 16> ArgCopy;
3819 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3820 ArgCopy.push_back(Args[I].getArgument());
3821 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3825 ASTContext::getDependentTemplateSpecializationType(
3826 ElaboratedTypeKeyword Keyword,
3827 NestedNameSpecifier *NNS,
3828 const IdentifierInfo *Name,
3829 ArrayRef<TemplateArgument> Args) const {
3830 assert((!NNS || NNS->isDependent()) &&
3831 "nested-name-specifier must be dependent");
3833 llvm::FoldingSetNodeID ID;
3834 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3837 void *InsertPos = nullptr;
3838 DependentTemplateSpecializationType *T
3839 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3841 return QualType(T, 0);
3843 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3845 ElaboratedTypeKeyword CanonKeyword = Keyword;
3846 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3848 bool AnyNonCanonArgs = false;
3849 unsigned NumArgs = Args.size();
3850 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3851 for (unsigned I = 0; I != NumArgs; ++I) {
3852 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3853 if (!CanonArgs[I].structurallyEquals(Args[I]))
3854 AnyNonCanonArgs = true;
3858 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3859 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3863 // Find the insert position again.
3864 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3867 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3868 sizeof(TemplateArgument) * NumArgs),
3870 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3873 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3874 return QualType(T, 0);
3878 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3879 SmallVectorImpl<TemplateArgument> &Args) {
3880 Args.reserve(Args.size() + Params->size());
3882 for (NamedDecl *Param : *Params) {
3883 TemplateArgument Arg;
3884 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3885 QualType ArgType = getTypeDeclType(TTP);
3886 if (TTP->isParameterPack())
3887 ArgType = getPackExpansionType(ArgType, None);
3889 Arg = TemplateArgument(ArgType);
3890 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3891 Expr *E = new (*this) DeclRefExpr(
3892 NTTP, /*enclosing*/false,
3893 NTTP->getType().getNonLValueExprType(*this),
3894 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3896 if (NTTP->isParameterPack())
3897 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3899 Arg = TemplateArgument(E);
3901 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3902 if (TTP->isParameterPack())
3903 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3905 Arg = TemplateArgument(TemplateName(TTP));
3908 if (Param->isTemplateParameterPack())
3909 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3911 Args.push_back(Arg);
3915 QualType ASTContext::getPackExpansionType(QualType Pattern,
3916 Optional<unsigned> NumExpansions) {
3917 llvm::FoldingSetNodeID ID;
3918 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3920 assert(Pattern->containsUnexpandedParameterPack() &&
3921 "Pack expansions must expand one or more parameter packs");
3922 void *InsertPos = nullptr;
3923 PackExpansionType *T
3924 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3926 return QualType(T, 0);
3929 if (!Pattern.isCanonical()) {
3930 Canon = getCanonicalType(Pattern);
3931 // The canonical type might not contain an unexpanded parameter pack, if it
3932 // contains an alias template specialization which ignores one of its
3934 if (Canon->containsUnexpandedParameterPack()) {
3935 Canon = getPackExpansionType(Canon, NumExpansions);
3937 // Find the insert position again, in case we inserted an element into
3938 // PackExpansionTypes and invalidated our insert position.
3939 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3943 T = new (*this, TypeAlignment)
3944 PackExpansionType(Pattern, Canon, NumExpansions);
3946 PackExpansionTypes.InsertNode(T, InsertPos);
3947 return QualType(T, 0);
3950 /// CmpProtocolNames - Comparison predicate for sorting protocols
3952 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3953 ObjCProtocolDecl *const *RHS) {
3954 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3957 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3958 if (Protocols.empty()) return true;
3960 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3963 for (unsigned i = 1; i != Protocols.size(); ++i)
3964 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3965 Protocols[i]->getCanonicalDecl() != Protocols[i])
3971 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3972 // Sort protocols, keyed by name.
3973 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3976 for (ObjCProtocolDecl *&P : Protocols)
3977 P = P->getCanonicalDecl();
3979 // Remove duplicates.
3980 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3981 Protocols.erase(ProtocolsEnd, Protocols.end());
3984 QualType ASTContext::getObjCObjectType(QualType BaseType,
3985 ObjCProtocolDecl * const *Protocols,
3986 unsigned NumProtocols) const {
3987 return getObjCObjectType(BaseType, { },
3988 llvm::makeArrayRef(Protocols, NumProtocols),
3989 /*isKindOf=*/false);
3992 QualType ASTContext::getObjCObjectType(
3994 ArrayRef<QualType> typeArgs,
3995 ArrayRef<ObjCProtocolDecl *> protocols,
3996 bool isKindOf) const {
3997 // If the base type is an interface and there aren't any protocols or
3998 // type arguments to add, then the interface type will do just fine.
3999 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4000 isa<ObjCInterfaceType>(baseType))
4003 // Look in the folding set for an existing type.
4004 llvm::FoldingSetNodeID ID;
4005 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4006 void *InsertPos = nullptr;
4007 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4008 return QualType(QT, 0);
4010 // Determine the type arguments to be used for canonicalization,
4011 // which may be explicitly specified here or written on the base
4013 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4014 if (effectiveTypeArgs.empty()) {
4015 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4016 effectiveTypeArgs = baseObject->getTypeArgs();
4019 // Build the canonical type, which has the canonical base type and a
4020 // sorted-and-uniqued list of protocols and the type arguments
4023 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4024 effectiveTypeArgs.end(),
4025 [&](QualType type) {
4026 return type.isCanonical();
4028 bool protocolsSorted = areSortedAndUniqued(protocols);
4029 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4030 // Determine the canonical type arguments.
4031 ArrayRef<QualType> canonTypeArgs;
4032 SmallVector<QualType, 4> canonTypeArgsVec;
4033 if (!typeArgsAreCanonical) {
4034 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4035 for (auto typeArg : effectiveTypeArgs)
4036 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4037 canonTypeArgs = canonTypeArgsVec;
4039 canonTypeArgs = effectiveTypeArgs;
4042 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4043 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4044 if (!protocolsSorted) {
4045 canonProtocolsVec.append(protocols.begin(), protocols.end());
4046 SortAndUniqueProtocols(canonProtocolsVec);
4047 canonProtocols = canonProtocolsVec;
4049 canonProtocols = protocols;
4052 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4053 canonProtocols, isKindOf);
4055 // Regenerate InsertPos.
4056 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4059 unsigned size = sizeof(ObjCObjectTypeImpl);
4060 size += typeArgs.size() * sizeof(QualType);
4061 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4062 void *mem = Allocate(size, TypeAlignment);
4063 ObjCObjectTypeImpl *T =
4064 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4068 ObjCObjectTypes.InsertNode(T, InsertPos);
4069 return QualType(T, 0);
4072 /// Apply Objective-C protocol qualifiers to the given type.
4073 /// If this is for the canonical type of a type parameter, we can apply
4074 /// protocol qualifiers on the ObjCObjectPointerType.
4076 ASTContext::applyObjCProtocolQualifiers(QualType type,
4077 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4078 bool allowOnPointerType) const {
4081 if (const ObjCTypeParamType *objT =
4082 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4083 return getObjCTypeParamType(objT->getDecl(), protocols);
4086 // Apply protocol qualifiers to ObjCObjectPointerType.
4087 if (allowOnPointerType) {
4088 if (const ObjCObjectPointerType *objPtr =
4089 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4090 const ObjCObjectType *objT = objPtr->getObjectType();
4091 // Merge protocol lists and construct ObjCObjectType.
4092 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4093 protocolsVec.append(objT->qual_begin(),
4095 protocolsVec.append(protocols.begin(), protocols.end());
4096 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4097 type = getObjCObjectType(
4098 objT->getBaseType(),
4099 objT->getTypeArgsAsWritten(),
4101 objT->isKindOfTypeAsWritten());
4102 return getObjCObjectPointerType(type);
4106 // Apply protocol qualifiers to ObjCObjectType.
4107 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4108 // FIXME: Check for protocols to which the class type is already
4109 // known to conform.
4111 return getObjCObjectType(objT->getBaseType(),
4112 objT->getTypeArgsAsWritten(),
4114 objT->isKindOfTypeAsWritten());
4117 // If the canonical type is ObjCObjectType, ...
4118 if (type->isObjCObjectType()) {
4119 // Silently overwrite any existing protocol qualifiers.
4120 // TODO: determine whether that's the right thing to do.
4122 // FIXME: Check for protocols to which the class type is already
4123 // known to conform.
4124 return getObjCObjectType(type, { }, protocols, false);
4127 // id<protocol-list>
4128 if (type->isObjCIdType()) {
4129 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4130 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4131 objPtr->isKindOfType());
4132 return getObjCObjectPointerType(type);
4135 // Class<protocol-list>
4136 if (type->isObjCClassType()) {
4137 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4138 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4139 objPtr->isKindOfType());
4140 return getObjCObjectPointerType(type);
4148 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4149 ArrayRef<ObjCProtocolDecl *> protocols,
4150 QualType Canonical) const {
4151 // Look in the folding set for an existing type.
4152 llvm::FoldingSetNodeID ID;
4153 ObjCTypeParamType::Profile(ID, Decl, protocols);
4154 void *InsertPos = nullptr;
4155 if (ObjCTypeParamType *TypeParam =
4156 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4157 return QualType(TypeParam, 0);
4159 if (Canonical.isNull()) {
4160 // We canonicalize to the underlying type.
4161 Canonical = getCanonicalType(Decl->getUnderlyingType());
4162 if (!protocols.empty()) {
4163 // Apply the protocol qualifers.
4165 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4166 true/*allowOnPointerType*/);
4167 assert(!hasError && "Error when apply protocol qualifier to bound type");
4171 unsigned size = sizeof(ObjCTypeParamType);
4172 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4173 void *mem = Allocate(size, TypeAlignment);
4174 ObjCTypeParamType *newType = new (mem)
4175 ObjCTypeParamType(Decl, Canonical, protocols);
4177 Types.push_back(newType);
4178 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4179 return QualType(newType, 0);
4182 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4183 /// protocol list adopt all protocols in QT's qualified-id protocol
4185 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4186 ObjCInterfaceDecl *IC) {
4187 if (!QT->isObjCQualifiedIdType())
4190 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4191 // If both the right and left sides have qualifiers.
4192 for (auto *Proto : OPT->quals()) {
4193 if (!IC->ClassImplementsProtocol(Proto, false))
4201 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4202 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4204 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4205 ObjCInterfaceDecl *IDecl) {
4206 if (!QT->isObjCQualifiedIdType())
4208 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4211 if (!IDecl->hasDefinition())
4213 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4214 CollectInheritedProtocols(IDecl, InheritedProtocols);
4215 if (InheritedProtocols.empty())
4217 // Check that if every protocol in list of id<plist> conforms to a protcol
4218 // of IDecl's, then bridge casting is ok.
4219 bool Conforms = false;
4220 for (auto *Proto : OPT->quals()) {
4222 for (auto *PI : InheritedProtocols) {
4223 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4234 for (auto *PI : InheritedProtocols) {
4235 // If both the right and left sides have qualifiers.
4236 bool Adopts = false;
4237 for (auto *Proto : OPT->quals()) {
4238 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4239 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4248 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4249 /// the given object type.
4250 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4251 llvm::FoldingSetNodeID ID;
4252 ObjCObjectPointerType::Profile(ID, ObjectT);
4254 void *InsertPos = nullptr;
4255 if (ObjCObjectPointerType *QT =
4256 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4257 return QualType(QT, 0);
4259 // Find the canonical object type.
4261 if (!ObjectT.isCanonical()) {
4262 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4264 // Regenerate InsertPos.
4265 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4269 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4270 ObjCObjectPointerType *QType =
4271 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4273 Types.push_back(QType);
4274 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4275 return QualType(QType, 0);
4278 /// getObjCInterfaceType - Return the unique reference to the type for the
4279 /// specified ObjC interface decl. The list of protocols is optional.
4280 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4281 ObjCInterfaceDecl *PrevDecl) const {
4282 if (Decl->TypeForDecl)
4283 return QualType(Decl->TypeForDecl, 0);
4286 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4287 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4288 return QualType(PrevDecl->TypeForDecl, 0);
4291 // Prefer the definition, if there is one.
4292 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4295 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4296 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4297 Decl->TypeForDecl = T;
4299 return QualType(T, 0);
4302 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4303 /// TypeOfExprType AST's (since expression's are never shared). For example,
4304 /// multiple declarations that refer to "typeof(x)" all contain different
4305 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4306 /// on canonical type's (which are always unique).
4307 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4308 TypeOfExprType *toe;
4309 if (tofExpr->isTypeDependent()) {
4310 llvm::FoldingSetNodeID ID;
4311 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4313 void *InsertPos = nullptr;
4314 DependentTypeOfExprType *Canon
4315 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4317 // We already have a "canonical" version of an identical, dependent
4318 // typeof(expr) type. Use that as our canonical type.
4319 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4320 QualType((TypeOfExprType*)Canon, 0));
4322 // Build a new, canonical typeof(expr) type.
4324 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4325 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4329 QualType Canonical = getCanonicalType(tofExpr->getType());
4330 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4332 Types.push_back(toe);
4333 return QualType(toe, 0);
4336 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4337 /// TypeOfType nodes. The only motivation to unique these nodes would be
4338 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4339 /// an issue. This doesn't affect the type checker, since it operates
4340 /// on canonical types (which are always unique).
4341 QualType ASTContext::getTypeOfType(QualType tofType) const {
4342 QualType Canonical = getCanonicalType(tofType);
4343 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4344 Types.push_back(tot);
4345 return QualType(tot, 0);
4348 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4349 /// nodes. This would never be helpful, since each such type has its own
4350 /// expression, and would not give a significant memory saving, since there
4351 /// is an Expr tree under each such type.
4352 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4355 // C++11 [temp.type]p2:
4356 // If an expression e involves a template parameter, decltype(e) denotes a
4357 // unique dependent type. Two such decltype-specifiers refer to the same
4358 // type only if their expressions are equivalent (14.5.6.1).
4359 if (e->isInstantiationDependent()) {
4360 llvm::FoldingSetNodeID ID;
4361 DependentDecltypeType::Profile(ID, *this, e);
4363 void *InsertPos = nullptr;
4364 DependentDecltypeType *Canon
4365 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4367 // Build a new, canonical decltype(expr) type.
4368 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4369 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4371 dt = new (*this, TypeAlignment)
4372 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4374 dt = new (*this, TypeAlignment)
4375 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4377 Types.push_back(dt);
4378 return QualType(dt, 0);
4381 /// getUnaryTransformationType - We don't unique these, since the memory
4382 /// savings are minimal and these are rare.
4383 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4384 QualType UnderlyingType,
4385 UnaryTransformType::UTTKind Kind)
4387 UnaryTransformType *ut = nullptr;
4389 if (BaseType->isDependentType()) {
4390 // Look in the folding set for an existing type.
4391 llvm::FoldingSetNodeID ID;
4392 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4394 void *InsertPos = nullptr;
4395 DependentUnaryTransformType *Canon
4396 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4399 // Build a new, canonical __underlying_type(type) type.
4400 Canon = new (*this, TypeAlignment)
4401 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4403 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4405 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4407 QualType(Canon, 0));
4409 QualType CanonType = getCanonicalType(UnderlyingType);
4410 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4411 UnderlyingType, Kind,
4414 Types.push_back(ut);
4415 return QualType(ut, 0);
4418 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4419 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4420 /// canonical deduced-but-dependent 'auto' type.
4421 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4422 bool IsDependent) const {
4423 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4424 return getAutoDeductType();
4426 // Look in the folding set for an existing type.
4427 void *InsertPos = nullptr;
4428 llvm::FoldingSetNodeID ID;
4429 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4430 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4431 return QualType(AT, 0);
4433 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4436 Types.push_back(AT);
4438 AutoTypes.InsertNode(AT, InsertPos);
4439 return QualType(AT, 0);
4442 /// getAtomicType - Return the uniqued reference to the atomic type for
4443 /// the given value type.
4444 QualType ASTContext::getAtomicType(QualType T) const {
4445 // Unique pointers, to guarantee there is only one pointer of a particular
4447 llvm::FoldingSetNodeID ID;
4448 AtomicType::Profile(ID, T);
4450 void *InsertPos = nullptr;
4451 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4452 return QualType(AT, 0);
4454 // If the atomic value type isn't canonical, this won't be a canonical type
4455 // either, so fill in the canonical type field.
4457 if (!T.isCanonical()) {
4458 Canonical = getAtomicType(getCanonicalType(T));
4460 // Get the new insert position for the node we care about.
4461 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4462 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4464 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4465 Types.push_back(New);
4466 AtomicTypes.InsertNode(New, InsertPos);
4467 return QualType(New, 0);
4470 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4471 QualType ASTContext::getAutoDeductType() const {
4472 if (AutoDeductTy.isNull())
4473 AutoDeductTy = QualType(
4474 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4475 /*dependent*/false),
4477 return AutoDeductTy;
4480 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4481 QualType ASTContext::getAutoRRefDeductType() const {
4482 if (AutoRRefDeductTy.isNull())
4483 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4484 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4485 return AutoRRefDeductTy;
4488 /// getTagDeclType - Return the unique reference to the type for the
4489 /// specified TagDecl (struct/union/class/enum) decl.
4490 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4492 // FIXME: What is the design on getTagDeclType when it requires casting
4493 // away const? mutable?
4494 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4497 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4498 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4499 /// needs to agree with the definition in <stddef.h>.
4500 CanQualType ASTContext::getSizeType() const {
4501 return getFromTargetType(Target->getSizeType());
4504 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4505 CanQualType ASTContext::getIntMaxType() const {
4506 return getFromTargetType(Target->getIntMaxType());
4509 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4510 CanQualType ASTContext::getUIntMaxType() const {
4511 return getFromTargetType(Target->getUIntMaxType());
4514 /// getSignedWCharType - Return the type of "signed wchar_t".
4515 /// Used when in C++, as a GCC extension.
4516 QualType ASTContext::getSignedWCharType() const {
4517 // FIXME: derive from "Target" ?
4521 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4522 /// Used when in C++, as a GCC extension.
4523 QualType ASTContext::getUnsignedWCharType() const {
4524 // FIXME: derive from "Target" ?
4525 return UnsignedIntTy;
4528 QualType ASTContext::getIntPtrType() const {
4529 return getFromTargetType(Target->getIntPtrType());
4532 QualType ASTContext::getUIntPtrType() const {
4533 return getCorrespondingUnsignedType(getIntPtrType());
4536 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4537 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4538 QualType ASTContext::getPointerDiffType() const {
4539 return getFromTargetType(Target->getPtrDiffType(0));
4542 /// \brief Return the unique type for "pid_t" defined in
4543 /// <sys/types.h>. We need this to compute the correct type for vfork().
4544 QualType ASTContext::getProcessIDType() const {
4545 return getFromTargetType(Target->getProcessIDType());
4548 //===----------------------------------------------------------------------===//
4550 //===----------------------------------------------------------------------===//
4552 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4553 // Push qualifiers into arrays, and then discard any remaining
4555 T = getCanonicalType(T);
4556 T = getVariableArrayDecayedType(T);
4557 const Type *Ty = T.getTypePtr();
4559 if (isa<ArrayType>(Ty)) {
4560 Result = getArrayDecayedType(QualType(Ty,0));
4561 } else if (isa<FunctionType>(Ty)) {
4562 Result = getPointerType(QualType(Ty, 0));
4564 Result = QualType(Ty, 0);
4567 return CanQualType::CreateUnsafe(Result);
4570 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4571 Qualifiers &quals) {
4572 SplitQualType splitType = type.getSplitUnqualifiedType();
4574 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4575 // the unqualified desugared type and then drops it on the floor.
4576 // We then have to strip that sugar back off with
4577 // getUnqualifiedDesugaredType(), which is silly.
4578 const ArrayType *AT =
4579 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4581 // If we don't have an array, just use the results in splitType.
4583 quals = splitType.Quals;
4584 return QualType(splitType.Ty, 0);
4587 // Otherwise, recurse on the array's element type.
4588 QualType elementType = AT->getElementType();
4589 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4591 // If that didn't change the element type, AT has no qualifiers, so we
4592 // can just use the results in splitType.
4593 if (elementType == unqualElementType) {
4594 assert(quals.empty()); // from the recursive call
4595 quals = splitType.Quals;
4596 return QualType(splitType.Ty, 0);
4599 // Otherwise, add in the qualifiers from the outermost type, then
4600 // build the type back up.
4601 quals.addConsistentQualifiers(splitType.Quals);
4603 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4604 return getConstantArrayType(unqualElementType, CAT->getSize(),
4605 CAT->getSizeModifier(), 0);
4608 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4609 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4612 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4613 return getVariableArrayType(unqualElementType,
4615 VAT->getSizeModifier(),
4616 VAT->getIndexTypeCVRQualifiers(),
4617 VAT->getBracketsRange());
4620 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4621 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4622 DSAT->getSizeModifier(), 0,
4626 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4627 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4628 /// they point to and return true. If T1 and T2 aren't pointer types
4629 /// or pointer-to-member types, or if they are not similar at this
4630 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4631 /// qualifiers on T1 and T2 are ignored. This function will typically
4632 /// be called in a loop that successively "unwraps" pointer and
4633 /// pointer-to-member types to compare them at each level.
4634 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4635 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4636 *T2PtrType = T2->getAs<PointerType>();
4637 if (T1PtrType && T2PtrType) {
4638 T1 = T1PtrType->getPointeeType();
4639 T2 = T2PtrType->getPointeeType();
4643 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4644 *T2MPType = T2->getAs<MemberPointerType>();
4645 if (T1MPType && T2MPType &&
4646 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4647 QualType(T2MPType->getClass(), 0))) {
4648 T1 = T1MPType->getPointeeType();
4649 T2 = T2MPType->getPointeeType();
4653 if (getLangOpts().ObjC1) {
4654 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4655 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4656 if (T1OPType && T2OPType) {
4657 T1 = T1OPType->getPointeeType();
4658 T2 = T2OPType->getPointeeType();
4663 // FIXME: Block pointers, too?
4669 ASTContext::getNameForTemplate(TemplateName Name,
4670 SourceLocation NameLoc) const {
4671 switch (Name.getKind()) {
4672 case TemplateName::QualifiedTemplate:
4673 case TemplateName::Template:
4674 // DNInfo work in progress: CHECKME: what about DNLoc?
4675 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4678 case TemplateName::OverloadedTemplate: {
4679 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4680 // DNInfo work in progress: CHECKME: what about DNLoc?
4681 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4684 case TemplateName::DependentTemplate: {
4685 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4686 DeclarationName DName;
4687 if (DTN->isIdentifier()) {
4688 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4689 return DeclarationNameInfo(DName, NameLoc);
4691 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4692 // DNInfo work in progress: FIXME: source locations?
4693 DeclarationNameLoc DNLoc;
4694 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4695 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4696 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4700 case TemplateName::SubstTemplateTemplateParm: {
4701 SubstTemplateTemplateParmStorage *subst
4702 = Name.getAsSubstTemplateTemplateParm();
4703 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4707 case TemplateName::SubstTemplateTemplateParmPack: {
4708 SubstTemplateTemplateParmPackStorage *subst
4709 = Name.getAsSubstTemplateTemplateParmPack();
4710 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4715 llvm_unreachable("bad template name kind!");
4718 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4719 switch (Name.getKind()) {
4720 case TemplateName::QualifiedTemplate:
4721 case TemplateName::Template: {
4722 TemplateDecl *Template = Name.getAsTemplateDecl();
4723 if (TemplateTemplateParmDecl *TTP
4724 = dyn_cast<TemplateTemplateParmDecl>(Template))
4725 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4727 // The canonical template name is the canonical template declaration.
4728 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4731 case TemplateName::OverloadedTemplate:
4732 llvm_unreachable("cannot canonicalize overloaded template");
4734 case TemplateName::DependentTemplate: {
4735 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4736 assert(DTN && "Non-dependent template names must refer to template decls.");
4737 return DTN->CanonicalTemplateName;
4740 case TemplateName::SubstTemplateTemplateParm: {
4741 SubstTemplateTemplateParmStorage *subst
4742 = Name.getAsSubstTemplateTemplateParm();
4743 return getCanonicalTemplateName(subst->getReplacement());
4746 case TemplateName::SubstTemplateTemplateParmPack: {
4747 SubstTemplateTemplateParmPackStorage *subst
4748 = Name.getAsSubstTemplateTemplateParmPack();
4749 TemplateTemplateParmDecl *canonParameter
4750 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4751 TemplateArgument canonArgPack
4752 = getCanonicalTemplateArgument(subst->getArgumentPack());
4753 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4757 llvm_unreachable("bad template name!");
4760 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4761 X = getCanonicalTemplateName(X);
4762 Y = getCanonicalTemplateName(Y);
4763 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4767 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4768 switch (Arg.getKind()) {
4769 case TemplateArgument::Null:
4772 case TemplateArgument::Expression:
4775 case TemplateArgument::Declaration: {
4776 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4777 return TemplateArgument(D, Arg.getParamTypeForDecl());
4780 case TemplateArgument::NullPtr:
4781 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4784 case TemplateArgument::Template:
4785 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4787 case TemplateArgument::TemplateExpansion:
4788 return TemplateArgument(getCanonicalTemplateName(
4789 Arg.getAsTemplateOrTemplatePattern()),
4790 Arg.getNumTemplateExpansions());
4792 case TemplateArgument::Integral:
4793 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4795 case TemplateArgument::Type:
4796 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4798 case TemplateArgument::Pack: {
4799 if (Arg.pack_size() == 0)
4802 TemplateArgument *CanonArgs
4803 = new (*this) TemplateArgument[Arg.pack_size()];
4805 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4806 AEnd = Arg.pack_end();
4807 A != AEnd; (void)++A, ++Idx)
4808 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4810 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4814 // Silence GCC warning
4815 llvm_unreachable("Unhandled template argument kind");
4818 NestedNameSpecifier *
4819 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4823 switch (NNS->getKind()) {
4824 case NestedNameSpecifier::Identifier:
4825 // Canonicalize the prefix but keep the identifier the same.
4826 return NestedNameSpecifier::Create(*this,
4827 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4828 NNS->getAsIdentifier());
4830 case NestedNameSpecifier::Namespace:
4831 // A namespace is canonical; build a nested-name-specifier with
4832 // this namespace and no prefix.
4833 return NestedNameSpecifier::Create(*this, nullptr,
4834 NNS->getAsNamespace()->getOriginalNamespace());
4836 case NestedNameSpecifier::NamespaceAlias:
4837 // A namespace is canonical; build a nested-name-specifier with
4838 // this namespace and no prefix.
4839 return NestedNameSpecifier::Create(*this, nullptr,
4840 NNS->getAsNamespaceAlias()->getNamespace()
4841 ->getOriginalNamespace());
4843 case NestedNameSpecifier::TypeSpec:
4844 case NestedNameSpecifier::TypeSpecWithTemplate: {
4845 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4847 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4848 // break it apart into its prefix and identifier, then reconsititute those
4849 // as the canonical nested-name-specifier. This is required to canonicalize
4850 // a dependent nested-name-specifier involving typedefs of dependent-name
4852 // typedef typename T::type T1;
4853 // typedef typename T1::type T2;
4854 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4855 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4856 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4858 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4859 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4861 return NestedNameSpecifier::Create(*this, nullptr, false,
4862 const_cast<Type *>(T.getTypePtr()));
4865 case NestedNameSpecifier::Global:
4866 case NestedNameSpecifier::Super:
4867 // The global specifier and __super specifer are canonical and unique.
4871 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4874 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4875 // Handle the non-qualified case efficiently.
4876 if (!T.hasLocalQualifiers()) {
4877 // Handle the common positive case fast.
4878 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4882 // Handle the common negative case fast.
4883 if (!isa<ArrayType>(T.getCanonicalType()))
4886 // Apply any qualifiers from the array type to the element type. This
4887 // implements C99 6.7.3p8: "If the specification of an array type includes
4888 // any type qualifiers, the element type is so qualified, not the array type."
4890 // If we get here, we either have type qualifiers on the type, or we have
4891 // sugar such as a typedef in the way. If we have type qualifiers on the type
4892 // we must propagate them down into the element type.
4894 SplitQualType split = T.getSplitDesugaredType();
4895 Qualifiers qs = split.Quals;
4897 // If we have a simple case, just return now.
4898 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4899 if (!ATy || qs.empty())
4902 // Otherwise, we have an array and we have qualifiers on it. Push the
4903 // qualifiers into the array element type and return a new array type.
4904 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4906 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4907 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4908 CAT->getSizeModifier(),
4909 CAT->getIndexTypeCVRQualifiers()));
4910 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4911 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4912 IAT->getSizeModifier(),
4913 IAT->getIndexTypeCVRQualifiers()));
4915 if (const DependentSizedArrayType *DSAT
4916 = dyn_cast<DependentSizedArrayType>(ATy))
4917 return cast<ArrayType>(
4918 getDependentSizedArrayType(NewEltTy,
4919 DSAT->getSizeExpr(),
4920 DSAT->getSizeModifier(),
4921 DSAT->getIndexTypeCVRQualifiers(),
4922 DSAT->getBracketsRange()));
4924 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4925 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4927 VAT->getSizeModifier(),
4928 VAT->getIndexTypeCVRQualifiers(),
4929 VAT->getBracketsRange()));
4932 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4933 if (T->isArrayType() || T->isFunctionType())
4934 return getDecayedType(T);
4938 QualType ASTContext::getSignatureParameterType(QualType T) const {
4939 T = getVariableArrayDecayedType(T);
4940 T = getAdjustedParameterType(T);
4941 return T.getUnqualifiedType();
4944 QualType ASTContext::getExceptionObjectType(QualType T) const {
4945 // C++ [except.throw]p3:
4946 // A throw-expression initializes a temporary object, called the exception
4947 // object, the type of which is determined by removing any top-level
4948 // cv-qualifiers from the static type of the operand of throw and adjusting
4949 // the type from "array of T" or "function returning T" to "pointer to T"
4950 // or "pointer to function returning T", [...]
4951 T = getVariableArrayDecayedType(T);
4952 if (T->isArrayType() || T->isFunctionType())
4953 T = getDecayedType(T);
4954 return T.getUnqualifiedType();
4957 /// getArrayDecayedType - Return the properly qualified result of decaying the
4958 /// specified array type to a pointer. This operation is non-trivial when
4959 /// handling typedefs etc. The canonical type of "T" must be an array type,
4960 /// this returns a pointer to a properly qualified element of the array.
4962 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4963 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4964 // Get the element type with 'getAsArrayType' so that we don't lose any
4965 // typedefs in the element type of the array. This also handles propagation
4966 // of type qualifiers from the array type into the element type if present
4968 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4969 assert(PrettyArrayType && "Not an array type!");
4971 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4973 // int x[restrict 4] -> int *restrict
4974 QualType Result = getQualifiedType(PtrTy,
4975 PrettyArrayType->getIndexTypeQualifiers());
4977 // int x[_Nullable] -> int * _Nullable
4978 if (auto Nullability = Ty->getNullability(*this)) {
4979 Result = const_cast<ASTContext *>(this)->getAttributedType(
4980 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
4985 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4986 return getBaseElementType(array->getElementType());
4989 QualType ASTContext::getBaseElementType(QualType type) const {
4992 SplitQualType split = type.getSplitDesugaredType();
4993 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4996 type = array->getElementType();
4997 qs.addConsistentQualifiers(split.Quals);
5000 return getQualifiedType(type, qs);
5003 /// getConstantArrayElementCount - Returns number of constant array elements.
5005 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5006 uint64_t ElementCount = 1;
5008 ElementCount *= CA->getSize().getZExtValue();
5009 CA = dyn_cast_or_null<ConstantArrayType>(
5010 CA->getElementType()->getAsArrayTypeUnsafe());
5012 return ElementCount;
5015 /// getFloatingRank - Return a relative rank for floating point types.
5016 /// This routine will assert if passed a built-in type that isn't a float.
5017 static FloatingRank getFloatingRank(QualType T) {
5018 if (const ComplexType *CT = T->getAs<ComplexType>())
5019 return getFloatingRank(CT->getElementType());
5021 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5022 switch (T->getAs<BuiltinType>()->getKind()) {
5023 default: llvm_unreachable("getFloatingRank(): not a floating type");
5024 case BuiltinType::Half: return HalfRank;
5025 case BuiltinType::Float: return FloatRank;
5026 case BuiltinType::Double: return DoubleRank;
5027 case BuiltinType::LongDouble: return LongDoubleRank;
5028 case BuiltinType::Float128: return Float128Rank;
5032 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5033 /// point or a complex type (based on typeDomain/typeSize).
5034 /// 'typeDomain' is a real floating point or complex type.
5035 /// 'typeSize' is a real floating point or complex type.
5036 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5037 QualType Domain) const {
5038 FloatingRank EltRank = getFloatingRank(Size);
5039 if (Domain->isComplexType()) {
5041 case HalfRank: llvm_unreachable("Complex half is not supported");
5042 case FloatRank: return FloatComplexTy;
5043 case DoubleRank: return DoubleComplexTy;
5044 case LongDoubleRank: return LongDoubleComplexTy;
5045 case Float128Rank: return Float128ComplexTy;
5049 assert(Domain->isRealFloatingType() && "Unknown domain!");
5051 case HalfRank: return HalfTy;
5052 case FloatRank: return FloatTy;
5053 case DoubleRank: return DoubleTy;
5054 case LongDoubleRank: return LongDoubleTy;
5055 case Float128Rank: return Float128Ty;
5057 llvm_unreachable("getFloatingRank(): illegal value for rank");
5060 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5061 /// point types, ignoring the domain of the type (i.e. 'double' ==
5062 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5063 /// LHS < RHS, return -1.
5064 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5065 FloatingRank LHSR = getFloatingRank(LHS);
5066 FloatingRank RHSR = getFloatingRank(RHS);
5075 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5076 /// routine will assert if passed a built-in type that isn't an integer or enum,
5077 /// or if it is not canonicalized.
5078 unsigned ASTContext::getIntegerRank(const Type *T) const {
5079 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5081 switch (cast<BuiltinType>(T)->getKind()) {
5082 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5083 case BuiltinType::Bool:
5084 return 1 + (getIntWidth(BoolTy) << 3);
5085 case BuiltinType::Char_S:
5086 case BuiltinType::Char_U:
5087 case BuiltinType::SChar:
5088 case BuiltinType::UChar:
5089 return 2 + (getIntWidth(CharTy) << 3);
5090 case BuiltinType::Short:
5091 case BuiltinType::UShort:
5092 return 3 + (getIntWidth(ShortTy) << 3);
5093 case BuiltinType::Int:
5094 case BuiltinType::UInt:
5095 return 4 + (getIntWidth(IntTy) << 3);
5096 case BuiltinType::Long:
5097 case BuiltinType::ULong:
5098 return 5 + (getIntWidth(LongTy) << 3);
5099 case BuiltinType::LongLong:
5100 case BuiltinType::ULongLong:
5101 return 6 + (getIntWidth(LongLongTy) << 3);
5102 case BuiltinType::Int128:
5103 case BuiltinType::UInt128:
5104 return 7 + (getIntWidth(Int128Ty) << 3);
5108 /// \brief Whether this is a promotable bitfield reference according
5109 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5111 /// \returns the type this bit-field will promote to, or NULL if no
5112 /// promotion occurs.
5113 QualType ASTContext::isPromotableBitField(Expr *E) const {
5114 if (E->isTypeDependent() || E->isValueDependent())
5117 // FIXME: We should not do this unless E->refersToBitField() is true. This
5118 // matters in C where getSourceBitField() will find bit-fields for various
5119 // cases where the source expression is not a bit-field designator.
5121 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5125 QualType FT = Field->getType();
5127 uint64_t BitWidth = Field->getBitWidthValue(*this);
5128 uint64_t IntSize = getTypeSize(IntTy);
5129 // C++ [conv.prom]p5:
5130 // A prvalue for an integral bit-field can be converted to a prvalue of type
5131 // int if int can represent all the values of the bit-field; otherwise, it
5132 // can be converted to unsigned int if unsigned int can represent all the
5133 // values of the bit-field. If the bit-field is larger yet, no integral
5134 // promotion applies to it.
5136 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5137 // If an int can represent all values of the original type (as restricted by
5138 // the width, for a bit-field), the value is converted to an int; otherwise,
5139 // it is converted to an unsigned int.
5141 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5142 // We perform that promotion here to match GCC and C++.
5143 if (BitWidth < IntSize)
5146 if (BitWidth == IntSize)
5147 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5149 // Types bigger than int are not subject to promotions, and therefore act
5150 // like the base type. GCC has some weird bugs in this area that we
5151 // deliberately do not follow (GCC follows a pre-standard resolution to
5152 // C's DR315 which treats bit-width as being part of the type, and this leaks
5153 // into their semantics in some cases).
5157 /// getPromotedIntegerType - Returns the type that Promotable will
5158 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5160 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5161 assert(!Promotable.isNull());
5162 assert(Promotable->isPromotableIntegerType());
5163 if (const EnumType *ET = Promotable->getAs<EnumType>())
5164 return ET->getDecl()->getPromotionType();
5166 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5167 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5168 // (3.9.1) can be converted to a prvalue of the first of the following
5169 // types that can represent all the values of its underlying type:
5170 // int, unsigned int, long int, unsigned long int, long long int, or
5171 // unsigned long long int [...]
5172 // FIXME: Is there some better way to compute this?
5173 if (BT->getKind() == BuiltinType::WChar_S ||
5174 BT->getKind() == BuiltinType::WChar_U ||
5175 BT->getKind() == BuiltinType::Char16 ||
5176 BT->getKind() == BuiltinType::Char32) {
5177 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5178 uint64_t FromSize = getTypeSize(BT);
5179 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5180 LongLongTy, UnsignedLongLongTy };
5181 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5182 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5183 if (FromSize < ToSize ||
5184 (FromSize == ToSize &&
5185 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5186 return PromoteTypes[Idx];
5188 llvm_unreachable("char type should fit into long long");
5192 // At this point, we should have a signed or unsigned integer type.
5193 if (Promotable->isSignedIntegerType())
5195 uint64_t PromotableSize = getIntWidth(Promotable);
5196 uint64_t IntSize = getIntWidth(IntTy);
5197 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5198 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5201 /// \brief Recurses in pointer/array types until it finds an objc retainable
5202 /// type and returns its ownership.
5203 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5204 while (!T.isNull()) {
5205 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5206 return T.getObjCLifetime();
5207 if (T->isArrayType())
5208 T = getBaseElementType(T);
5209 else if (const PointerType *PT = T->getAs<PointerType>())
5210 T = PT->getPointeeType();
5211 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
5212 T = RT->getPointeeType();
5217 return Qualifiers::OCL_None;
5220 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5221 // Incomplete enum types are not treated as integer types.
5222 // FIXME: In C++, enum types are never integer types.
5223 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5224 return ET->getDecl()->getIntegerType().getTypePtr();
5228 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5229 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5230 /// LHS < RHS, return -1.
5231 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5232 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5233 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5235 // Unwrap enums to their underlying type.
5236 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5237 LHSC = getIntegerTypeForEnum(ET);
5238 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5239 RHSC = getIntegerTypeForEnum(ET);
5241 if (LHSC == RHSC) return 0;
5243 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5244 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5246 unsigned LHSRank = getIntegerRank(LHSC);
5247 unsigned RHSRank = getIntegerRank(RHSC);
5249 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5250 if (LHSRank == RHSRank) return 0;
5251 return LHSRank > RHSRank ? 1 : -1;
5254 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5256 // If the unsigned [LHS] type is larger, return it.
5257 if (LHSRank >= RHSRank)
5260 // If the signed type can represent all values of the unsigned type, it
5261 // wins. Because we are dealing with 2's complement and types that are
5262 // powers of two larger than each other, this is always safe.
5266 // If the unsigned [RHS] type is larger, return it.
5267 if (RHSRank >= LHSRank)
5270 // If the signed type can represent all values of the unsigned type, it
5271 // wins. Because we are dealing with 2's complement and types that are
5272 // powers of two larger than each other, this is always safe.
5276 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5277 if (!CFConstantStringTypeDecl) {
5278 assert(!CFConstantStringTagDecl &&
5279 "tag and typedef should be initialized together");
5280 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5281 CFConstantStringTagDecl->startDefinition();
5283 QualType FieldTypes[4];
5284 const char *FieldNames[4];
5287 FieldTypes[0] = getPointerType(IntTy.withConst());
5288 FieldNames[0] = "isa";
5290 FieldTypes[1] = IntTy;
5291 FieldNames[1] = "flags";
5293 FieldTypes[2] = getPointerType(CharTy.withConst());
5294 FieldNames[2] = "str";
5296 FieldTypes[3] = LongTy;
5297 FieldNames[3] = "length";
5300 for (unsigned i = 0; i < 4; ++i) {
5301 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5304 &Idents.get(FieldNames[i]),
5305 FieldTypes[i], /*TInfo=*/nullptr,
5306 /*BitWidth=*/nullptr,
5309 Field->setAccess(AS_public);
5310 CFConstantStringTagDecl->addDecl(Field);
5313 CFConstantStringTagDecl->completeDefinition();
5314 // This type is designed to be compatible with NSConstantString, but cannot
5315 // use the same name, since NSConstantString is an interface.
5316 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5317 CFConstantStringTypeDecl =
5318 buildImplicitTypedef(tagType, "__NSConstantString");
5321 return CFConstantStringTypeDecl;
5324 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5325 if (!CFConstantStringTagDecl)
5326 getCFConstantStringDecl(); // Build the tag and the typedef.
5327 return CFConstantStringTagDecl;
5330 // getCFConstantStringType - Return the type used for constant CFStrings.
5331 QualType ASTContext::getCFConstantStringType() const {
5332 return getTypedefType(getCFConstantStringDecl());
5335 QualType ASTContext::getObjCSuperType() const {
5336 if (ObjCSuperType.isNull()) {
5337 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5338 TUDecl->addDecl(ObjCSuperTypeDecl);
5339 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5341 return ObjCSuperType;
5344 void ASTContext::setCFConstantStringType(QualType T) {
5345 const TypedefType *TD = T->getAs<TypedefType>();
5346 assert(TD && "Invalid CFConstantStringType");
5347 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5349 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5350 assert(TagType && "Invalid CFConstantStringType");
5351 CFConstantStringTagDecl = TagType->getDecl();
5354 QualType ASTContext::getBlockDescriptorType() const {
5355 if (BlockDescriptorType)
5356 return getTagDeclType(BlockDescriptorType);
5359 // FIXME: Needs the FlagAppleBlock bit.
5360 RD = buildImplicitRecord("__block_descriptor");
5361 RD->startDefinition();
5363 QualType FieldTypes[] = {
5368 static const char *const FieldNames[] = {
5373 for (size_t i = 0; i < 2; ++i) {
5374 FieldDecl *Field = FieldDecl::Create(
5375 *this, RD, SourceLocation(), SourceLocation(),
5376 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5377 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5378 Field->setAccess(AS_public);
5382 RD->completeDefinition();
5384 BlockDescriptorType = RD;
5386 return getTagDeclType(BlockDescriptorType);
5389 QualType ASTContext::getBlockDescriptorExtendedType() const {
5390 if (BlockDescriptorExtendedType)
5391 return getTagDeclType(BlockDescriptorExtendedType);
5394 // FIXME: Needs the FlagAppleBlock bit.
5395 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5396 RD->startDefinition();
5398 QualType FieldTypes[] = {
5401 getPointerType(VoidPtrTy),
5402 getPointerType(VoidPtrTy)
5405 static const char *const FieldNames[] = {
5412 for (size_t i = 0; i < 4; ++i) {
5413 FieldDecl *Field = FieldDecl::Create(
5414 *this, RD, SourceLocation(), SourceLocation(),
5415 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5416 /*BitWidth=*/nullptr,
5417 /*Mutable=*/false, ICIS_NoInit);
5418 Field->setAccess(AS_public);
5422 RD->completeDefinition();
5424 BlockDescriptorExtendedType = RD;
5425 return getTagDeclType(BlockDescriptorExtendedType);
5428 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5429 /// requires copy/dispose. Note that this must match the logic
5430 /// in buildByrefHelpers.
5431 bool ASTContext::BlockRequiresCopying(QualType Ty,
5433 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5434 const Expr *copyExpr = getBlockVarCopyInits(D);
5435 if (!copyExpr && record->hasTrivialDestructor()) return false;
5440 if (!Ty->isObjCRetainableType()) return false;
5442 Qualifiers qs = Ty.getQualifiers();
5444 // If we have lifetime, that dominates.
5445 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5447 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5449 // These are just bits as far as the runtime is concerned.
5450 case Qualifiers::OCL_ExplicitNone:
5451 case Qualifiers::OCL_Autoreleasing:
5454 // Tell the runtime that this is ARC __weak, called by the
5456 case Qualifiers::OCL_Weak:
5457 // ARC __strong __block variables need to be retained.
5458 case Qualifiers::OCL_Strong:
5461 llvm_unreachable("fell out of lifetime switch!");
5463 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5464 Ty->isObjCObjectPointerType());
5467 bool ASTContext::getByrefLifetime(QualType Ty,
5468 Qualifiers::ObjCLifetime &LifeTime,
5469 bool &HasByrefExtendedLayout) const {
5471 if (!getLangOpts().ObjC1 ||
5472 getLangOpts().getGC() != LangOptions::NonGC)
5475 HasByrefExtendedLayout = false;
5476 if (Ty->isRecordType()) {
5477 HasByrefExtendedLayout = true;
5478 LifeTime = Qualifiers::OCL_None;
5479 } else if ((LifeTime = Ty.getObjCLifetime())) {
5480 // Honor the ARC qualifiers.
5481 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5483 LifeTime = Qualifiers::OCL_ExplicitNone;
5485 LifeTime = Qualifiers::OCL_None;
5490 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5491 if (!ObjCInstanceTypeDecl)
5492 ObjCInstanceTypeDecl =
5493 buildImplicitTypedef(getObjCIdType(), "instancetype");
5494 return ObjCInstanceTypeDecl;
5497 // This returns true if a type has been typedefed to BOOL:
5498 // typedef <type> BOOL;
5499 static bool isTypeTypedefedAsBOOL(QualType T) {
5500 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5501 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5502 return II->isStr("BOOL");
5507 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5509 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5510 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5511 return CharUnits::Zero();
5513 CharUnits sz = getTypeSizeInChars(type);
5515 // Make all integer and enum types at least as large as an int
5516 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5517 sz = std::max(sz, getTypeSizeInChars(IntTy));
5518 // Treat arrays as pointers, since that's how they're passed in.
5519 else if (type->isArrayType())
5520 sz = getTypeSizeInChars(VoidPtrTy);
5524 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5525 return getTargetInfo().getCXXABI().isMicrosoft() &&
5526 VD->isStaticDataMember() &&
5527 VD->getType()->isIntegralOrEnumerationType() &&
5528 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5531 ASTContext::InlineVariableDefinitionKind
5532 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5533 if (!VD->isInline())
5534 return InlineVariableDefinitionKind::None;
5536 // In almost all cases, it's a weak definition.
5537 auto *First = VD->getFirstDecl();
5538 if (!First->isConstexpr() || First->isInlineSpecified() ||
5539 !VD->isStaticDataMember())
5540 return InlineVariableDefinitionKind::Weak;
5542 // If there's a file-context declaration in this translation unit, it's a
5543 // non-discardable definition.
5544 for (auto *D : VD->redecls())
5545 if (D->getLexicalDeclContext()->isFileContext())
5546 return InlineVariableDefinitionKind::Strong;
5548 // If we've not seen one yet, we don't know.
5549 return InlineVariableDefinitionKind::WeakUnknown;
5553 std::string charUnitsToString(const CharUnits &CU) {
5554 return llvm::itostr(CU.getQuantity());
5557 /// getObjCEncodingForBlock - Return the encoded type for this block
5559 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5562 const BlockDecl *Decl = Expr->getBlockDecl();
5564 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5565 // Encode result type.
5566 if (getLangOpts().EncodeExtendedBlockSig)
5567 getObjCEncodingForMethodParameter(
5568 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5571 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5572 // Compute size of all parameters.
5573 // Start with computing size of a pointer in number of bytes.
5574 // FIXME: There might(should) be a better way of doing this computation!
5576 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5577 CharUnits ParmOffset = PtrSize;
5578 for (auto PI : Decl->parameters()) {
5579 QualType PType = PI->getType();
5580 CharUnits sz = getObjCEncodingTypeSize(PType);
5583 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5586 // Size of the argument frame
5587 S += charUnitsToString(ParmOffset);
5588 // Block pointer and offset.
5592 ParmOffset = PtrSize;
5593 for (auto PVDecl : Decl->parameters()) {
5594 QualType PType = PVDecl->getOriginalType();
5595 if (const ArrayType *AT =
5596 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5597 // Use array's original type only if it has known number of
5599 if (!isa<ConstantArrayType>(AT))
5600 PType = PVDecl->getType();
5601 } else if (PType->isFunctionType())
5602 PType = PVDecl->getType();
5603 if (getLangOpts().EncodeExtendedBlockSig)
5604 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5605 S, true /*Extended*/);
5607 getObjCEncodingForType(PType, S);
5608 S += charUnitsToString(ParmOffset);
5609 ParmOffset += getObjCEncodingTypeSize(PType);
5616 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5618 // Encode result type.
5619 getObjCEncodingForType(Decl->getReturnType(), S);
5620 CharUnits ParmOffset;
5621 // Compute size of all parameters.
5622 for (auto PI : Decl->parameters()) {
5623 QualType PType = PI->getType();
5624 CharUnits sz = getObjCEncodingTypeSize(PType);
5628 assert(sz.isPositive() &&
5629 "getObjCEncodingForFunctionDecl - Incomplete param type");
5632 S += charUnitsToString(ParmOffset);
5633 ParmOffset = CharUnits::Zero();
5636 for (auto PVDecl : Decl->parameters()) {
5637 QualType PType = PVDecl->getOriginalType();
5638 if (const ArrayType *AT =
5639 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5640 // Use array's original type only if it has known number of
5642 if (!isa<ConstantArrayType>(AT))
5643 PType = PVDecl->getType();
5644 } else if (PType->isFunctionType())
5645 PType = PVDecl->getType();
5646 getObjCEncodingForType(PType, S);
5647 S += charUnitsToString(ParmOffset);
5648 ParmOffset += getObjCEncodingTypeSize(PType);
5654 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5655 /// method parameter or return type. If Extended, include class names and
5656 /// block object types.
5657 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5658 QualType T, std::string& S,
5659 bool Extended) const {
5660 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5661 getObjCEncodingForTypeQualifier(QT, S);
5662 // Encode parameter type.
5663 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5664 true /*OutermostType*/,
5665 false /*EncodingProperty*/,
5666 false /*StructField*/,
5667 Extended /*EncodeBlockParameters*/,
5668 Extended /*EncodeClassNames*/);
5671 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5673 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5674 bool Extended) const {
5675 // FIXME: This is not very efficient.
5676 // Encode return type.
5678 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5679 Decl->getReturnType(), S, Extended);
5680 // Compute size of all parameters.
5681 // Start with computing size of a pointer in number of bytes.
5682 // FIXME: There might(should) be a better way of doing this computation!
5684 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5685 // The first two arguments (self and _cmd) are pointers; account for
5687 CharUnits ParmOffset = 2 * PtrSize;
5688 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5689 E = Decl->sel_param_end(); PI != E; ++PI) {
5690 QualType PType = (*PI)->getType();
5691 CharUnits sz = getObjCEncodingTypeSize(PType);
5695 assert (sz.isPositive() &&
5696 "getObjCEncodingForMethodDecl - Incomplete param type");
5699 S += charUnitsToString(ParmOffset);
5701 S += charUnitsToString(PtrSize);
5704 ParmOffset = 2 * PtrSize;
5705 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5706 E = Decl->sel_param_end(); PI != E; ++PI) {
5707 const ParmVarDecl *PVDecl = *PI;
5708 QualType PType = PVDecl->getOriginalType();
5709 if (const ArrayType *AT =
5710 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5711 // Use array's original type only if it has known number of
5713 if (!isa<ConstantArrayType>(AT))
5714 PType = PVDecl->getType();
5715 } else if (PType->isFunctionType())
5716 PType = PVDecl->getType();
5717 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5718 PType, S, Extended);
5719 S += charUnitsToString(ParmOffset);
5720 ParmOffset += getObjCEncodingTypeSize(PType);
5726 ObjCPropertyImplDecl *
5727 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5728 const ObjCPropertyDecl *PD,
5729 const Decl *Container) const {
5732 if (const ObjCCategoryImplDecl *CID =
5733 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5734 for (auto *PID : CID->property_impls())
5735 if (PID->getPropertyDecl() == PD)
5738 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5739 for (auto *PID : OID->property_impls())
5740 if (PID->getPropertyDecl() == PD)
5746 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5747 /// property declaration. If non-NULL, Container must be either an
5748 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5749 /// NULL when getting encodings for protocol properties.
5750 /// Property attributes are stored as a comma-delimited C string. The simple
5751 /// attributes readonly and bycopy are encoded as single characters. The
5752 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5753 /// encoded as single characters, followed by an identifier. Property types
5754 /// are also encoded as a parametrized attribute. The characters used to encode
5755 /// these attributes are defined by the following enumeration:
5757 /// enum PropertyAttributes {
5758 /// kPropertyReadOnly = 'R', // property is read-only.
5759 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5760 /// kPropertyByref = '&', // property is a reference to the value last assigned
5761 /// kPropertyDynamic = 'D', // property is dynamic
5762 /// kPropertyGetter = 'G', // followed by getter selector name
5763 /// kPropertySetter = 'S', // followed by setter selector name
5764 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5765 /// kPropertyType = 'T' // followed by old-style type encoding.
5766 /// kPropertyWeak = 'W' // 'weak' property
5767 /// kPropertyStrong = 'P' // property GC'able
5768 /// kPropertyNonAtomic = 'N' // property non-atomic
5772 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5773 const Decl *Container) const {
5774 // Collect information from the property implementation decl(s).
5775 bool Dynamic = false;
5776 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5778 if (ObjCPropertyImplDecl *PropertyImpDecl =
5779 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5780 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5783 SynthesizePID = PropertyImpDecl;
5786 // FIXME: This is not very efficient.
5787 std::string S = "T";
5789 // Encode result type.
5790 // GCC has some special rules regarding encoding of properties which
5791 // closely resembles encoding of ivars.
5792 getObjCEncodingForPropertyType(PD->getType(), S);
5794 if (PD->isReadOnly()) {
5796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5798 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5800 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5803 switch (PD->getSetterKind()) {
5804 case ObjCPropertyDecl::Assign: break;
5805 case ObjCPropertyDecl::Copy: S += ",C"; break;
5806 case ObjCPropertyDecl::Retain: S += ",&"; break;
5807 case ObjCPropertyDecl::Weak: S += ",W"; break;
5811 // It really isn't clear at all what this means, since properties
5812 // are "dynamic by default".
5816 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5819 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5821 S += PD->getGetterName().getAsString();
5824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5826 S += PD->getSetterName().getAsString();
5829 if (SynthesizePID) {
5830 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5832 S += OID->getNameAsString();
5835 // FIXME: OBJCGC: weak & strong
5839 /// getLegacyIntegralTypeEncoding -
5840 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5841 /// 'l' or 'L' , but not always. For typedefs, we need to use
5842 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5844 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5845 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5846 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5847 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5848 PointeeTy = UnsignedIntTy;
5850 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5856 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5857 const FieldDecl *Field,
5858 QualType *NotEncodedT) const {
5859 // We follow the behavior of gcc, expanding structures which are
5860 // directly pointed to, and expanding embedded structures. Note that
5861 // these rules are sufficient to prevent recursive encoding of the
5863 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5864 true /* outermost type */, false, false,
5865 false, false, false, NotEncodedT);
5868 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5869 std::string& S) const {
5870 // Encode result type.
5871 // GCC has some special rules regarding encoding of properties which
5872 // closely resembles encoding of ivars.
5873 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5874 true /* outermost type */,
5875 true /* encoding property */);
5878 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5879 BuiltinType::Kind kind) {
5881 case BuiltinType::Void: return 'v';
5882 case BuiltinType::Bool: return 'B';
5883 case BuiltinType::Char_U:
5884 case BuiltinType::UChar: return 'C';
5885 case BuiltinType::Char16:
5886 case BuiltinType::UShort: return 'S';
5887 case BuiltinType::Char32:
5888 case BuiltinType::UInt: return 'I';
5889 case BuiltinType::ULong:
5890 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5891 case BuiltinType::UInt128: return 'T';
5892 case BuiltinType::ULongLong: return 'Q';
5893 case BuiltinType::Char_S:
5894 case BuiltinType::SChar: return 'c';
5895 case BuiltinType::Short: return 's';
5896 case BuiltinType::WChar_S:
5897 case BuiltinType::WChar_U:
5898 case BuiltinType::Int: return 'i';
5899 case BuiltinType::Long:
5900 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5901 case BuiltinType::LongLong: return 'q';
5902 case BuiltinType::Int128: return 't';
5903 case BuiltinType::Float: return 'f';
5904 case BuiltinType::Double: return 'd';
5905 case BuiltinType::LongDouble: return 'D';
5906 case BuiltinType::NullPtr: return '*'; // like char*
5908 case BuiltinType::Float128:
5909 case BuiltinType::Half:
5910 // FIXME: potentially need @encodes for these!
5913 case BuiltinType::ObjCId:
5914 case BuiltinType::ObjCClass:
5915 case BuiltinType::ObjCSel:
5916 llvm_unreachable("@encoding ObjC primitive type");
5918 // OpenCL and placeholder types don't need @encodings.
5919 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5920 case BuiltinType::Id:
5921 #include "clang/Basic/OpenCLImageTypes.def"
5922 case BuiltinType::OCLEvent:
5923 case BuiltinType::OCLClkEvent:
5924 case BuiltinType::OCLQueue:
5925 case BuiltinType::OCLNDRange:
5926 case BuiltinType::OCLReserveID:
5927 case BuiltinType::OCLSampler:
5928 case BuiltinType::Dependent:
5929 #define BUILTIN_TYPE(KIND, ID)
5930 #define PLACEHOLDER_TYPE(KIND, ID) \
5931 case BuiltinType::KIND:
5932 #include "clang/AST/BuiltinTypes.def"
5933 llvm_unreachable("invalid builtin type for @encode");
5935 llvm_unreachable("invalid BuiltinType::Kind value");
5938 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5939 EnumDecl *Enum = ET->getDecl();
5941 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5942 if (!Enum->isFixed())
5945 // The encoding of a fixed enum type matches its fixed underlying type.
5946 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5947 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5950 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5951 QualType T, const FieldDecl *FD) {
5952 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5954 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5955 // The GNU runtime requires more information; bitfields are encoded as b,
5956 // then the offset (in bits) of the first element, then the type of the
5957 // bitfield, then the size in bits. For example, in this structure:
5964 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5965 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5966 // information is not especially sensible, but we're stuck with it for
5967 // compatibility with GCC, although providing it breaks anything that
5968 // actually uses runtime introspection and wants to work on both runtimes...
5969 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5970 const RecordDecl *RD = FD->getParent();
5971 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5972 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5973 if (const EnumType *ET = T->getAs<EnumType>())
5974 S += ObjCEncodingForEnumType(Ctx, ET);
5976 const BuiltinType *BT = T->castAs<BuiltinType>();
5977 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5980 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5983 // FIXME: Use SmallString for accumulating string.
5984 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5985 bool ExpandPointedToStructures,
5986 bool ExpandStructures,
5987 const FieldDecl *FD,
5989 bool EncodingProperty,
5991 bool EncodeBlockParameters,
5992 bool EncodeClassNames,
5993 bool EncodePointerToObjCTypedef,
5994 QualType *NotEncodedT) const {
5995 CanQualType CT = getCanonicalType(T);
5996 switch (CT->getTypeClass()) {
5999 if (FD && FD->isBitField())
6000 return EncodeBitField(this, S, T, FD);
6001 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6002 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6004 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6007 case Type::Complex: {
6008 const ComplexType *CT = T->castAs<ComplexType>();
6010 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6014 case Type::Atomic: {
6015 const AtomicType *AT = T->castAs<AtomicType>();
6017 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6021 // encoding for pointer or reference types.
6023 case Type::LValueReference:
6024 case Type::RValueReference: {
6026 if (isa<PointerType>(CT)) {
6027 const PointerType *PT = T->castAs<PointerType>();
6028 if (PT->isObjCSelType()) {
6032 PointeeTy = PT->getPointeeType();
6034 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6037 bool isReadOnly = false;
6038 // For historical/compatibility reasons, the read-only qualifier of the
6039 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6040 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6041 // Also, do not emit the 'r' for anything but the outermost type!
6042 if (isa<TypedefType>(T.getTypePtr())) {
6043 if (OutermostType && T.isConstQualified()) {
6047 } else if (OutermostType) {
6048 QualType P = PointeeTy;
6049 while (P->getAs<PointerType>())
6050 P = P->getAs<PointerType>()->getPointeeType();
6051 if (P.isConstQualified()) {
6057 // Another legacy compatibility encoding. Some ObjC qualifier and type
6058 // combinations need to be rearranged.
6059 // Rewrite "in const" from "nr" to "rn"
6060 if (StringRef(S).endswith("nr"))
6061 S.replace(S.end()-2, S.end(), "rn");
6064 if (PointeeTy->isCharType()) {
6065 // char pointer types should be encoded as '*' unless it is a
6066 // type that has been typedef'd to 'BOOL'.
6067 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6071 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
6072 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6073 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6077 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6078 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6085 getLegacyIntegralTypeEncoding(PointeeTy);
6087 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6088 nullptr, false, false, false, false, false, false,
6093 case Type::ConstantArray:
6094 case Type::IncompleteArray:
6095 case Type::VariableArray: {
6096 const ArrayType *AT = cast<ArrayType>(CT);
6098 if (isa<IncompleteArrayType>(AT) && !StructField) {
6099 // Incomplete arrays are encoded as a pointer to the array element.
6102 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6103 false, ExpandStructures, FD);
6107 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6108 S += llvm::utostr(CAT->getSize().getZExtValue());
6110 //Variable length arrays are encoded as a regular array with 0 elements.
6111 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6112 "Unknown array type!");
6116 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6117 false, ExpandStructures, FD,
6118 false, false, false, false, false, false,
6125 case Type::FunctionNoProto:
6126 case Type::FunctionProto:
6130 case Type::Record: {
6131 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6132 S += RDecl->isUnion() ? '(' : '{';
6133 // Anonymous structures print as '?'
6134 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6136 if (ClassTemplateSpecializationDecl *Spec
6137 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6138 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6139 llvm::raw_string_ostream OS(S);
6140 TemplateSpecializationType::PrintTemplateArgumentList(OS,
6141 TemplateArgs.asArray(),
6142 (*this).getPrintingPolicy());
6147 if (ExpandStructures) {
6149 if (!RDecl->isUnion()) {
6150 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6152 for (const auto *Field : RDecl->fields()) {
6155 S += Field->getNameAsString();
6159 // Special case bit-fields.
6160 if (Field->isBitField()) {
6161 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6164 QualType qt = Field->getType();
6165 getLegacyIntegralTypeEncoding(qt);
6166 getObjCEncodingForTypeImpl(qt, S, false, true,
6167 FD, /*OutermostType*/false,
6168 /*EncodingProperty*/false,
6169 /*StructField*/true,
6170 false, false, false, NotEncodedT);
6175 S += RDecl->isUnion() ? ')' : '}';
6179 case Type::BlockPointer: {
6180 const BlockPointerType *BT = T->castAs<BlockPointerType>();
6181 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6182 if (EncodeBlockParameters) {
6183 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
6186 // Block return type
6187 getObjCEncodingForTypeImpl(
6188 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6189 FD, false /* OutermostType */, EncodingProperty,
6190 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6195 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
6196 for (const auto &I : FPT->param_types())
6197 getObjCEncodingForTypeImpl(
6198 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6199 false /* OutermostType */, EncodingProperty,
6200 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6201 false, NotEncodedT);
6208 case Type::ObjCObject: {
6209 // hack to match legacy encoding of *id and *Class
6210 QualType Ty = getObjCObjectPointerType(CT);
6211 if (Ty->isObjCIdType()) {
6212 S += "{objc_object=}";
6215 else if (Ty->isObjCClassType()) {
6216 S += "{objc_class=}";
6221 case Type::ObjCInterface: {
6222 // Ignore protocol qualifiers when mangling at this level.
6223 // @encode(class_name)
6224 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6226 S += OI->getObjCRuntimeNameAsString();
6227 if (ExpandStructures) {
6229 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6230 DeepCollectObjCIvars(OI, true, Ivars);
6231 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6232 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6233 if (Field->isBitField())
6234 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6236 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6237 false, false, false, false, false,
6238 EncodePointerToObjCTypedef,
6246 case Type::ObjCObjectPointer: {
6247 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
6248 if (OPT->isObjCIdType()) {
6253 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6254 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6255 // Since this is a binary compatibility issue, need to consult with runtime
6256 // folks. Fortunately, this is a *very* obsure construct.
6261 if (OPT->isObjCQualifiedIdType()) {
6262 getObjCEncodingForTypeImpl(getObjCIdType(), S,
6263 ExpandPointedToStructures,
6264 ExpandStructures, FD);
6265 if (FD || EncodingProperty || EncodeClassNames) {
6266 // Note that we do extended encoding of protocol qualifer list
6267 // Only when doing ivar or property encoding.
6269 for (const auto *I : OPT->quals()) {
6271 S += I->getObjCRuntimeNameAsString();
6279 QualType PointeeTy = OPT->getPointeeType();
6280 if (!EncodingProperty &&
6281 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6282 !EncodePointerToObjCTypedef) {
6283 // Another historical/compatibility reason.
6284 // We encode the underlying type which comes out as
6287 if (FD && OPT->getInterfaceDecl()) {
6288 // Prevent recursive encoding of fields in some rare cases.
6289 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6290 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6291 DeepCollectObjCIvars(OI, true, Ivars);
6292 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6293 if (cast<FieldDecl>(Ivars[i]) == FD) {
6295 S += OI->getObjCRuntimeNameAsString();
6301 getObjCEncodingForTypeImpl(PointeeTy, S,
6302 false, ExpandPointedToStructures,
6304 false, false, false, false, false,
6305 /*EncodePointerToObjCTypedef*/true);
6310 if (OPT->getInterfaceDecl() &&
6311 (FD || EncodingProperty || EncodeClassNames)) {
6313 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6314 for (const auto *I : OPT->quals()) {
6316 S += I->getObjCRuntimeNameAsString();
6324 // gcc just blithely ignores member pointers.
6325 // FIXME: we shoul do better than that. 'M' is available.
6326 case Type::MemberPointer:
6327 // This matches gcc's encoding, even though technically it is insufficient.
6328 //FIXME. We should do a better job than gcc.
6330 case Type::ExtVector:
6331 // Until we have a coherent encoding of these three types, issue warning.
6337 // We could see an undeduced auto type here during error recovery.
6343 #define ABSTRACT_TYPE(KIND, BASE)
6344 #define TYPE(KIND, BASE)
6345 #define DEPENDENT_TYPE(KIND, BASE) \
6347 #define NON_CANONICAL_TYPE(KIND, BASE) \
6349 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6351 #include "clang/AST/TypeNodes.def"
6352 llvm_unreachable("@encode for dependent type!");
6354 llvm_unreachable("bad type kind!");
6357 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6359 const FieldDecl *FD,
6361 QualType *NotEncodedT) const {
6362 assert(RDecl && "Expected non-null RecordDecl");
6363 assert(!RDecl->isUnion() && "Should not be called for unions");
6364 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6367 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6368 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6369 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6372 for (const auto &BI : CXXRec->bases()) {
6373 if (!BI.isVirtual()) {
6374 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6375 if (base->isEmpty())
6377 uint64_t offs = toBits(layout.getBaseClassOffset(base));
6378 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6379 std::make_pair(offs, base));
6385 for (auto *Field : RDecl->fields()) {
6386 uint64_t offs = layout.getFieldOffset(i);
6387 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6388 std::make_pair(offs, Field));
6392 if (CXXRec && includeVBases) {
6393 for (const auto &BI : CXXRec->vbases()) {
6394 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6395 if (base->isEmpty())
6397 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6398 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6399 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6400 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6401 std::make_pair(offs, base));
6407 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6409 size = layout.getSize();
6413 uint64_t CurOffs = 0;
6415 std::multimap<uint64_t, NamedDecl *>::iterator
6416 CurLayObj = FieldOrBaseOffsets.begin();
6418 if (CXXRec && CXXRec->isDynamicClass() &&
6419 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6422 std::string recname = CXXRec->getNameAsString();
6423 if (recname.empty()) recname = "?";
6429 CurOffs += getTypeSize(VoidPtrTy);
6433 if (!RDecl->hasFlexibleArrayMember()) {
6434 // Mark the end of the structure.
6435 uint64_t offs = toBits(size);
6436 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6437 std::make_pair(offs, nullptr));
6440 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6442 assert(CurOffs <= CurLayObj->first);
6443 if (CurOffs < CurLayObj->first) {
6444 uint64_t padding = CurLayObj->first - CurOffs;
6445 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6446 // packing/alignment of members is different that normal, in which case
6447 // the encoding will be out-of-sync with the real layout.
6448 // If the runtime switches to just consider the size of types without
6449 // taking into account alignment, we could make padding explicit in the
6450 // encoding (e.g. using arrays of chars). The encoding strings would be
6451 // longer then though.
6456 NamedDecl *dcl = CurLayObj->second;
6458 break; // reached end of structure.
6460 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6461 // We expand the bases without their virtual bases since those are going
6462 // in the initial structure. Note that this differs from gcc which
6463 // expands virtual bases each time one is encountered in the hierarchy,
6464 // making the encoding type bigger than it really is.
6465 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6467 assert(!base->isEmpty());
6469 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6472 FieldDecl *field = cast<FieldDecl>(dcl);
6475 S += field->getNameAsString();
6479 if (field->isBitField()) {
6480 EncodeBitField(this, S, field->getType(), field);
6482 CurOffs += field->getBitWidthValue(*this);
6485 QualType qt = field->getType();
6486 getLegacyIntegralTypeEncoding(qt);
6487 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6488 /*OutermostType*/false,
6489 /*EncodingProperty*/false,
6490 /*StructField*/true,
6491 false, false, false, NotEncodedT);
6493 CurOffs += getTypeSize(field->getType());
6500 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6501 std::string& S) const {
6502 if (QT & Decl::OBJC_TQ_In)
6504 if (QT & Decl::OBJC_TQ_Inout)
6506 if (QT & Decl::OBJC_TQ_Out)
6508 if (QT & Decl::OBJC_TQ_Bycopy)
6510 if (QT & Decl::OBJC_TQ_Byref)
6512 if (QT & Decl::OBJC_TQ_Oneway)
6516 TypedefDecl *ASTContext::getObjCIdDecl() const {
6518 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6519 T = getObjCObjectPointerType(T);
6520 ObjCIdDecl = buildImplicitTypedef(T, "id");
6525 TypedefDecl *ASTContext::getObjCSelDecl() const {
6527 QualType T = getPointerType(ObjCBuiltinSelTy);
6528 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6533 TypedefDecl *ASTContext::getObjCClassDecl() const {
6534 if (!ObjCClassDecl) {
6535 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6536 T = getObjCObjectPointerType(T);
6537 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6539 return ObjCClassDecl;
6542 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6543 if (!ObjCProtocolClassDecl) {
6544 ObjCProtocolClassDecl
6545 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6547 &Idents.get("Protocol"),
6548 /*typeParamList=*/nullptr,
6549 /*PrevDecl=*/nullptr,
6550 SourceLocation(), true);
6553 return ObjCProtocolClassDecl;
6556 //===----------------------------------------------------------------------===//
6557 // __builtin_va_list Construction Functions
6558 //===----------------------------------------------------------------------===//
6560 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6562 // typedef char* __builtin[_ms]_va_list;
6563 QualType T = Context->getPointerType(Context->CharTy);
6564 return Context->buildImplicitTypedef(T, Name);
6567 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6568 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6571 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6572 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6575 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6576 // typedef void* __builtin_va_list;
6577 QualType T = Context->getPointerType(Context->VoidTy);
6578 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6581 static TypedefDecl *
6582 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6584 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6585 if (Context->getLangOpts().CPlusPlus) {
6586 // namespace std { struct __va_list {
6588 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6589 Context->getTranslationUnitDecl(),
6590 /*Inline*/ false, SourceLocation(),
6591 SourceLocation(), &Context->Idents.get("std"),
6592 /*PrevDecl*/ nullptr);
6594 VaListTagDecl->setDeclContext(NS);
6597 VaListTagDecl->startDefinition();
6599 const size_t NumFields = 5;
6600 QualType FieldTypes[NumFields];
6601 const char *FieldNames[NumFields];
6604 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6605 FieldNames[0] = "__stack";
6608 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6609 FieldNames[1] = "__gr_top";
6612 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6613 FieldNames[2] = "__vr_top";
6616 FieldTypes[3] = Context->IntTy;
6617 FieldNames[3] = "__gr_offs";
6620 FieldTypes[4] = Context->IntTy;
6621 FieldNames[4] = "__vr_offs";
6624 for (unsigned i = 0; i < NumFields; ++i) {
6625 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6629 &Context->Idents.get(FieldNames[i]),
6630 FieldTypes[i], /*TInfo=*/nullptr,
6631 /*BitWidth=*/nullptr,
6634 Field->setAccess(AS_public);
6635 VaListTagDecl->addDecl(Field);
6637 VaListTagDecl->completeDefinition();
6638 Context->VaListTagDecl = VaListTagDecl;
6639 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6641 // } __builtin_va_list;
6642 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6645 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6646 // typedef struct __va_list_tag {
6647 RecordDecl *VaListTagDecl;
6649 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6650 VaListTagDecl->startDefinition();
6652 const size_t NumFields = 5;
6653 QualType FieldTypes[NumFields];
6654 const char *FieldNames[NumFields];
6656 // unsigned char gpr;
6657 FieldTypes[0] = Context->UnsignedCharTy;
6658 FieldNames[0] = "gpr";
6660 // unsigned char fpr;
6661 FieldTypes[1] = Context->UnsignedCharTy;
6662 FieldNames[1] = "fpr";
6664 // unsigned short reserved;
6665 FieldTypes[2] = Context->UnsignedShortTy;
6666 FieldNames[2] = "reserved";
6668 // void* overflow_arg_area;
6669 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6670 FieldNames[3] = "overflow_arg_area";
6672 // void* reg_save_area;
6673 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6674 FieldNames[4] = "reg_save_area";
6677 for (unsigned i = 0; i < NumFields; ++i) {
6678 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6681 &Context->Idents.get(FieldNames[i]),
6682 FieldTypes[i], /*TInfo=*/nullptr,
6683 /*BitWidth=*/nullptr,
6686 Field->setAccess(AS_public);
6687 VaListTagDecl->addDecl(Field);
6689 VaListTagDecl->completeDefinition();
6690 Context->VaListTagDecl = VaListTagDecl;
6691 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6694 TypedefDecl *VaListTagTypedefDecl =
6695 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6697 QualType VaListTagTypedefType =
6698 Context->getTypedefType(VaListTagTypedefDecl);
6700 // typedef __va_list_tag __builtin_va_list[1];
6701 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6702 QualType VaListTagArrayType
6703 = Context->getConstantArrayType(VaListTagTypedefType,
6704 Size, ArrayType::Normal, 0);
6705 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6708 static TypedefDecl *
6709 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6710 // struct __va_list_tag {
6711 RecordDecl *VaListTagDecl;
6712 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6713 VaListTagDecl->startDefinition();
6715 const size_t NumFields = 4;
6716 QualType FieldTypes[NumFields];
6717 const char *FieldNames[NumFields];
6719 // unsigned gp_offset;
6720 FieldTypes[0] = Context->UnsignedIntTy;
6721 FieldNames[0] = "gp_offset";
6723 // unsigned fp_offset;
6724 FieldTypes[1] = Context->UnsignedIntTy;
6725 FieldNames[1] = "fp_offset";
6727 // void* overflow_arg_area;
6728 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6729 FieldNames[2] = "overflow_arg_area";
6731 // void* reg_save_area;
6732 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6733 FieldNames[3] = "reg_save_area";
6736 for (unsigned i = 0; i < NumFields; ++i) {
6737 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6741 &Context->Idents.get(FieldNames[i]),
6742 FieldTypes[i], /*TInfo=*/nullptr,
6743 /*BitWidth=*/nullptr,
6746 Field->setAccess(AS_public);
6747 VaListTagDecl->addDecl(Field);
6749 VaListTagDecl->completeDefinition();
6750 Context->VaListTagDecl = VaListTagDecl;
6751 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6755 // typedef struct __va_list_tag __builtin_va_list[1];
6756 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6757 QualType VaListTagArrayType =
6758 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6759 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6762 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6763 // typedef int __builtin_va_list[4];
6764 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6765 QualType IntArrayType =
6766 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
6767 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6770 static TypedefDecl *
6771 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6773 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6774 if (Context->getLangOpts().CPlusPlus) {
6775 // namespace std { struct __va_list {
6777 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6778 Context->getTranslationUnitDecl(),
6779 /*Inline*/false, SourceLocation(),
6780 SourceLocation(), &Context->Idents.get("std"),
6781 /*PrevDecl*/ nullptr);
6783 VaListDecl->setDeclContext(NS);
6786 VaListDecl->startDefinition();
6789 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6793 &Context->Idents.get("__ap"),
6794 Context->getPointerType(Context->VoidTy),
6796 /*BitWidth=*/nullptr,
6799 Field->setAccess(AS_public);
6800 VaListDecl->addDecl(Field);
6803 VaListDecl->completeDefinition();
6804 Context->VaListTagDecl = VaListDecl;
6806 // typedef struct __va_list __builtin_va_list;
6807 QualType T = Context->getRecordType(VaListDecl);
6808 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6811 static TypedefDecl *
6812 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6813 // struct __va_list_tag {
6814 RecordDecl *VaListTagDecl;
6815 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6816 VaListTagDecl->startDefinition();
6818 const size_t NumFields = 4;
6819 QualType FieldTypes[NumFields];
6820 const char *FieldNames[NumFields];
6823 FieldTypes[0] = Context->LongTy;
6824 FieldNames[0] = "__gpr";
6827 FieldTypes[1] = Context->LongTy;
6828 FieldNames[1] = "__fpr";
6830 // void *__overflow_arg_area;
6831 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6832 FieldNames[2] = "__overflow_arg_area";
6834 // void *__reg_save_area;
6835 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6836 FieldNames[3] = "__reg_save_area";
6839 for (unsigned i = 0; i < NumFields; ++i) {
6840 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6844 &Context->Idents.get(FieldNames[i]),
6845 FieldTypes[i], /*TInfo=*/nullptr,
6846 /*BitWidth=*/nullptr,
6849 Field->setAccess(AS_public);
6850 VaListTagDecl->addDecl(Field);
6852 VaListTagDecl->completeDefinition();
6853 Context->VaListTagDecl = VaListTagDecl;
6854 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6858 // typedef __va_list_tag __builtin_va_list[1];
6859 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6860 QualType VaListTagArrayType =
6861 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6863 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6866 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6867 TargetInfo::BuiltinVaListKind Kind) {
6869 case TargetInfo::CharPtrBuiltinVaList:
6870 return CreateCharPtrBuiltinVaListDecl(Context);
6871 case TargetInfo::VoidPtrBuiltinVaList:
6872 return CreateVoidPtrBuiltinVaListDecl(Context);
6873 case TargetInfo::AArch64ABIBuiltinVaList:
6874 return CreateAArch64ABIBuiltinVaListDecl(Context);
6875 case TargetInfo::PowerABIBuiltinVaList:
6876 return CreatePowerABIBuiltinVaListDecl(Context);
6877 case TargetInfo::X86_64ABIBuiltinVaList:
6878 return CreateX86_64ABIBuiltinVaListDecl(Context);
6879 case TargetInfo::PNaClABIBuiltinVaList:
6880 return CreatePNaClABIBuiltinVaListDecl(Context);
6881 case TargetInfo::AAPCSABIBuiltinVaList:
6882 return CreateAAPCSABIBuiltinVaListDecl(Context);
6883 case TargetInfo::SystemZBuiltinVaList:
6884 return CreateSystemZBuiltinVaListDecl(Context);
6887 llvm_unreachable("Unhandled __builtin_va_list type kind");
6890 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6891 if (!BuiltinVaListDecl) {
6892 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6893 assert(BuiltinVaListDecl->isImplicit());
6896 return BuiltinVaListDecl;
6899 Decl *ASTContext::getVaListTagDecl() const {
6900 // Force the creation of VaListTagDecl by building the __builtin_va_list
6903 (void)getBuiltinVaListDecl();
6905 return VaListTagDecl;
6908 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6909 if (!BuiltinMSVaListDecl)
6910 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6912 return BuiltinMSVaListDecl;
6915 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6916 assert(ObjCConstantStringType.isNull() &&
6917 "'NSConstantString' type already set!");
6919 ObjCConstantStringType = getObjCInterfaceType(Decl);
6922 /// \brief Retrieve the template name that corresponds to a non-empty
6925 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6926 UnresolvedSetIterator End) const {
6927 unsigned size = End - Begin;
6928 assert(size > 1 && "set is not overloaded!");
6930 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6931 size * sizeof(FunctionTemplateDecl*));
6932 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6934 NamedDecl **Storage = OT->getStorage();
6935 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6937 assert(isa<FunctionTemplateDecl>(D) ||
6938 (isa<UsingShadowDecl>(D) &&
6939 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6943 return TemplateName(OT);
6946 /// \brief Retrieve the template name that represents a qualified
6947 /// template name such as \c std::vector.
6949 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6950 bool TemplateKeyword,
6951 TemplateDecl *Template) const {
6952 assert(NNS && "Missing nested-name-specifier in qualified template name");
6954 // FIXME: Canonicalization?
6955 llvm::FoldingSetNodeID ID;
6956 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6958 void *InsertPos = nullptr;
6959 QualifiedTemplateName *QTN =
6960 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6962 QTN = new (*this, alignof(QualifiedTemplateName))
6963 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6964 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6967 return TemplateName(QTN);
6970 /// \brief Retrieve the template name that represents a dependent
6971 /// template name such as \c MetaFun::template apply.
6973 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6974 const IdentifierInfo *Name) const {
6975 assert((!NNS || NNS->isDependent()) &&
6976 "Nested name specifier must be dependent");
6978 llvm::FoldingSetNodeID ID;
6979 DependentTemplateName::Profile(ID, NNS, Name);
6981 void *InsertPos = nullptr;
6982 DependentTemplateName *QTN =
6983 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6986 return TemplateName(QTN);
6988 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6989 if (CanonNNS == NNS) {
6990 QTN = new (*this, alignof(DependentTemplateName))
6991 DependentTemplateName(NNS, Name);
6993 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6994 QTN = new (*this, alignof(DependentTemplateName))
6995 DependentTemplateName(NNS, Name, Canon);
6996 DependentTemplateName *CheckQTN =
6997 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6998 assert(!CheckQTN && "Dependent type name canonicalization broken");
7002 DependentTemplateNames.InsertNode(QTN, InsertPos);
7003 return TemplateName(QTN);
7006 /// \brief Retrieve the template name that represents a dependent
7007 /// template name such as \c MetaFun::template operator+.
7009 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7010 OverloadedOperatorKind Operator) const {
7011 assert((!NNS || NNS->isDependent()) &&
7012 "Nested name specifier must be dependent");
7014 llvm::FoldingSetNodeID ID;
7015 DependentTemplateName::Profile(ID, NNS, Operator);
7017 void *InsertPos = nullptr;
7018 DependentTemplateName *QTN
7019 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7022 return TemplateName(QTN);
7024 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7025 if (CanonNNS == NNS) {
7026 QTN = new (*this, alignof(DependentTemplateName))
7027 DependentTemplateName(NNS, Operator);
7029 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7030 QTN = new (*this, alignof(DependentTemplateName))
7031 DependentTemplateName(NNS, Operator, Canon);
7033 DependentTemplateName *CheckQTN
7034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7035 assert(!CheckQTN && "Dependent template name canonicalization broken");
7039 DependentTemplateNames.InsertNode(QTN, InsertPos);
7040 return TemplateName(QTN);
7044 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7045 TemplateName replacement) const {
7046 llvm::FoldingSetNodeID ID;
7047 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7049 void *insertPos = nullptr;
7050 SubstTemplateTemplateParmStorage *subst
7051 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7054 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7055 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7058 return TemplateName(subst);
7062 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7063 const TemplateArgument &ArgPack) const {
7064 ASTContext &Self = const_cast<ASTContext &>(*this);
7065 llvm::FoldingSetNodeID ID;
7066 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7068 void *InsertPos = nullptr;
7069 SubstTemplateTemplateParmPackStorage *Subst
7070 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7073 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7074 ArgPack.pack_size(),
7075 ArgPack.pack_begin());
7076 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7079 return TemplateName(Subst);
7082 /// getFromTargetType - Given one of the integer types provided by
7083 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7084 /// is actually a value of type @c TargetInfo::IntType.
7085 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7087 case TargetInfo::NoInt: return CanQualType();
7088 case TargetInfo::SignedChar: return SignedCharTy;
7089 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7090 case TargetInfo::SignedShort: return ShortTy;
7091 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7092 case TargetInfo::SignedInt: return IntTy;
7093 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7094 case TargetInfo::SignedLong: return LongTy;
7095 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7096 case TargetInfo::SignedLongLong: return LongLongTy;
7097 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7100 llvm_unreachable("Unhandled TargetInfo::IntType value");
7103 //===----------------------------------------------------------------------===//
7105 //===----------------------------------------------------------------------===//
7107 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7108 /// garbage collection attribute.
7110 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7111 if (getLangOpts().getGC() == LangOptions::NonGC)
7112 return Qualifiers::GCNone;
7114 assert(getLangOpts().ObjC1);
7115 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7117 // Default behaviour under objective-C's gc is for ObjC pointers
7118 // (or pointers to them) be treated as though they were declared
7120 if (GCAttrs == Qualifiers::GCNone) {
7121 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7122 return Qualifiers::Strong;
7123 else if (Ty->isPointerType())
7124 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7126 // It's not valid to set GC attributes on anything that isn't a
7129 QualType CT = Ty->getCanonicalTypeInternal();
7130 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7131 CT = AT->getElementType();
7132 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7138 //===----------------------------------------------------------------------===//
7139 // Type Compatibility Testing
7140 //===----------------------------------------------------------------------===//
7142 /// areCompatVectorTypes - Return true if the two specified vector types are
7144 static bool areCompatVectorTypes(const VectorType *LHS,
7145 const VectorType *RHS) {
7146 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7147 return LHS->getElementType() == RHS->getElementType() &&
7148 LHS->getNumElements() == RHS->getNumElements();
7151 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7152 QualType SecondVec) {
7153 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7154 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7156 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7159 // Treat Neon vector types and most AltiVec vector types as if they are the
7160 // equivalent GCC vector types.
7161 const VectorType *First = FirstVec->getAs<VectorType>();
7162 const VectorType *Second = SecondVec->getAs<VectorType>();
7163 if (First->getNumElements() == Second->getNumElements() &&
7164 hasSameType(First->getElementType(), Second->getElementType()) &&
7165 First->getVectorKind() != VectorType::AltiVecPixel &&
7166 First->getVectorKind() != VectorType::AltiVecBool &&
7167 Second->getVectorKind() != VectorType::AltiVecPixel &&
7168 Second->getVectorKind() != VectorType::AltiVecBool)
7174 //===----------------------------------------------------------------------===//
7175 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7176 //===----------------------------------------------------------------------===//
7178 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7179 /// inheritance hierarchy of 'rProto'.
7181 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7182 ObjCProtocolDecl *rProto) const {
7183 if (declaresSameEntity(lProto, rProto))
7185 for (auto *PI : rProto->protocols())
7186 if (ProtocolCompatibleWithProtocol(lProto, PI))
7191 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7192 /// Class<pr1, ...>.
7193 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7195 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7196 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7197 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7199 for (auto *lhsProto : lhsQID->quals()) {
7201 for (auto *rhsProto : rhsOPT->quals()) {
7202 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7213 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7214 /// ObjCQualifiedIDType.
7215 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7217 // Allow id<P..> and an 'id' or void* type in all cases.
7218 if (lhs->isVoidPointerType() ||
7219 lhs->isObjCIdType() || lhs->isObjCClassType())
7221 else if (rhs->isVoidPointerType() ||
7222 rhs->isObjCIdType() || rhs->isObjCClassType())
7225 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7226 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7228 if (!rhsOPT) return false;
7230 if (rhsOPT->qual_empty()) {
7231 // If the RHS is a unqualified interface pointer "NSString*",
7232 // make sure we check the class hierarchy.
7233 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7234 for (auto *I : lhsQID->quals()) {
7235 // when comparing an id<P> on lhs with a static type on rhs,
7236 // see if static class implements all of id's protocols, directly or
7237 // through its super class and categories.
7238 if (!rhsID->ClassImplementsProtocol(I, true))
7242 // If there are no qualifiers and no interface, we have an 'id'.
7245 // Both the right and left sides have qualifiers.
7246 for (auto *lhsProto : lhsQID->quals()) {
7249 // when comparing an id<P> on lhs with a static type on rhs,
7250 // see if static class implements all of id's protocols, directly or
7251 // through its super class and categories.
7252 for (auto *rhsProto : rhsOPT->quals()) {
7253 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7254 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7259 // If the RHS is a qualified interface pointer "NSString<P>*",
7260 // make sure we check the class hierarchy.
7261 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7262 for (auto *I : lhsQID->quals()) {
7263 // when comparing an id<P> on lhs with a static type on rhs,
7264 // see if static class implements all of id's protocols, directly or
7265 // through its super class and categories.
7266 if (rhsID->ClassImplementsProtocol(I, true)) {
7279 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7280 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7282 if (const ObjCObjectPointerType *lhsOPT =
7283 lhs->getAsObjCInterfacePointerType()) {
7284 // If both the right and left sides have qualifiers.
7285 for (auto *lhsProto : lhsOPT->quals()) {
7288 // when comparing an id<P> on rhs with a static type on lhs,
7289 // see if static class implements all of id's protocols, directly or
7290 // through its super class and categories.
7291 // First, lhs protocols in the qualifier list must be found, direct
7292 // or indirect in rhs's qualifier list or it is a mismatch.
7293 for (auto *rhsProto : rhsQID->quals()) {
7294 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7295 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7304 // Static class's protocols, or its super class or category protocols
7305 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7306 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7307 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7308 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7309 // This is rather dubious but matches gcc's behavior. If lhs has
7310 // no type qualifier and its class has no static protocol(s)
7311 // assume that it is mismatch.
7312 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7314 for (auto *lhsProto : LHSInheritedProtocols) {
7316 for (auto *rhsProto : rhsQID->quals()) {
7317 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7318 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7332 /// canAssignObjCInterfaces - Return true if the two interface types are
7333 /// compatible for assignment from RHS to LHS. This handles validation of any
7334 /// protocol qualifiers on the LHS or RHS.
7336 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7337 const ObjCObjectPointerType *RHSOPT) {
7338 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7339 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7341 // If either type represents the built-in 'id' or 'Class' types, return true.
7342 if (LHS->isObjCUnqualifiedIdOrClass() ||
7343 RHS->isObjCUnqualifiedIdOrClass())
7346 // Function object that propagates a successful result or handles
7348 auto finish = [&](bool succeeded) -> bool {
7352 if (!RHS->isKindOfType())
7355 // Strip off __kindof and protocol qualifiers, then check whether
7356 // we can assign the other way.
7357 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7358 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7361 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7362 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7367 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7368 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7369 QualType(RHSOPT,0)));
7372 // If we have 2 user-defined types, fall into that path.
7373 if (LHS->getInterface() && RHS->getInterface()) {
7374 return finish(canAssignObjCInterfaces(LHS, RHS));
7380 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7381 /// for providing type-safety for objective-c pointers used to pass/return
7382 /// arguments in block literals. When passed as arguments, passing 'A*' where
7383 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7384 /// not OK. For the return type, the opposite is not OK.
7385 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7386 const ObjCObjectPointerType *LHSOPT,
7387 const ObjCObjectPointerType *RHSOPT,
7388 bool BlockReturnType) {
7390 // Function object that propagates a successful result or handles
7392 auto finish = [&](bool succeeded) -> bool {
7396 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7397 if (!Expected->isKindOfType())
7400 // Strip off __kindof and protocol qualifiers, then check whether
7401 // we can assign the other way.
7402 return canAssignObjCInterfacesInBlockPointer(
7403 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7404 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7408 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7411 if (LHSOPT->isObjCBuiltinType()) {
7412 return finish(RHSOPT->isObjCBuiltinType() ||
7413 RHSOPT->isObjCQualifiedIdType());
7416 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7417 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7421 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7422 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7423 if (LHS && RHS) { // We have 2 user-defined types.
7425 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7426 return finish(BlockReturnType);
7427 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7428 return finish(!BlockReturnType);
7436 /// Comparison routine for Objective-C protocols to be used with
7437 /// llvm::array_pod_sort.
7438 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7439 ObjCProtocolDecl * const *rhs) {
7440 return (*lhs)->getName().compare((*rhs)->getName());
7444 /// getIntersectionOfProtocols - This routine finds the intersection of set
7445 /// of protocols inherited from two distinct objective-c pointer objects with
7446 /// the given common base.
7447 /// It is used to build composite qualifier list of the composite type of
7448 /// the conditional expression involving two objective-c pointer objects.
7450 void getIntersectionOfProtocols(ASTContext &Context,
7451 const ObjCInterfaceDecl *CommonBase,
7452 const ObjCObjectPointerType *LHSOPT,
7453 const ObjCObjectPointerType *RHSOPT,
7454 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7456 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7457 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7458 assert(LHS->getInterface() && "LHS must have an interface base");
7459 assert(RHS->getInterface() && "RHS must have an interface base");
7461 // Add all of the protocols for the LHS.
7462 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7464 // Start with the protocol qualifiers.
7465 for (auto proto : LHS->quals()) {
7466 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7469 // Also add the protocols associated with the LHS interface.
7470 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7472 // Add all of the protocls for the RHS.
7473 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7475 // Start with the protocol qualifiers.
7476 for (auto proto : RHS->quals()) {
7477 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7480 // Also add the protocols associated with the RHS interface.
7481 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7483 // Compute the intersection of the collected protocol sets.
7484 for (auto proto : LHSProtocolSet) {
7485 if (RHSProtocolSet.count(proto))
7486 IntersectionSet.push_back(proto);
7489 // Compute the set of protocols that is implied by either the common type or
7490 // the protocols within the intersection.
7491 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7492 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7494 // Remove any implied protocols from the list of inherited protocols.
7495 if (!ImpliedProtocols.empty()) {
7496 IntersectionSet.erase(
7497 std::remove_if(IntersectionSet.begin(),
7498 IntersectionSet.end(),
7499 [&](ObjCProtocolDecl *proto) -> bool {
7500 return ImpliedProtocols.count(proto) > 0;
7502 IntersectionSet.end());
7505 // Sort the remaining protocols by name.
7506 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7507 compareObjCProtocolsByName);
7510 /// Determine whether the first type is a subtype of the second.
7511 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7513 // Common case: two object pointers.
7514 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7515 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7516 if (lhsOPT && rhsOPT)
7517 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7519 // Two block pointers.
7520 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7521 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7522 if (lhsBlock && rhsBlock)
7523 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7525 // If either is an unqualified 'id' and the other is a block, it's
7527 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7528 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7534 // Check that the given Objective-C type argument lists are equivalent.
7535 static bool sameObjCTypeArgs(ASTContext &ctx,
7536 const ObjCInterfaceDecl *iface,
7537 ArrayRef<QualType> lhsArgs,
7538 ArrayRef<QualType> rhsArgs,
7540 if (lhsArgs.size() != rhsArgs.size())
7543 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7544 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7545 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7548 switch (typeParams->begin()[i]->getVariance()) {
7549 case ObjCTypeParamVariance::Invariant:
7551 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7552 rhsArgs[i].stripObjCKindOfType(ctx))) {
7557 case ObjCTypeParamVariance::Covariant:
7558 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7562 case ObjCTypeParamVariance::Contravariant:
7563 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7572 QualType ASTContext::areCommonBaseCompatible(
7573 const ObjCObjectPointerType *Lptr,
7574 const ObjCObjectPointerType *Rptr) {
7575 const ObjCObjectType *LHS = Lptr->getObjectType();
7576 const ObjCObjectType *RHS = Rptr->getObjectType();
7577 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7578 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7580 if (!LDecl || !RDecl)
7583 // When either LHS or RHS is a kindof type, we should return a kindof type.
7584 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7586 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7588 // Follow the left-hand side up the class hierarchy until we either hit a
7589 // root or find the RHS. Record the ancestors in case we don't find it.
7590 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7593 // Record this ancestor. We'll need this if the common type isn't in the
7594 // path from the LHS to the root.
7595 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7597 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7598 // Get the type arguments.
7599 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7600 bool anyChanges = false;
7601 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7602 // Both have type arguments, compare them.
7603 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7604 LHS->getTypeArgs(), RHS->getTypeArgs(),
7605 /*stripKindOf=*/true))
7607 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7608 // If only one has type arguments, the result will not have type
7614 // Compute the intersection of protocols.
7615 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7616 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7618 if (!Protocols.empty())
7621 // If anything in the LHS will have changed, build a new result type.
7622 // If we need to return a kindof type but LHS is not a kindof type, we
7623 // build a new result type.
7624 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7625 QualType Result = getObjCInterfaceType(LHS->getInterface());
7626 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7627 anyKindOf || LHS->isKindOfType());
7628 return getObjCObjectPointerType(Result);
7631 return getObjCObjectPointerType(QualType(LHS, 0));
7634 // Find the superclass.
7635 QualType LHSSuperType = LHS->getSuperClassType();
7636 if (LHSSuperType.isNull())
7639 LHS = LHSSuperType->castAs<ObjCObjectType>();
7642 // We didn't find anything by following the LHS to its root; now check
7643 // the RHS against the cached set of ancestors.
7645 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7646 if (KnownLHS != LHSAncestors.end()) {
7647 LHS = KnownLHS->second;
7649 // Get the type arguments.
7650 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7651 bool anyChanges = false;
7652 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7653 // Both have type arguments, compare them.
7654 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7655 LHS->getTypeArgs(), RHS->getTypeArgs(),
7656 /*stripKindOf=*/true))
7658 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7659 // If only one has type arguments, the result will not have type
7665 // Compute the intersection of protocols.
7666 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7667 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7669 if (!Protocols.empty())
7672 // If we need to return a kindof type but RHS is not a kindof type, we
7673 // build a new result type.
7674 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7675 QualType Result = getObjCInterfaceType(RHS->getInterface());
7676 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7677 anyKindOf || RHS->isKindOfType());
7678 return getObjCObjectPointerType(Result);
7681 return getObjCObjectPointerType(QualType(RHS, 0));
7684 // Find the superclass of the RHS.
7685 QualType RHSSuperType = RHS->getSuperClassType();
7686 if (RHSSuperType.isNull())
7689 RHS = RHSSuperType->castAs<ObjCObjectType>();
7695 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7696 const ObjCObjectType *RHS) {
7697 assert(LHS->getInterface() && "LHS is not an interface type");
7698 assert(RHS->getInterface() && "RHS is not an interface type");
7700 // Verify that the base decls are compatible: the RHS must be a subclass of
7702 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7703 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7707 // If the LHS has protocol qualifiers, determine whether all of them are
7708 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7710 if (LHS->getNumProtocols() > 0) {
7711 // OK if conversion of LHS to SuperClass results in narrowing of types
7712 // ; i.e., SuperClass may implement at least one of the protocols
7713 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7714 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7715 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7716 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7717 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7719 for (auto *RHSPI : RHS->quals())
7720 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7721 // If there is no protocols associated with RHS, it is not a match.
7722 if (SuperClassInheritedProtocols.empty())
7725 for (const auto *LHSProto : LHS->quals()) {
7726 bool SuperImplementsProtocol = false;
7727 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7728 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7729 SuperImplementsProtocol = true;
7732 if (!SuperImplementsProtocol)
7737 // If the LHS is specialized, we may need to check type arguments.
7738 if (LHS->isSpecialized()) {
7739 // Follow the superclass chain until we've matched the LHS class in the
7740 // hierarchy. This substitutes type arguments through.
7741 const ObjCObjectType *RHSSuper = RHS;
7742 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7743 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7745 // If the RHS is specializd, compare type arguments.
7746 if (RHSSuper->isSpecialized() &&
7747 !sameObjCTypeArgs(*this, LHS->getInterface(),
7748 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7749 /*stripKindOf=*/true)) {
7757 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7758 // get the "pointed to" types
7759 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7760 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7762 if (!LHSOPT || !RHSOPT)
7765 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7766 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7769 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7770 return canAssignObjCInterfaces(
7771 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7772 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7775 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7776 /// both shall have the identically qualified version of a compatible type.
7777 /// C99 6.2.7p1: Two types have compatible types if their types are the
7778 /// same. See 6.7.[2,3,5] for additional rules.
7779 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7780 bool CompareUnqualified) {
7781 if (getLangOpts().CPlusPlus)
7782 return hasSameType(LHS, RHS);
7784 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7787 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7788 return typesAreCompatible(LHS, RHS);
7791 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7792 return !mergeTypes(LHS, RHS, true).isNull();
7795 /// mergeTransparentUnionType - if T is a transparent union type and a member
7796 /// of T is compatible with SubType, return the merged type, else return
7798 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7799 bool OfBlockPointer,
7801 if (const RecordType *UT = T->getAsUnionType()) {
7802 RecordDecl *UD = UT->getDecl();
7803 if (UD->hasAttr<TransparentUnionAttr>()) {
7804 for (const auto *I : UD->fields()) {
7805 QualType ET = I->getType().getUnqualifiedType();
7806 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7816 /// mergeFunctionParameterTypes - merge two types which appear as function
7818 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7819 bool OfBlockPointer,
7821 // GNU extension: two types are compatible if they appear as a function
7822 // argument, one of the types is a transparent union type and the other
7823 // type is compatible with a union member
7824 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7826 if (!lmerge.isNull())
7829 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7831 if (!rmerge.isNull())
7834 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7837 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7838 bool OfBlockPointer,
7840 const FunctionType *lbase = lhs->getAs<FunctionType>();
7841 const FunctionType *rbase = rhs->getAs<FunctionType>();
7842 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7843 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7844 bool allLTypes = true;
7845 bool allRTypes = true;
7847 // Check return type
7849 if (OfBlockPointer) {
7850 QualType RHS = rbase->getReturnType();
7851 QualType LHS = lbase->getReturnType();
7852 bool UnqualifiedResult = Unqualified;
7853 if (!UnqualifiedResult)
7854 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7855 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7858 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7860 if (retType.isNull()) return QualType();
7863 retType = retType.getUnqualifiedType();
7865 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7866 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7868 LRetType = LRetType.getUnqualifiedType();
7869 RRetType = RRetType.getUnqualifiedType();
7872 if (getCanonicalType(retType) != LRetType)
7874 if (getCanonicalType(retType) != RRetType)
7877 // FIXME: double check this
7878 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7879 // rbase->getRegParmAttr() != 0 &&
7880 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7881 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7882 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7884 // Compatible functions must have compatible calling conventions
7885 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7888 // Regparm is part of the calling convention.
7889 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7891 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7894 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7897 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7898 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7900 if (lbaseInfo.getNoReturn() != NoReturn)
7902 if (rbaseInfo.getNoReturn() != NoReturn)
7905 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7907 if (lproto && rproto) { // two C99 style function prototypes
7908 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7909 "C++ shouldn't be here");
7910 // Compatible functions must have the same number of parameters
7911 if (lproto->getNumParams() != rproto->getNumParams())
7914 // Variadic and non-variadic functions aren't compatible
7915 if (lproto->isVariadic() != rproto->isVariadic())
7918 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7921 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7924 // Check parameter type compatibility
7925 SmallVector<QualType, 10> types;
7926 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7927 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7928 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7929 QualType paramType = mergeFunctionParameterTypes(
7930 lParamType, rParamType, OfBlockPointer, Unqualified);
7931 if (paramType.isNull())
7935 paramType = paramType.getUnqualifiedType();
7937 types.push_back(paramType);
7939 lParamType = lParamType.getUnqualifiedType();
7940 rParamType = rParamType.getUnqualifiedType();
7943 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7945 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7949 if (allLTypes) return lhs;
7950 if (allRTypes) return rhs;
7952 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7953 EPI.ExtInfo = einfo;
7954 return getFunctionType(retType, types, EPI);
7957 if (lproto) allRTypes = false;
7958 if (rproto) allLTypes = false;
7960 const FunctionProtoType *proto = lproto ? lproto : rproto;
7962 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7963 if (proto->isVariadic()) return QualType();
7964 // Check that the types are compatible with the types that
7965 // would result from default argument promotions (C99 6.7.5.3p15).
7966 // The only types actually affected are promotable integer
7967 // types and floats, which would be passed as a different
7968 // type depending on whether the prototype is visible.
7969 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7970 QualType paramTy = proto->getParamType(i);
7972 // Look at the converted type of enum types, since that is the type used
7973 // to pass enum values.
7974 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7975 paramTy = Enum->getDecl()->getIntegerType();
7976 if (paramTy.isNull())
7980 if (paramTy->isPromotableIntegerType() ||
7981 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7985 if (allLTypes) return lhs;
7986 if (allRTypes) return rhs;
7988 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7989 EPI.ExtInfo = einfo;
7990 return getFunctionType(retType, proto->getParamTypes(), EPI);
7993 if (allLTypes) return lhs;
7994 if (allRTypes) return rhs;
7995 return getFunctionNoProtoType(retType, einfo);
7998 /// Given that we have an enum type and a non-enum type, try to merge them.
7999 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8000 QualType other, bool isBlockReturnType) {
8001 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8002 // a signed integer type, or an unsigned integer type.
8003 // Compatibility is based on the underlying type, not the promotion
8005 QualType underlyingType = ET->getDecl()->getIntegerType();
8006 if (underlyingType.isNull()) return QualType();
8007 if (Context.hasSameType(underlyingType, other))
8010 // In block return types, we're more permissive and accept any
8011 // integral type of the same size.
8012 if (isBlockReturnType && other->isIntegerType() &&
8013 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8019 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
8020 bool OfBlockPointer,
8021 bool Unqualified, bool BlockReturnType) {
8022 // C++ [expr]: If an expression initially has the type "reference to T", the
8023 // type is adjusted to "T" prior to any further analysis, the expression
8024 // designates the object or function denoted by the reference, and the
8025 // expression is an lvalue unless the reference is an rvalue reference and
8026 // the expression is a function call (possibly inside parentheses).
8027 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8028 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8031 LHS = LHS.getUnqualifiedType();
8032 RHS = RHS.getUnqualifiedType();
8035 QualType LHSCan = getCanonicalType(LHS),
8036 RHSCan = getCanonicalType(RHS);
8038 // If two types are identical, they are compatible.
8039 if (LHSCan == RHSCan)
8042 // If the qualifiers are different, the types aren't compatible... mostly.
8043 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8044 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8045 if (LQuals != RQuals) {
8046 if (getLangOpts().OpenCL) {
8047 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
8048 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
8050 if (LQuals.isAddressSpaceSupersetOf(RQuals))
8052 if (RQuals.isAddressSpaceSupersetOf(LQuals))
8055 // If any of these qualifiers are different, we have a type
8057 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8058 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8059 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
8062 // Exactly one GC qualifier difference is allowed: __strong is
8063 // okay if the other type has no GC qualifier but is an Objective
8064 // C object pointer (i.e. implicitly strong by default). We fix
8065 // this by pretending that the unqualified type was actually
8066 // qualified __strong.
8067 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8068 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8069 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8071 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8074 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8075 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8077 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8078 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8083 // Okay, qualifiers are equal.
8085 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8086 Type::TypeClass RHSClass = RHSCan->getTypeClass();
8088 // We want to consider the two function types to be the same for these
8089 // comparisons, just force one to the other.
8090 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8091 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8093 // Same as above for arrays
8094 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8095 LHSClass = Type::ConstantArray;
8096 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8097 RHSClass = Type::ConstantArray;
8099 // ObjCInterfaces are just specialized ObjCObjects.
8100 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8101 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8103 // Canonicalize ExtVector -> Vector.
8104 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8105 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8107 // If the canonical type classes don't match.
8108 if (LHSClass != RHSClass) {
8109 // Note that we only have special rules for turning block enum
8110 // returns into block int returns, not vice-versa.
8111 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
8112 return mergeEnumWithInteger(*this, ETy, RHS, false);
8114 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8115 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8117 // allow block pointer type to match an 'id' type.
8118 if (OfBlockPointer && !BlockReturnType) {
8119 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8121 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8128 // The canonical type classes match.
8130 #define TYPE(Class, Base)
8131 #define ABSTRACT_TYPE(Class, Base)
8132 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8133 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8134 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8135 #include "clang/AST/TypeNodes.def"
8136 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8139 case Type::LValueReference:
8140 case Type::RValueReference:
8141 case Type::MemberPointer:
8142 llvm_unreachable("C++ should never be in mergeTypes");
8144 case Type::ObjCInterface:
8145 case Type::IncompleteArray:
8146 case Type::VariableArray:
8147 case Type::FunctionProto:
8148 case Type::ExtVector:
8149 llvm_unreachable("Types are eliminated above");
8153 // Merge two pointer types, while trying to preserve typedef info
8154 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8155 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8157 LHSPointee = LHSPointee.getUnqualifiedType();
8158 RHSPointee = RHSPointee.getUnqualifiedType();
8160 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8162 if (ResultType.isNull()) return QualType();
8163 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8165 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8167 return getPointerType(ResultType);
8169 case Type::BlockPointer:
8171 // Merge two block pointer types, while trying to preserve typedef info
8172 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8173 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8175 LHSPointee = LHSPointee.getUnqualifiedType();
8176 RHSPointee = RHSPointee.getUnqualifiedType();
8178 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8180 if (ResultType.isNull()) return QualType();
8181 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8183 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8185 return getBlockPointerType(ResultType);
8189 // Merge two pointer types, while trying to preserve typedef info
8190 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8191 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8193 LHSValue = LHSValue.getUnqualifiedType();
8194 RHSValue = RHSValue.getUnqualifiedType();
8196 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8198 if (ResultType.isNull()) return QualType();
8199 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8201 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8203 return getAtomicType(ResultType);
8205 case Type::ConstantArray:
8207 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8208 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8209 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8212 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8213 QualType RHSElem = getAsArrayType(RHS)->getElementType();
8215 LHSElem = LHSElem.getUnqualifiedType();
8216 RHSElem = RHSElem.getUnqualifiedType();
8219 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8220 if (ResultType.isNull()) return QualType();
8221 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8223 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8225 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8226 ArrayType::ArraySizeModifier(), 0);
8227 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8228 ArrayType::ArraySizeModifier(), 0);
8229 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8230 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8231 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8233 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8236 // FIXME: This isn't correct! But tricky to implement because
8237 // the array's size has to be the size of LHS, but the type
8238 // has to be different.
8242 // FIXME: This isn't correct! But tricky to implement because
8243 // the array's size has to be the size of RHS, but the type
8244 // has to be different.
8247 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8248 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
8249 return getIncompleteArrayType(ResultType,
8250 ArrayType::ArraySizeModifier(), 0);
8252 case Type::FunctionNoProto:
8253 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
8258 // Only exactly equal builtin types are compatible, which is tested above.
8261 // Distinct complex types are incompatible.
8264 // FIXME: The merged type should be an ExtVector!
8265 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8266 RHSCan->getAs<VectorType>()))
8269 case Type::ObjCObject: {
8270 // Check if the types are assignment compatible.
8271 // FIXME: This should be type compatibility, e.g. whether
8272 // "LHS x; RHS x;" at global scope is legal.
8273 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8274 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8275 if (canAssignObjCInterfaces(LHSIface, RHSIface))
8280 case Type::ObjCObjectPointer: {
8281 if (OfBlockPointer) {
8282 if (canAssignObjCInterfacesInBlockPointer(
8283 LHS->getAs<ObjCObjectPointerType>(),
8284 RHS->getAs<ObjCObjectPointerType>(),
8289 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8290 RHS->getAs<ObjCObjectPointerType>()))
8297 assert(LHS != RHS &&
8298 "Equivalent pipe types should have already been handled!");
8303 llvm_unreachable("Invalid Type::Class!");
8306 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8307 const FunctionProtoType *firstFnType,
8308 const FunctionProtoType *secondFnType) {
8309 // Fast path: if the first type doesn't have ext parameter infos,
8310 // we match if and only if they second type also doesn't have them.
8311 if (!firstFnType->hasExtParameterInfos())
8312 return !secondFnType->hasExtParameterInfos();
8314 // Otherwise, we can only match if the second type has them.
8315 if (!secondFnType->hasExtParameterInfos())
8318 auto firstEPI = firstFnType->getExtParameterInfos();
8319 auto secondEPI = secondFnType->getExtParameterInfos();
8320 assert(firstEPI.size() == secondEPI.size());
8322 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8323 if (firstEPI[i] != secondEPI[i])
8329 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8330 ObjCLayouts[CD] = nullptr;
8333 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8334 /// 'RHS' attributes and returns the merged version; including for function
8336 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8337 QualType LHSCan = getCanonicalType(LHS),
8338 RHSCan = getCanonicalType(RHS);
8339 // If two types are identical, they are compatible.
8340 if (LHSCan == RHSCan)
8342 if (RHSCan->isFunctionType()) {
8343 if (!LHSCan->isFunctionType())
8345 QualType OldReturnType =
8346 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
8347 QualType NewReturnType =
8348 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
8349 QualType ResReturnType =
8350 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8351 if (ResReturnType.isNull())
8353 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8354 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8355 // In either case, use OldReturnType to build the new function type.
8356 const FunctionType *F = LHS->getAs<FunctionType>();
8357 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
8358 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8359 EPI.ExtInfo = getFunctionExtInfo(LHS);
8360 QualType ResultType =
8361 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
8368 // If the qualifiers are different, the types can still be merged.
8369 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8370 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8371 if (LQuals != RQuals) {
8372 // If any of these qualifiers are different, we have a type mismatch.
8373 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8374 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8377 // Exactly one GC qualifier difference is allowed: __strong is
8378 // okay if the other type has no GC qualifier but is an Objective
8379 // C object pointer (i.e. implicitly strong by default). We fix
8380 // this by pretending that the unqualified type was actually
8381 // qualified __strong.
8382 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8383 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8384 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8386 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8389 if (GC_L == Qualifiers::Strong)
8391 if (GC_R == Qualifiers::Strong)
8396 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8397 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8398 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8399 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8400 if (ResQT == LHSBaseQT)
8402 if (ResQT == RHSBaseQT)
8408 //===----------------------------------------------------------------------===//
8409 // Integer Predicates
8410 //===----------------------------------------------------------------------===//
8412 unsigned ASTContext::getIntWidth(QualType T) const {
8413 if (const EnumType *ET = T->getAs<EnumType>())
8414 T = ET->getDecl()->getIntegerType();
8415 if (T->isBooleanType())
8417 // For builtin types, just use the standard type sizing method
8418 return (unsigned)getTypeSize(T);
8421 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8422 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8424 // Turn <4 x signed int> -> <4 x unsigned int>
8425 if (const VectorType *VTy = T->getAs<VectorType>())
8426 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8427 VTy->getNumElements(), VTy->getVectorKind());
8429 // For enums, we return the unsigned version of the base type.
8430 if (const EnumType *ETy = T->getAs<EnumType>())
8431 T = ETy->getDecl()->getIntegerType();
8433 const BuiltinType *BTy = T->getAs<BuiltinType>();
8434 assert(BTy && "Unexpected signed integer type");
8435 switch (BTy->getKind()) {
8436 case BuiltinType::Char_S:
8437 case BuiltinType::SChar:
8438 return UnsignedCharTy;
8439 case BuiltinType::Short:
8440 return UnsignedShortTy;
8441 case BuiltinType::Int:
8442 return UnsignedIntTy;
8443 case BuiltinType::Long:
8444 return UnsignedLongTy;
8445 case BuiltinType::LongLong:
8446 return UnsignedLongLongTy;
8447 case BuiltinType::Int128:
8448 return UnsignedInt128Ty;
8450 llvm_unreachable("Unexpected signed integer type");
8454 ASTMutationListener::~ASTMutationListener() { }
8456 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8457 QualType ReturnType) {}
8459 //===----------------------------------------------------------------------===//
8460 // Builtin Type Computation
8461 //===----------------------------------------------------------------------===//
8463 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8464 /// pointer over the consumed characters. This returns the resultant type. If
8465 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8466 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8467 /// a vector of "i*".
8469 /// RequiresICE is filled in on return to indicate whether the value is required
8470 /// to be an Integer Constant Expression.
8471 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8472 ASTContext::GetBuiltinTypeError &Error,
8474 bool AllowTypeModifiers) {
8477 bool Signed = false, Unsigned = false;
8478 RequiresICE = false;
8480 // Read the prefixed modifiers first.
8484 default: Done = true; --Str; break;
8489 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8490 assert(!Signed && "Can't use 'S' modifier multiple times!");
8494 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8495 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8499 assert(HowLong <= 2 && "Can't have LLLL modifier");
8503 // This modifier represents int64 type.
8504 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8505 switch (Context.getTargetInfo().getInt64Type()) {
8507 llvm_unreachable("Unexpected integer type");
8508 case TargetInfo::SignedLong:
8511 case TargetInfo::SignedLongLong:
8520 // Read the base type.
8522 default: llvm_unreachable("Unknown builtin type letter!");
8524 assert(HowLong == 0 && !Signed && !Unsigned &&
8525 "Bad modifiers used with 'v'!");
8526 Type = Context.VoidTy;
8529 assert(HowLong == 0 && !Signed && !Unsigned &&
8530 "Bad modifiers used with 'h'!");
8531 Type = Context.HalfTy;
8534 assert(HowLong == 0 && !Signed && !Unsigned &&
8535 "Bad modifiers used with 'f'!");
8536 Type = Context.FloatTy;
8539 assert(HowLong < 2 && !Signed && !Unsigned &&
8540 "Bad modifiers used with 'd'!");
8542 Type = Context.LongDoubleTy;
8544 Type = Context.DoubleTy;
8547 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8549 Type = Context.UnsignedShortTy;
8551 Type = Context.ShortTy;
8555 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8556 else if (HowLong == 2)
8557 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8558 else if (HowLong == 1)
8559 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8561 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8564 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8566 Type = Context.SignedCharTy;
8568 Type = Context.UnsignedCharTy;
8570 Type = Context.CharTy;
8572 case 'b': // boolean
8573 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8574 Type = Context.BoolTy;
8576 case 'z': // size_t.
8577 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8578 Type = Context.getSizeType();
8580 case 'w': // wchar_t.
8581 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8582 Type = Context.getWideCharType();
8585 Type = Context.getCFConstantStringType();
8588 Type = Context.getObjCIdType();
8591 Type = Context.getObjCSelType();
8594 Type = Context.getObjCSuperType();
8597 Type = Context.getBuiltinVaListType();
8598 assert(!Type.isNull() && "builtin va list type not initialized!");
8601 // This is a "reference" to a va_list; however, what exactly
8602 // this means depends on how va_list is defined. There are two
8603 // different kinds of va_list: ones passed by value, and ones
8604 // passed by reference. An example of a by-value va_list is
8605 // x86, where va_list is a char*. An example of by-ref va_list
8606 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8607 // we want this argument to be a char*&; for x86-64, we want
8608 // it to be a __va_list_tag*.
8609 Type = Context.getBuiltinVaListType();
8610 assert(!Type.isNull() && "builtin va list type not initialized!");
8611 if (Type->isArrayType())
8612 Type = Context.getArrayDecayedType(Type);
8614 Type = Context.getLValueReferenceType(Type);
8618 unsigned NumElements = strtoul(Str, &End, 10);
8619 assert(End != Str && "Missing vector size");
8622 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8623 RequiresICE, false);
8624 assert(!RequiresICE && "Can't require vector ICE");
8626 // TODO: No way to make AltiVec vectors in builtins yet.
8627 Type = Context.getVectorType(ElementType, NumElements,
8628 VectorType::GenericVector);
8634 unsigned NumElements = strtoul(Str, &End, 10);
8635 assert(End != Str && "Missing vector size");
8639 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8641 Type = Context.getExtVectorType(ElementType, NumElements);
8645 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8647 assert(!RequiresICE && "Can't require complex ICE");
8648 Type = Context.getComplexType(ElementType);
8652 Type = Context.getPointerDiffType();
8656 Type = Context.getFILEType();
8657 if (Type.isNull()) {
8658 Error = ASTContext::GE_Missing_stdio;
8664 Type = Context.getsigjmp_bufType();
8666 Type = Context.getjmp_bufType();
8668 if (Type.isNull()) {
8669 Error = ASTContext::GE_Missing_setjmp;
8674 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8675 Type = Context.getucontext_tType();
8677 if (Type.isNull()) {
8678 Error = ASTContext::GE_Missing_ucontext;
8683 Type = Context.getProcessIDType();
8687 // If there are modifiers and if we're allowed to parse them, go for it.
8688 Done = !AllowTypeModifiers;
8690 switch (char c = *Str++) {
8691 default: Done = true; --Str; break;
8694 // Both pointers and references can have their pointee types
8695 // qualified with an address space.
8697 unsigned AddrSpace = strtoul(Str, &End, 10);
8698 if (End != Str && AddrSpace != 0) {
8699 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8703 Type = Context.getPointerType(Type);
8705 Type = Context.getLValueReferenceType(Type);
8708 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8710 Type = Type.withConst();
8713 Type = Context.getVolatileType(Type);
8716 Type = Type.withRestrict();
8721 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8722 "Integer constant 'I' type must be an integer");
8727 /// GetBuiltinType - Return the type for the specified builtin.
8728 QualType ASTContext::GetBuiltinType(unsigned Id,
8729 GetBuiltinTypeError &Error,
8730 unsigned *IntegerConstantArgs) const {
8731 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8733 SmallVector<QualType, 8> ArgTypes;
8735 bool RequiresICE = false;
8737 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8739 if (Error != GE_None)
8742 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8744 while (TypeStr[0] && TypeStr[0] != '.') {
8745 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8746 if (Error != GE_None)
8749 // If this argument is required to be an IntegerConstantExpression and the
8750 // caller cares, fill in the bitmask we return.
8751 if (RequiresICE && IntegerConstantArgs)
8752 *IntegerConstantArgs |= 1 << ArgTypes.size();
8754 // Do array -> pointer decay. The builtin should use the decayed type.
8755 if (Ty->isArrayType())
8756 Ty = getArrayDecayedType(Ty);
8758 ArgTypes.push_back(Ty);
8761 if (Id == Builtin::BI__GetExceptionInfo)
8764 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8765 "'.' should only occur at end of builtin type list!");
8767 FunctionType::ExtInfo EI(CC_C);
8768 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8770 bool Variadic = (TypeStr[0] == '.');
8772 // We really shouldn't be making a no-proto type here.
8773 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
8774 return getFunctionNoProtoType(ResType, EI);
8776 FunctionProtoType::ExtProtoInfo EPI;
8778 EPI.Variadic = Variadic;
8779 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8780 EPI.ExceptionSpec.Type =
8781 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
8783 return getFunctionType(ResType, ArgTypes, EPI);
8786 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8787 const FunctionDecl *FD) {
8788 if (!FD->isExternallyVisible())
8789 return GVA_Internal;
8791 GVALinkage External = GVA_StrongExternal;
8792 switch (FD->getTemplateSpecializationKind()) {
8793 case TSK_Undeclared:
8794 case TSK_ExplicitSpecialization:
8795 External = GVA_StrongExternal;
8798 case TSK_ExplicitInstantiationDefinition:
8799 return GVA_StrongODR;
8801 // C++11 [temp.explicit]p10:
8802 // [ Note: The intent is that an inline function that is the subject of
8803 // an explicit instantiation declaration will still be implicitly
8804 // instantiated when used so that the body can be considered for
8805 // inlining, but that no out-of-line copy of the inline function would be
8806 // generated in the translation unit. -- end note ]
8807 case TSK_ExplicitInstantiationDeclaration:
8808 return GVA_AvailableExternally;
8810 case TSK_ImplicitInstantiation:
8811 External = GVA_DiscardableODR;
8815 if (!FD->isInlined())
8818 if ((!Context.getLangOpts().CPlusPlus &&
8819 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8820 !FD->hasAttr<DLLExportAttr>()) ||
8821 FD->hasAttr<GNUInlineAttr>()) {
8822 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8824 // GNU or C99 inline semantics. Determine whether this symbol should be
8825 // externally visible.
8826 if (FD->isInlineDefinitionExternallyVisible())
8829 // C99 inline semantics, where the symbol is not externally visible.
8830 return GVA_AvailableExternally;
8833 // Functions specified with extern and inline in -fms-compatibility mode
8834 // forcibly get emitted. While the body of the function cannot be later
8835 // replaced, the function definition cannot be discarded.
8836 if (FD->isMSExternInline())
8837 return GVA_StrongODR;
8839 return GVA_DiscardableODR;
8842 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8843 GVALinkage L, const Decl *D) {
8844 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8845 // dllexport/dllimport on inline functions.
8846 if (D->hasAttr<DLLImportAttr>()) {
8847 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8848 return GVA_AvailableExternally;
8849 } else if (D->hasAttr<DLLExportAttr>()) {
8850 if (L == GVA_DiscardableODR)
8851 return GVA_StrongODR;
8852 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8853 D->hasAttr<CUDAGlobalAttr>()) {
8854 // Device-side functions with __global__ attribute must always be
8855 // visible externally so they can be launched from host.
8856 if (L == GVA_DiscardableODR || L == GVA_Internal)
8857 return GVA_StrongODR;
8862 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8863 return adjustGVALinkageForAttributes(
8864 *this, basicGVALinkageForFunction(*this, FD), FD);
8867 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8868 const VarDecl *VD) {
8869 if (!VD->isExternallyVisible())
8870 return GVA_Internal;
8872 if (VD->isStaticLocal()) {
8873 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8874 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8875 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8876 LexicalContext = LexicalContext->getLexicalParent();
8878 // Let the static local variable inherit its linkage from the nearest
8879 // enclosing function.
8881 StaticLocalLinkage =
8882 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8884 // GVA_StrongODR function linkage is stronger than what we need,
8885 // downgrade to GVA_DiscardableODR.
8886 // This allows us to discard the variable if we never end up needing it.
8887 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8888 : StaticLocalLinkage;
8891 // MSVC treats in-class initialized static data members as definitions.
8892 // By giving them non-strong linkage, out-of-line definitions won't
8893 // cause link errors.
8894 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8895 return GVA_DiscardableODR;
8897 // Most non-template variables have strong linkage; inline variables are
8898 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8899 GVALinkage StrongLinkage;
8900 switch (Context.getInlineVariableDefinitionKind(VD)) {
8901 case ASTContext::InlineVariableDefinitionKind::None:
8902 StrongLinkage = GVA_StrongExternal;
8904 case ASTContext::InlineVariableDefinitionKind::Weak:
8905 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8906 StrongLinkage = GVA_DiscardableODR;
8908 case ASTContext::InlineVariableDefinitionKind::Strong:
8909 StrongLinkage = GVA_StrongODR;
8913 switch (VD->getTemplateSpecializationKind()) {
8914 case TSK_Undeclared:
8915 return StrongLinkage;
8917 case TSK_ExplicitSpecialization:
8918 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8919 VD->isStaticDataMember()
8923 case TSK_ExplicitInstantiationDefinition:
8924 return GVA_StrongODR;
8926 case TSK_ExplicitInstantiationDeclaration:
8927 return GVA_AvailableExternally;
8929 case TSK_ImplicitInstantiation:
8930 return GVA_DiscardableODR;
8933 llvm_unreachable("Invalid Linkage!");
8936 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8937 return adjustGVALinkageForAttributes(
8938 *this, basicGVALinkageForVariable(*this, VD), VD);
8941 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8942 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8943 if (!VD->isFileVarDecl())
8945 // Global named register variables (GNU extension) are never emitted.
8946 if (VD->getStorageClass() == SC_Register)
8948 if (VD->getDescribedVarTemplate() ||
8949 isa<VarTemplatePartialSpecializationDecl>(VD))
8951 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8952 // We never need to emit an uninstantiated function template.
8953 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8955 } else if (isa<PragmaCommentDecl>(D))
8957 else if (isa<OMPThreadPrivateDecl>(D) ||
8958 D->hasAttr<OMPDeclareTargetDeclAttr>())
8960 else if (isa<PragmaDetectMismatchDecl>(D))
8962 else if (isa<OMPThreadPrivateDecl>(D))
8963 return !D->getDeclContext()->isDependentContext();
8964 else if (isa<OMPDeclareReductionDecl>(D))
8965 return !D->getDeclContext()->isDependentContext();
8966 else if (isa<ImportDecl>(D))
8971 // If this is a member of a class template, we do not need to emit it.
8972 if (D->getDeclContext()->isDependentContext())
8975 // Weak references don't produce any output by themselves.
8976 if (D->hasAttr<WeakRefAttr>())
8979 // Aliases and used decls are required.
8980 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8983 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8984 // Forward declarations aren't required.
8985 if (!FD->doesThisDeclarationHaveABody())
8986 return FD->doesDeclarationForceExternallyVisibleDefinition();
8988 // Constructors and destructors are required.
8989 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8992 // The key function for a class is required. This rule only comes
8993 // into play when inline functions can be key functions, though.
8994 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8995 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8996 const CXXRecordDecl *RD = MD->getParent();
8997 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8998 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8999 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9005 // static, static inline, always_inline, and extern inline functions can
9006 // always be deferred. Normal inline functions can be deferred in C99/C++.
9007 // Implicit template instantiations can also be deferred in C++.
9008 return !isDiscardableGVALinkage(GetGVALinkageForFunction(FD));
9011 const VarDecl *VD = cast<VarDecl>(D);
9012 assert(VD->isFileVarDecl() && "Expected file scoped var");
9014 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9015 !isMSStaticDataMemberInlineDefinition(VD))
9018 // Variables that can be needed in other TUs are required.
9019 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
9022 // Variables that have destruction with side-effects are required.
9023 if (VD->getType().isDestructedType())
9026 // Variables that have initialization with side-effects are required.
9027 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9028 // We can get a value-dependent initializer during error recovery.
9029 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9032 // Likewise, variables with tuple-like bindings are required if their
9033 // bindings have side-effects.
9034 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9035 for (auto *BD : DD->bindings())
9036 if (auto *BindingVD = BD->getHoldingVar())
9037 if (DeclMustBeEmitted(BindingVD))
9043 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9044 bool IsCXXMethod) const {
9045 // Pass through to the C++ ABI object
9047 return ABI->getDefaultMethodCallConv(IsVariadic);
9049 switch (LangOpts.getDefaultCallingConv()) {
9050 case LangOptions::DCC_None:
9052 case LangOptions::DCC_CDecl:
9054 case LangOptions::DCC_FastCall:
9055 if (getTargetInfo().hasFeature("sse2"))
9056 return CC_X86FastCall;
9058 case LangOptions::DCC_StdCall:
9060 return CC_X86StdCall;
9062 case LangOptions::DCC_VectorCall:
9063 // __vectorcall cannot be applied to variadic functions.
9065 return CC_X86VectorCall;
9068 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
9071 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
9072 // Pass through to the C++ ABI object
9073 return ABI->isNearlyEmpty(RD);
9076 VTableContextBase *ASTContext::getVTableContext() {
9077 if (!VTContext.get()) {
9078 if (Target->getCXXABI().isMicrosoft())
9079 VTContext.reset(new MicrosoftVTableContext(*this));
9081 VTContext.reset(new ItaniumVTableContext(*this));
9083 return VTContext.get();
9086 MangleContext *ASTContext::createMangleContext() {
9087 switch (Target->getCXXABI().getKind()) {
9088 case TargetCXXABI::GenericAArch64:
9089 case TargetCXXABI::GenericItanium:
9090 case TargetCXXABI::GenericARM:
9091 case TargetCXXABI::GenericMIPS:
9092 case TargetCXXABI::iOS:
9093 case TargetCXXABI::iOS64:
9094 case TargetCXXABI::WebAssembly:
9095 case TargetCXXABI::WatchOS:
9096 return ItaniumMangleContext::create(*this, getDiagnostics());
9097 case TargetCXXABI::Microsoft:
9098 return MicrosoftMangleContext::create(*this, getDiagnostics());
9100 llvm_unreachable("Unsupported ABI");
9103 CXXABI::~CXXABI() {}
9105 size_t ASTContext::getSideTableAllocatedMemory() const {
9106 return ASTRecordLayouts.getMemorySize() +
9107 llvm::capacity_in_bytes(ObjCLayouts) +
9108 llvm::capacity_in_bytes(KeyFunctions) +
9109 llvm::capacity_in_bytes(ObjCImpls) +
9110 llvm::capacity_in_bytes(BlockVarCopyInits) +
9111 llvm::capacity_in_bytes(DeclAttrs) +
9112 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9113 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9114 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9115 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9116 llvm::capacity_in_bytes(OverriddenMethods) +
9117 llvm::capacity_in_bytes(Types) +
9118 llvm::capacity_in_bytes(VariableArrayTypes) +
9119 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
9122 /// getIntTypeForBitwidth -
9123 /// sets integer QualTy according to specified details:
9124 /// bitwidth, signed/unsigned.
9125 /// Returns empty type if there is no appropriate target types.
9126 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9127 unsigned Signed) const {
9128 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9129 CanQualType QualTy = getFromTargetType(Ty);
9130 if (!QualTy && DestWidth == 128)
9131 return Signed ? Int128Ty : UnsignedInt128Ty;
9135 /// getRealTypeForBitwidth -
9136 /// sets floating point QualTy according to specified bitwidth.
9137 /// Returns empty type if there is no appropriate target types.
9138 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9139 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9141 case TargetInfo::Float:
9143 case TargetInfo::Double:
9145 case TargetInfo::LongDouble:
9146 return LongDoubleTy;
9147 case TargetInfo::Float128:
9149 case TargetInfo::NoFloat:
9153 llvm_unreachable("Unhandled TargetInfo::RealType value");
9156 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9158 MangleNumbers[ND] = Number;
9161 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
9162 auto I = MangleNumbers.find(ND);
9163 return I != MangleNumbers.end() ? I->second : 1;
9166 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9168 StaticLocalNumbers[VD] = Number;
9171 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
9172 auto I = StaticLocalNumbers.find(VD);
9173 return I != StaticLocalNumbers.end() ? I->second : 1;
9176 MangleNumberingContext &
9177 ASTContext::getManglingNumberContext(const DeclContext *DC) {
9178 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
9179 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
9181 MCtx = createMangleNumberingContext();
9185 std::unique_ptr<MangleNumberingContext>
9186 ASTContext::createMangleNumberingContext() const {
9187 return ABI->createMangleNumberingContext();
9190 const CXXConstructorDecl *
9191 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9192 return ABI->getCopyConstructorForExceptionObject(
9193 cast<CXXRecordDecl>(RD->getFirstDecl()));
9196 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9197 CXXConstructorDecl *CD) {
9198 return ABI->addCopyConstructorForExceptionObject(
9199 cast<CXXRecordDecl>(RD->getFirstDecl()),
9200 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9203 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9204 TypedefNameDecl *DD) {
9205 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9209 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9210 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9213 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9214 DeclaratorDecl *DD) {
9215 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9218 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9219 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9222 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9223 ParamIndices[D] = index;
9226 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9227 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9228 assert(I != ParamIndices.end() &&
9229 "ParmIndices lacks entry set by ParmVarDecl");
9234 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9236 assert(E && E->getStorageDuration() == SD_Static &&
9237 "don't need to cache the computed value for this temporary");
9239 APValue *&MTVI = MaterializedTemporaryValues[E];
9241 MTVI = new (*this) APValue;
9245 return MaterializedTemporaryValues.lookup(E);
9248 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9249 const llvm::Triple &T = getTargetInfo().getTriple();
9250 if (!T.isOSDarwin())
9253 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9254 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9257 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9258 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9259 uint64_t Size = sizeChars.getQuantity();
9260 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9261 unsigned Align = alignChars.getQuantity();
9262 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9263 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9268 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9269 ASTContext::ParentMapPointers::mapped_type U) {
9270 if (const auto *D = U.dyn_cast<const Decl *>())
9271 return ast_type_traits::DynTypedNode::create(*D);
9272 if (const auto *S = U.dyn_cast<const Stmt *>())
9273 return ast_type_traits::DynTypedNode::create(*S);
9274 return *U.get<ast_type_traits::DynTypedNode *>();
9277 /// Template specializations to abstract away from pointers and TypeLocs.
9279 template <typename T>
9280 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9281 return ast_type_traits::DynTypedNode::create(*Node);
9284 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9285 return ast_type_traits::DynTypedNode::create(Node);
9288 ast_type_traits::DynTypedNode
9289 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9290 return ast_type_traits::DynTypedNode::create(Node);
9294 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9295 /// parents as defined by the \c RecursiveASTVisitor.
9297 /// Note that the relationship described here is purely in terms of AST
9298 /// traversal - there are other relationships (for example declaration context)
9299 /// in the AST that are better modeled by special matchers.
9301 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
9302 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
9304 /// \brief Builds and returns the translation unit's parent map.
9306 /// The caller takes ownership of the returned \c ParentMap.
9307 static std::pair<ASTContext::ParentMapPointers *,
9308 ASTContext::ParentMapOtherNodes *>
9309 buildMap(TranslationUnitDecl &TU) {
9310 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9311 new ASTContext::ParentMapOtherNodes);
9312 Visitor.TraverseDecl(&TU);
9313 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
9317 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9319 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9320 ASTContext::ParentMapOtherNodes *OtherParents)
9321 : Parents(Parents), OtherParents(OtherParents) {}
9323 bool shouldVisitTemplateInstantiations() const {
9326 bool shouldVisitImplicitCode() const {
9330 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9332 bool TraverseNode(T Node, MapNodeTy MapNode,
9333 BaseTraverseFn BaseTraverse, MapTy *Parents) {
9336 if (ParentStack.size() > 0) {
9337 // FIXME: Currently we add the same parent multiple times, but only
9338 // when no memoization data is available for the type.
9339 // For example when we visit all subexpressions of template
9340 // instantiations; this is suboptimal, but benign: the only way to
9341 // visit those is with hasAncestor / hasParent, and those do not create
9343 // The plan is to enable DynTypedNode to be storable in a map or hash
9344 // map. The main problem there is to implement hash functions /
9345 // comparison operators for all types that DynTypedNode supports that
9346 // do not have pointer identity.
9347 auto &NodeOrVector = (*Parents)[MapNode];
9348 if (NodeOrVector.isNull()) {
9349 if (const auto *D = ParentStack.back().get<Decl>())
9351 else if (const auto *S = ParentStack.back().get<Stmt>())
9355 new ast_type_traits::DynTypedNode(ParentStack.back());
9357 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9358 auto *Vector = new ASTContext::ParentVector(
9359 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
9362 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9364 NodeOrVector = Vector;
9368 NodeOrVector.template get<ASTContext::ParentVector *>();
9369 // Skip duplicates for types that have memoization data.
9370 // We must check that the type has memoization data before calling
9371 // std::find() because DynTypedNode::operator== can't compare all
9373 bool Found = ParentStack.back().getMemoizationData() &&
9374 std::find(Vector->begin(), Vector->end(),
9375 ParentStack.back()) != Vector->end();
9377 Vector->push_back(ParentStack.back());
9380 ParentStack.push_back(createDynTypedNode(Node));
9381 bool Result = BaseTraverse();
9382 ParentStack.pop_back();
9386 bool TraverseDecl(Decl *DeclNode) {
9387 return TraverseNode(DeclNode, DeclNode,
9388 [&] { return VisitorBase::TraverseDecl(DeclNode); },
9392 bool TraverseStmt(Stmt *StmtNode) {
9393 return TraverseNode(StmtNode, StmtNode,
9394 [&] { return VisitorBase::TraverseStmt(StmtNode); },
9398 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9399 return TraverseNode(
9400 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9401 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9405 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9406 return TraverseNode(
9407 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9409 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9414 ASTContext::ParentMapPointers *Parents;
9415 ASTContext::ParentMapOtherNodes *OtherParents;
9416 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9418 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9421 } // anonymous namespace
9423 template <typename NodeTy, typename MapTy>
9424 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9426 auto I = Map.find(Node);
9427 if (I == Map.end()) {
9428 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9430 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9431 return llvm::makeArrayRef(*V);
9433 return getSingleDynTypedNodeFromParentMap(I->second);
9436 ASTContext::DynTypedNodeList
9437 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9438 if (!PointerParents) {
9439 // We always need to run over the whole translation unit, as
9440 // hasAncestor can escape any subtree.
9441 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9442 PointerParents.reset(Maps.first);
9443 OtherParents.reset(Maps.second);
9445 if (Node.getNodeKind().hasPointerIdentity())
9446 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9447 return getDynNodeFromMap(Node, *OtherParents);
9451 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9452 const ObjCMethodDecl *MethodImpl) {
9453 // No point trying to match an unavailable/deprecated mothod.
9454 if (MethodDecl->hasAttr<UnavailableAttr>()
9455 || MethodDecl->hasAttr<DeprecatedAttr>())
9457 if (MethodDecl->getObjCDeclQualifier() !=
9458 MethodImpl->getObjCDeclQualifier())
9460 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9463 if (MethodDecl->param_size() != MethodImpl->param_size())
9466 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9467 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9468 EF = MethodDecl->param_end();
9469 IM != EM && IF != EF; ++IM, ++IF) {
9470 const ParmVarDecl *DeclVar = (*IF);
9471 const ParmVarDecl *ImplVar = (*IM);
9472 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9474 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9477 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9481 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9483 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9486 AS = QT->getPointeeType().getAddressSpace();
9488 return getTargetInfo().getNullPointerValue(AS);
9491 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9492 // doesn't include ASTContext.h
9494 clang::LazyGenerationalUpdatePtr<
9495 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9496 clang::LazyGenerationalUpdatePtr<
9497 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9498 const clang::ASTContext &Ctx, Decl *Value);