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/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/VTableBuilder.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/SmallString.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
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 } // unnamed 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;
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
384 *OriginalDecl = OriginalDeclForRC;
386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
390 Raw.setOriginalDecl(OriginalDeclForRC);
392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
401 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 // Add redeclared method here.
409 for (const auto *Ext : ID->known_extensions()) {
410 if (ObjCMethodDecl *RedeclaredMethod =
411 Ext->getMethod(ObjCMethod->getSelector(),
412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
418 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
434 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
439 comments::FullComment *ASTContext::getCommentForDecl(
441 const Preprocessor *PP) const {
442 if (D->isInvalidDecl())
444 D = adjustDeclToTemplate(D);
446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
450 if (Pos != ParsedComments.end()) {
451 if (Canonical != D) {
452 comments::FullComment *FC = Pos->second;
453 comments::FullComment *CFC = cloneFullComment(FC, D);
459 const Decl *OriginalDecl;
461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
464 SmallVector<const NamedDecl*, 8> Overridden;
465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
478 // Attach any tag type's documentation to its typedef if latter
479 // does not have one of its own.
480 QualType QT = TD->getUnderlyingType();
481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
484 return cloneFullComment(FC, D);
486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
501 // Check non-virtual bases.
502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
505 QualType Ty = I.getType();
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
516 // Check virtual bases.
517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
520 QualType Ty = I.getType();
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
538 if (D != OriginalDecl)
539 return getCommentForDecl(OriginalDecl, PP);
541 comments::FullComment *FC = RC->parse(*this, PP, D);
542 ParsedComments[Canonical] = FC;
547 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
551 ID.AddBoolean(Parm->isParameterPack());
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddBoolean(TTP->isParameterPack());
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddBoolean(NTTP->isParameterPack());
567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
568 if (NTTP->isExpandedParameterPack()) {
570 ID.AddInteger(NTTP->getNumExpansionTypes());
571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576 ID.AddBoolean(false);
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
586 TemplateTemplateParmDecl *
587 ASTContext::getCanonicalTemplateTemplateParmDecl(
588 TemplateTemplateParmDecl *TTP) const {
589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
592 void *InsertPos = nullptr;
593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 return Canonical->getParam();
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
600 SmallVector<NamedDecl *, 4> CanonParams;
601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
611 TTP->getIndex(), nullptr, false,
612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
631 NTTP->getPosition(), nullptr,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
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 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
658 TTP->isParameterPack(),
660 TemplateParameterList::Create(*this, SourceLocation(),
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
668 assert(!Canonical && "Shouldn't be in the map!");
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
678 if (!LangOpts.CPlusPlus) return nullptr;
680 switch (T.getCXXABI().getKind()) {
681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
682 case TargetCXXABI::iOS:
683 case TargetCXXABI::iOS64:
684 case TargetCXXABI::GenericAArch64:
685 case TargetCXXABI::GenericItanium:
686 return CreateItaniumCXXABI(*this);
687 case TargetCXXABI::Microsoft:
688 return CreateMicrosoftCXXABI(*this);
690 llvm_unreachable("Invalid CXXABI type!");
693 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
694 const LangOptions &LOpts) {
695 if (LOpts.FakeAddressSpaceMap) {
696 // The fake address space map must have a distinct entry for each
697 // language-specific address space.
698 static const unsigned FakeAddrSpaceMap[] = {
701 3, // opencl_constant
707 return &FakeAddrSpaceMap;
709 return &T.getAddressSpaceMap();
713 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
714 const LangOptions &LangOpts) {
715 switch (LangOpts.getAddressSpaceMapMangling()) {
716 case LangOptions::ASMM_Target:
717 return TI.useAddressSpaceMapMangling();
718 case LangOptions::ASMM_On:
720 case LangOptions::ASMM_Off:
723 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
726 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
727 IdentifierTable &idents, SelectorTable &sels,
728 Builtin::Context &builtins)
729 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
732 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
733 UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
735 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
736 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
737 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
738 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
739 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
740 FirstLocalImport(), LastLocalImport(),
741 SourceMgr(SM), LangOpts(LOpts),
742 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)),
743 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
744 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
745 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
746 Comments(SM), CommentsLoaded(false),
747 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
748 TUDecl = TranslationUnitDecl::Create(*this);
751 ASTContext::~ASTContext() {
752 ReleaseParentMapEntries();
754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
783 A->second->~AttrVec();
785 llvm::DeleteContainerSeconds(MangleNumberingContexts);
788 void ASTContext::ReleaseParentMapEntries() {
789 if (!AllParents) return;
790 for (const auto &Entry : *AllParents) {
791 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
792 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794 assert(Entry.second.is<ParentVector *>());
795 delete Entry.second.get<ParentVector *>();
800 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
801 Deallocations[Callback].push_back(Data);
805 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
806 ExternalSource = Source;
809 void ASTContext::PrintStats() const {
810 llvm::errs() << "\n*** AST Context Stats:\n";
811 llvm::errs() << " " << Types.size() << " types total.\n";
813 unsigned counts[] = {
814 #define TYPE(Name, Parent) 0,
815 #define ABSTRACT_TYPE(Name, Parent)
816 #include "clang/AST/TypeNodes.def"
820 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822 counts[(unsigned)T->getTypeClass()]++;
826 unsigned TotalBytes = 0;
827 #define TYPE(Name, Parent) \
829 llvm::errs() << " " << counts[Idx] << " " << #Name \
831 TotalBytes += counts[Idx] * sizeof(Name##Type); \
833 #define ABSTRACT_TYPE(Name, Parent)
834 #include "clang/AST/TypeNodes.def"
836 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838 // Implicit special member functions.
839 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
840 << NumImplicitDefaultConstructors
841 << " implicit default constructors created\n";
842 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
843 << NumImplicitCopyConstructors
844 << " implicit copy constructors created\n";
845 if (getLangOpts().CPlusPlus)
846 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
847 << NumImplicitMoveConstructors
848 << " implicit move constructors created\n";
849 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
850 << NumImplicitCopyAssignmentOperators
851 << " implicit copy assignment operators created\n";
852 if (getLangOpts().CPlusPlus)
853 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
854 << NumImplicitMoveAssignmentOperators
855 << " implicit move assignment operators created\n";
856 llvm::errs() << NumImplicitDestructorsDeclared << "/"
857 << NumImplicitDestructors
858 << " implicit destructors created\n";
860 if (ExternalSource) {
861 llvm::errs() << "\n";
862 ExternalSource->PrintStats();
865 BumpAlloc.PrintStats();
868 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
869 RecordDecl::TagKind TK) const {
872 if (getLangOpts().CPlusPlus)
873 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
874 Loc, &Idents.get(Name));
876 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
878 NewDecl->setImplicit();
882 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
883 StringRef Name) const {
884 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
885 TypedefDecl *NewDecl = TypedefDecl::Create(
886 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
887 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
888 NewDecl->setImplicit();
892 TypedefDecl *ASTContext::getInt128Decl() const {
894 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
898 TypedefDecl *ASTContext::getUInt128Decl() const {
900 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
904 TypeDecl *ASTContext::getFloat128StubType() const {
905 assert(LangOpts.CPlusPlus && "should only be called for c++");
906 if (!Float128StubDecl)
907 Float128StubDecl = buildImplicitRecord("__float128");
909 return Float128StubDecl;
912 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
913 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
914 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
918 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
919 assert((!this->Target || this->Target == &Target) &&
920 "Incorrect target reinitialization");
921 assert(VoidTy.isNull() && "Context reinitialized?");
923 this->Target = &Target;
925 ABI.reset(createCXXABI(Target));
926 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
927 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
930 InitBuiltinType(VoidTy, BuiltinType::Void);
933 InitBuiltinType(BoolTy, BuiltinType::Bool);
935 if (LangOpts.CharIsSigned)
936 InitBuiltinType(CharTy, BuiltinType::Char_S);
938 InitBuiltinType(CharTy, BuiltinType::Char_U);
940 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
941 InitBuiltinType(ShortTy, BuiltinType::Short);
942 InitBuiltinType(IntTy, BuiltinType::Int);
943 InitBuiltinType(LongTy, BuiltinType::Long);
944 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
947 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
948 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
949 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
950 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
951 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
954 InitBuiltinType(FloatTy, BuiltinType::Float);
955 InitBuiltinType(DoubleTy, BuiltinType::Double);
956 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
958 // GNU extension, 128-bit integers.
959 InitBuiltinType(Int128Ty, BuiltinType::Int128);
960 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
963 if (TargetInfo::isTypeSigned(Target.getWCharType()))
964 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
965 else // -fshort-wchar makes wchar_t be unsigned.
966 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
967 if (LangOpts.CPlusPlus && LangOpts.WChar)
968 WideCharTy = WCharTy;
970 // C99 (or C++ using -fno-wchar).
971 WideCharTy = getFromTargetType(Target.getWCharType());
974 WIntTy = getFromTargetType(Target.getWIntType());
976 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
977 InitBuiltinType(Char16Ty, BuiltinType::Char16);
979 Char16Ty = getFromTargetType(Target.getChar16Type());
981 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
982 InitBuiltinType(Char32Ty, BuiltinType::Char32);
984 Char32Ty = getFromTargetType(Target.getChar32Type());
986 // Placeholder type for type-dependent expressions whose type is
987 // completely unknown. No code should ever check a type against
988 // DependentTy and users should never see it; however, it is here to
989 // help diagnose failures to properly check for type-dependent
991 InitBuiltinType(DependentTy, BuiltinType::Dependent);
993 // Placeholder type for functions.
994 InitBuiltinType(OverloadTy, BuiltinType::Overload);
996 // Placeholder type for bound members.
997 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
999 // Placeholder type for pseudo-objects.
1000 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1002 // "any" type; useful for debugger-like clients.
1003 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1005 // Placeholder type for unbridged ARC casts.
1006 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1008 // Placeholder type for builtin functions.
1009 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1012 FloatComplexTy = getComplexType(FloatTy);
1013 DoubleComplexTy = getComplexType(DoubleTy);
1014 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1016 // Builtin types for 'id', 'Class', and 'SEL'.
1017 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1018 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1019 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1021 if (LangOpts.OpenCL) {
1022 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1023 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1024 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1025 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1026 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1027 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1029 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1030 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1033 // Builtin type for __objc_yes and __objc_no
1034 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1035 SignedCharTy : BoolTy);
1037 ObjCConstantStringType = QualType();
1039 ObjCSuperType = QualType();
1042 VoidPtrTy = getPointerType(VoidTy);
1044 // nullptr type (C++0x 2.14.7)
1045 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1047 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1048 InitBuiltinType(HalfTy, BuiltinType::Half);
1050 // Builtin type used to help define __builtin_va_list.
1051 VaListTagTy = QualType();
1054 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1055 return SourceMgr.getDiagnostics();
1058 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1059 AttrVec *&Result = DeclAttrs[D];
1061 void *Mem = Allocate(sizeof(AttrVec));
1062 Result = new (Mem) AttrVec;
1068 /// \brief Erase the attributes corresponding to the given declaration.
1069 void ASTContext::eraseDeclAttrs(const Decl *D) {
1070 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1071 if (Pos != DeclAttrs.end()) {
1072 Pos->second->~AttrVec();
1073 DeclAttrs.erase(Pos);
1078 MemberSpecializationInfo *
1079 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1080 assert(Var->isStaticDataMember() && "Not a static data member");
1081 return getTemplateOrSpecializationInfo(Var)
1082 .dyn_cast<MemberSpecializationInfo *>();
1085 ASTContext::TemplateOrSpecializationInfo
1086 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1087 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1088 TemplateOrInstantiation.find(Var);
1089 if (Pos == TemplateOrInstantiation.end())
1090 return TemplateOrSpecializationInfo();
1096 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1097 TemplateSpecializationKind TSK,
1098 SourceLocation PointOfInstantiation) {
1099 assert(Inst->isStaticDataMember() && "Not a static data member");
1100 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1101 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1102 Tmpl, TSK, PointOfInstantiation));
1106 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1107 TemplateOrSpecializationInfo TSI) {
1108 assert(!TemplateOrInstantiation[Inst] &&
1109 "Already noted what the variable was instantiated from");
1110 TemplateOrInstantiation[Inst] = TSI;
1113 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1114 const FunctionDecl *FD){
1115 assert(FD && "Specialization is 0");
1116 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1117 = ClassScopeSpecializationPattern.find(FD);
1118 if (Pos == ClassScopeSpecializationPattern.end())
1124 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1125 FunctionDecl *Pattern) {
1126 assert(FD && "Specialization is 0");
1127 assert(Pattern && "Class scope specialization pattern is 0");
1128 ClassScopeSpecializationPattern[FD] = Pattern;
1132 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1133 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1134 = InstantiatedFromUsingDecl.find(UUD);
1135 if (Pos == InstantiatedFromUsingDecl.end())
1142 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1143 assert((isa<UsingDecl>(Pattern) ||
1144 isa<UnresolvedUsingValueDecl>(Pattern) ||
1145 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1146 "pattern decl is not a using decl");
1147 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1148 InstantiatedFromUsingDecl[Inst] = Pattern;
1152 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1153 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1154 = InstantiatedFromUsingShadowDecl.find(Inst);
1155 if (Pos == InstantiatedFromUsingShadowDecl.end())
1162 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1163 UsingShadowDecl *Pattern) {
1164 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1165 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1168 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1169 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1170 = InstantiatedFromUnnamedFieldDecl.find(Field);
1171 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1177 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1179 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1180 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1181 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1182 "Already noted what unnamed field was instantiated from");
1184 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1187 ASTContext::overridden_cxx_method_iterator
1188 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1190 = OverriddenMethods.find(Method->getCanonicalDecl());
1191 if (Pos == OverriddenMethods.end())
1194 return Pos->second.begin();
1197 ASTContext::overridden_cxx_method_iterator
1198 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1200 = OverriddenMethods.find(Method->getCanonicalDecl());
1201 if (Pos == OverriddenMethods.end())
1204 return Pos->second.end();
1208 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1209 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1210 = OverriddenMethods.find(Method->getCanonicalDecl());
1211 if (Pos == OverriddenMethods.end())
1214 return Pos->second.size();
1217 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1218 const CXXMethodDecl *Overridden) {
1219 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1220 OverriddenMethods[Method].push_back(Overridden);
1223 void ASTContext::getOverriddenMethods(
1225 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1228 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1229 Overridden.append(overridden_methods_begin(CXXMethod),
1230 overridden_methods_end(CXXMethod));
1234 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1238 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1239 Method->getOverriddenMethods(OverDecls);
1240 Overridden.append(OverDecls.begin(), OverDecls.end());
1243 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1244 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1245 assert(!Import->isFromASTFile() && "Non-local import declaration");
1246 if (!FirstLocalImport) {
1247 FirstLocalImport = Import;
1248 LastLocalImport = Import;
1252 LastLocalImport->NextLocalImport = Import;
1253 LastLocalImport = Import;
1256 //===----------------------------------------------------------------------===//
1257 // Type Sizing and Analysis
1258 //===----------------------------------------------------------------------===//
1260 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1261 /// scalar floating point type.
1262 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1263 const BuiltinType *BT = T->getAs<BuiltinType>();
1264 assert(BT && "Not a floating point type!");
1265 switch (BT->getKind()) {
1266 default: llvm_unreachable("Not a floating point type!");
1267 case BuiltinType::Half: return Target->getHalfFormat();
1268 case BuiltinType::Float: return Target->getFloatFormat();
1269 case BuiltinType::Double: return Target->getDoubleFormat();
1270 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1274 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1275 unsigned Align = Target->getCharWidth();
1277 bool UseAlignAttrOnly = false;
1278 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1279 Align = AlignFromAttr;
1281 // __attribute__((aligned)) can increase or decrease alignment
1282 // *except* on a struct or struct member, where it only increases
1283 // alignment unless 'packed' is also specified.
1285 // It is an error for alignas to decrease alignment, so we can
1286 // ignore that possibility; Sema should diagnose it.
1287 if (isa<FieldDecl>(D)) {
1288 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1289 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1291 UseAlignAttrOnly = true;
1294 else if (isa<FieldDecl>(D))
1296 D->hasAttr<PackedAttr>() ||
1297 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1299 // If we're using the align attribute only, just ignore everything
1300 // else about the declaration and its type.
1301 if (UseAlignAttrOnly) {
1304 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1305 QualType T = VD->getType();
1306 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1308 T = RT->getPointeeType();
1310 T = getPointerType(RT->getPointeeType());
1312 QualType BaseT = getBaseElementType(T);
1313 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1314 // Adjust alignments of declarations with array type by the
1315 // large-array alignment on the target.
1316 if (const ArrayType *arrayType = getAsArrayType(T)) {
1317 unsigned MinWidth = Target->getLargeArrayMinWidth();
1318 if (!ForAlignof && MinWidth) {
1319 if (isa<VariableArrayType>(arrayType))
1320 Align = std::max(Align, Target->getLargeArrayAlign());
1321 else if (isa<ConstantArrayType>(arrayType) &&
1322 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1323 Align = std::max(Align, Target->getLargeArrayAlign());
1326 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1327 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1328 if (VD->hasGlobalStorage())
1329 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1333 // Fields can be subject to extra alignment constraints, like if
1334 // the field is packed, the struct is packed, or the struct has a
1335 // a max-field-alignment constraint (#pragma pack). So calculate
1336 // the actual alignment of the field within the struct, and then
1337 // (as we're expected to) constrain that by the alignment of the type.
1338 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1339 const RecordDecl *Parent = Field->getParent();
1340 // We can only produce a sensible answer if the record is valid.
1341 if (!Parent->isInvalidDecl()) {
1342 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1344 // Start with the record's overall alignment.
1345 unsigned FieldAlign = toBits(Layout.getAlignment());
1347 // Use the GCD of that and the offset within the record.
1348 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1350 // Alignment is always a power of 2, so the GCD will be a power of 2,
1351 // which means we get to do this crazy thing instead of Euclid's.
1352 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1353 if (LowBitOfOffset < FieldAlign)
1354 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1357 Align = std::min(Align, FieldAlign);
1362 return toCharUnitsFromBits(Align);
1365 // getTypeInfoDataSizeInChars - Return the size of a type, in
1366 // chars. If the type is a record, its data size is returned. This is
1367 // the size of the memcpy that's performed when assigning this type
1368 // using a trivial copy/move assignment operator.
1369 std::pair<CharUnits, CharUnits>
1370 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1371 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1373 // In C++, objects can sometimes be allocated into the tail padding
1374 // of a base-class subobject. We decide whether that's possible
1375 // during class layout, so here we can just trust the layout results.
1376 if (getLangOpts().CPlusPlus) {
1377 if (const RecordType *RT = T->getAs<RecordType>()) {
1378 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1379 sizeAndAlign.first = layout.getDataSize();
1383 return sizeAndAlign;
1386 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1387 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1388 std::pair<CharUnits, CharUnits>
1389 static getConstantArrayInfoInChars(const ASTContext &Context,
1390 const ConstantArrayType *CAT) {
1391 std::pair<CharUnits, CharUnits> EltInfo =
1392 Context.getTypeInfoInChars(CAT->getElementType());
1393 uint64_t Size = CAT->getSize().getZExtValue();
1394 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1395 (uint64_t)(-1)/Size) &&
1396 "Overflow in array type char size evaluation");
1397 uint64_t Width = EltInfo.first.getQuantity() * Size;
1398 unsigned Align = EltInfo.second.getQuantity();
1399 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1400 Context.getTargetInfo().getPointerWidth(0) == 64)
1401 Width = llvm::RoundUpToAlignment(Width, Align);
1402 return std::make_pair(CharUnits::fromQuantity(Width),
1403 CharUnits::fromQuantity(Align));
1406 std::pair<CharUnits, CharUnits>
1407 ASTContext::getTypeInfoInChars(const Type *T) const {
1408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1409 return getConstantArrayInfoInChars(*this, CAT);
1410 TypeInfo Info = getTypeInfo(T);
1411 return std::make_pair(toCharUnitsFromBits(Info.Width),
1412 toCharUnitsFromBits(Info.Align));
1415 std::pair<CharUnits, CharUnits>
1416 ASTContext::getTypeInfoInChars(QualType T) const {
1417 return getTypeInfoInChars(T.getTypePtr());
1420 bool ASTContext::isAlignmentRequired(const Type *T) const {
1421 return getTypeInfo(T).AlignIsRequired;
1424 bool ASTContext::isAlignmentRequired(QualType T) const {
1425 return isAlignmentRequired(T.getTypePtr());
1428 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1429 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1430 if (I != MemoizedTypeInfo.end())
1433 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1434 TypeInfo TI = getTypeInfoImpl(T);
1435 MemoizedTypeInfo[T] = TI;
1439 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1440 /// method does not work on incomplete types.
1442 /// FIXME: Pointers into different addr spaces could have different sizes and
1443 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1444 /// should take a QualType, &c.
1445 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1448 bool AlignIsRequired = false;
1449 switch (T->getTypeClass()) {
1450 #define TYPE(Class, Base)
1451 #define ABSTRACT_TYPE(Class, Base)
1452 #define NON_CANONICAL_TYPE(Class, Base)
1453 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1454 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1456 assert(!T->isDependentType() && "should not see dependent types here"); \
1457 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1458 #include "clang/AST/TypeNodes.def"
1459 llvm_unreachable("Should not see dependent types");
1461 case Type::FunctionNoProto:
1462 case Type::FunctionProto:
1463 // GCC extension: alignof(function) = 32 bits
1468 case Type::IncompleteArray:
1469 case Type::VariableArray:
1471 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1474 case Type::ConstantArray: {
1475 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1477 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1478 uint64_t Size = CAT->getSize().getZExtValue();
1479 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1480 "Overflow in array type bit size evaluation");
1481 Width = EltInfo.Width * Size;
1482 Align = EltInfo.Align;
1483 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1484 getTargetInfo().getPointerWidth(0) == 64)
1485 Width = llvm::RoundUpToAlignment(Width, Align);
1488 case Type::ExtVector:
1489 case Type::Vector: {
1490 const VectorType *VT = cast<VectorType>(T);
1491 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1492 Width = EltInfo.Width * VT->getNumElements();
1494 // If the alignment is not a power of 2, round up to the next power of 2.
1495 // This happens for non-power-of-2 length vectors.
1496 if (Align & (Align-1)) {
1497 Align = llvm::NextPowerOf2(Align);
1498 Width = llvm::RoundUpToAlignment(Width, Align);
1500 // Adjust the alignment based on the target max.
1501 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1502 if (TargetVectorAlign && TargetVectorAlign < Align)
1503 Align = TargetVectorAlign;
1508 switch (cast<BuiltinType>(T)->getKind()) {
1509 default: llvm_unreachable("Unknown builtin type!");
1510 case BuiltinType::Void:
1511 // GCC extension: alignof(void) = 8 bits.
1516 case BuiltinType::Bool:
1517 Width = Target->getBoolWidth();
1518 Align = Target->getBoolAlign();
1520 case BuiltinType::Char_S:
1521 case BuiltinType::Char_U:
1522 case BuiltinType::UChar:
1523 case BuiltinType::SChar:
1524 Width = Target->getCharWidth();
1525 Align = Target->getCharAlign();
1527 case BuiltinType::WChar_S:
1528 case BuiltinType::WChar_U:
1529 Width = Target->getWCharWidth();
1530 Align = Target->getWCharAlign();
1532 case BuiltinType::Char16:
1533 Width = Target->getChar16Width();
1534 Align = Target->getChar16Align();
1536 case BuiltinType::Char32:
1537 Width = Target->getChar32Width();
1538 Align = Target->getChar32Align();
1540 case BuiltinType::UShort:
1541 case BuiltinType::Short:
1542 Width = Target->getShortWidth();
1543 Align = Target->getShortAlign();
1545 case BuiltinType::UInt:
1546 case BuiltinType::Int:
1547 Width = Target->getIntWidth();
1548 Align = Target->getIntAlign();
1550 case BuiltinType::ULong:
1551 case BuiltinType::Long:
1552 Width = Target->getLongWidth();
1553 Align = Target->getLongAlign();
1555 case BuiltinType::ULongLong:
1556 case BuiltinType::LongLong:
1557 Width = Target->getLongLongWidth();
1558 Align = Target->getLongLongAlign();
1560 case BuiltinType::Int128:
1561 case BuiltinType::UInt128:
1563 Align = 128; // int128_t is 128-bit aligned on all targets.
1565 case BuiltinType::Half:
1566 Width = Target->getHalfWidth();
1567 Align = Target->getHalfAlign();
1569 case BuiltinType::Float:
1570 Width = Target->getFloatWidth();
1571 Align = Target->getFloatAlign();
1573 case BuiltinType::Double:
1574 Width = Target->getDoubleWidth();
1575 Align = Target->getDoubleAlign();
1577 case BuiltinType::LongDouble:
1578 Width = Target->getLongDoubleWidth();
1579 Align = Target->getLongDoubleAlign();
1581 case BuiltinType::NullPtr:
1582 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1583 Align = Target->getPointerAlign(0); // == sizeof(void*)
1585 case BuiltinType::ObjCId:
1586 case BuiltinType::ObjCClass:
1587 case BuiltinType::ObjCSel:
1588 Width = Target->getPointerWidth(0);
1589 Align = Target->getPointerAlign(0);
1591 case BuiltinType::OCLSampler:
1592 // Samplers are modeled as integers.
1593 Width = Target->getIntWidth();
1594 Align = Target->getIntAlign();
1596 case BuiltinType::OCLEvent:
1597 case BuiltinType::OCLImage1d:
1598 case BuiltinType::OCLImage1dArray:
1599 case BuiltinType::OCLImage1dBuffer:
1600 case BuiltinType::OCLImage2d:
1601 case BuiltinType::OCLImage2dArray:
1602 case BuiltinType::OCLImage3d:
1603 // Currently these types are pointers to opaque types.
1604 Width = Target->getPointerWidth(0);
1605 Align = Target->getPointerAlign(0);
1609 case Type::ObjCObjectPointer:
1610 Width = Target->getPointerWidth(0);
1611 Align = Target->getPointerAlign(0);
1613 case Type::BlockPointer: {
1614 unsigned AS = getTargetAddressSpace(
1615 cast<BlockPointerType>(T)->getPointeeType());
1616 Width = Target->getPointerWidth(AS);
1617 Align = Target->getPointerAlign(AS);
1620 case Type::LValueReference:
1621 case Type::RValueReference: {
1622 // alignof and sizeof should never enter this code path here, so we go
1623 // the pointer route.
1624 unsigned AS = getTargetAddressSpace(
1625 cast<ReferenceType>(T)->getPointeeType());
1626 Width = Target->getPointerWidth(AS);
1627 Align = Target->getPointerAlign(AS);
1630 case Type::Pointer: {
1631 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1632 Width = Target->getPointerWidth(AS);
1633 Align = Target->getPointerAlign(AS);
1636 case Type::MemberPointer: {
1637 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1638 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1641 case Type::Complex: {
1642 // Complex types have the same alignment as their elements, but twice the
1644 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1645 Width = EltInfo.Width * 2;
1646 Align = EltInfo.Align;
1649 case Type::ObjCObject:
1650 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1651 case Type::Adjusted:
1653 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1654 case Type::ObjCInterface: {
1655 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1656 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1657 Width = toBits(Layout.getSize());
1658 Align = toBits(Layout.getAlignment());
1663 const TagType *TT = cast<TagType>(T);
1665 if (TT->getDecl()->isInvalidDecl()) {
1671 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1672 return getTypeInfo(ET->getDecl()->getIntegerType());
1674 const RecordType *RT = cast<RecordType>(TT);
1675 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1676 Width = toBits(Layout.getSize());
1677 Align = toBits(Layout.getAlignment());
1681 case Type::SubstTemplateTypeParm:
1682 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1683 getReplacementType().getTypePtr());
1686 const AutoType *A = cast<AutoType>(T);
1687 assert(!A->getDeducedType().isNull() &&
1688 "cannot request the size of an undeduced or dependent auto type");
1689 return getTypeInfo(A->getDeducedType().getTypePtr());
1693 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1695 case Type::Typedef: {
1696 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1697 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1698 // If the typedef has an aligned attribute on it, it overrides any computed
1699 // alignment we have. This violates the GCC documentation (which says that
1700 // attribute(aligned) can only round up) but matches its implementation.
1701 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1703 AlignIsRequired = true;
1706 AlignIsRequired = Info.AlignIsRequired;
1712 case Type::Elaborated:
1713 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1715 case Type::Attributed:
1717 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1719 case Type::Atomic: {
1720 // Start with the base type information.
1721 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1725 // If the size of the type doesn't exceed the platform's max
1726 // atomic promotion width, make the size and alignment more
1727 // favorable to atomic operations:
1728 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1729 // Round the size up to a power of 2.
1730 if (!llvm::isPowerOf2_64(Width))
1731 Width = llvm::NextPowerOf2(Width);
1733 // Set the alignment equal to the size.
1734 Align = static_cast<unsigned>(Width);
1740 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1741 return TypeInfo(Width, Align, AlignIsRequired);
1744 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1745 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1746 return CharUnits::fromQuantity(BitSize / getCharWidth());
1749 /// toBits - Convert a size in characters to a size in characters.
1750 int64_t ASTContext::toBits(CharUnits CharSize) const {
1751 return CharSize.getQuantity() * getCharWidth();
1754 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1755 /// This method does not work on incomplete types.
1756 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1757 return getTypeInfoInChars(T).first;
1759 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1760 return getTypeInfoInChars(T).first;
1763 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1764 /// characters. This method does not work on incomplete types.
1765 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1766 return toCharUnitsFromBits(getTypeAlign(T));
1768 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1769 return toCharUnitsFromBits(getTypeAlign(T));
1772 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1773 /// type for the current target in bits. This can be different than the ABI
1774 /// alignment in cases where it is beneficial for performance to overalign
1776 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1777 TypeInfo TI = getTypeInfo(T);
1778 unsigned ABIAlign = TI.Align;
1780 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1781 return ABIAlign; // Never overalign on XCore.
1783 // Double and long long should be naturally aligned if possible.
1784 T = T->getBaseElementTypeUnsafe();
1785 if (const ComplexType *CT = T->getAs<ComplexType>())
1786 T = CT->getElementType().getTypePtr();
1787 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1788 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1789 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1790 // Don't increase the alignment if an alignment attribute was specified on a
1791 // typedef declaration.
1792 if (!TI.AlignIsRequired)
1793 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1798 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1799 /// to a global variable of the specified type.
1800 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1801 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1804 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1805 /// should be given to a global variable of the specified type.
1806 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1807 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1810 /// DeepCollectObjCIvars -
1811 /// This routine first collects all declared, but not synthesized, ivars in
1812 /// super class and then collects all ivars, including those synthesized for
1813 /// current class. This routine is used for implementation of current class
1814 /// when all ivars, declared and synthesized are known.
1816 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1818 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1819 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1820 DeepCollectObjCIvars(SuperClass, false, Ivars);
1822 for (const auto *I : OI->ivars())
1825 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1826 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1827 Iv= Iv->getNextIvar())
1828 Ivars.push_back(Iv);
1832 /// CollectInheritedProtocols - Collect all protocols in current class and
1833 /// those inherited by it.
1834 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1835 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1836 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1837 // We can use protocol_iterator here instead of
1838 // all_referenced_protocol_iterator since we are walking all categories.
1839 for (auto *Proto : OI->all_referenced_protocols()) {
1840 Protocols.insert(Proto->getCanonicalDecl());
1841 for (auto *P : Proto->protocols()) {
1842 Protocols.insert(P->getCanonicalDecl());
1843 CollectInheritedProtocols(P, Protocols);
1847 // Categories of this Interface.
1848 for (const auto *Cat : OI->visible_categories())
1849 CollectInheritedProtocols(Cat, Protocols);
1851 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1853 CollectInheritedProtocols(SD, Protocols);
1854 SD = SD->getSuperClass();
1856 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1857 for (auto *Proto : OC->protocols()) {
1858 Protocols.insert(Proto->getCanonicalDecl());
1859 for (const auto *P : Proto->protocols())
1860 CollectInheritedProtocols(P, Protocols);
1862 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1863 for (auto *Proto : OP->protocols()) {
1864 Protocols.insert(Proto->getCanonicalDecl());
1865 for (const auto *P : Proto->protocols())
1866 CollectInheritedProtocols(P, Protocols);
1871 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1873 // Count ivars declared in class extension.
1874 for (const auto *Ext : OI->known_extensions())
1875 count += Ext->ivar_size();
1877 // Count ivar defined in this class's implementation. This
1878 // includes synthesized ivars.
1879 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1880 count += ImplDecl->ivar_size();
1885 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1889 // nullptr_t is always treated as null.
1890 if (E->getType()->isNullPtrType()) return true;
1892 if (E->getType()->isAnyPointerType() &&
1893 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1894 Expr::NPC_ValueDependentIsNull))
1897 // Unfortunately, __null has type 'int'.
1898 if (isa<GNUNullExpr>(E)) return true;
1903 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1904 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1905 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1906 I = ObjCImpls.find(D);
1907 if (I != ObjCImpls.end())
1908 return cast<ObjCImplementationDecl>(I->second);
1911 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1912 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1913 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1914 I = ObjCImpls.find(D);
1915 if (I != ObjCImpls.end())
1916 return cast<ObjCCategoryImplDecl>(I->second);
1920 /// \brief Set the implementation of ObjCInterfaceDecl.
1921 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1922 ObjCImplementationDecl *ImplD) {
1923 assert(IFaceD && ImplD && "Passed null params");
1924 ObjCImpls[IFaceD] = ImplD;
1926 /// \brief Set the implementation of ObjCCategoryDecl.
1927 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1928 ObjCCategoryImplDecl *ImplD) {
1929 assert(CatD && ImplD && "Passed null params");
1930 ObjCImpls[CatD] = ImplD;
1933 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1934 const NamedDecl *ND) const {
1935 if (const ObjCInterfaceDecl *ID =
1936 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1938 if (const ObjCCategoryDecl *CD =
1939 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1940 return CD->getClassInterface();
1941 if (const ObjCImplDecl *IMD =
1942 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1943 return IMD->getClassInterface();
1948 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1950 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1951 assert(VD && "Passed null params");
1952 assert(VD->hasAttr<BlocksAttr>() &&
1953 "getBlockVarCopyInits - not __block var");
1954 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1955 I = BlockVarCopyInits.find(VD);
1956 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
1959 /// \brief Set the copy inialization expression of a block var decl.
1960 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1961 assert(VD && Init && "Passed null params");
1962 assert(VD->hasAttr<BlocksAttr>() &&
1963 "setBlockVarCopyInits - not __block var");
1964 BlockVarCopyInits[VD] = Init;
1967 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1968 unsigned DataSize) const {
1970 DataSize = TypeLoc::getFullDataSizeForType(T);
1972 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1973 "incorrect data size provided to CreateTypeSourceInfo!");
1975 TypeSourceInfo *TInfo =
1976 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1977 new (TInfo) TypeSourceInfo(T);
1981 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1982 SourceLocation L) const {
1983 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1984 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1988 const ASTRecordLayout &
1989 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1990 return getObjCLayout(D, nullptr);
1993 const ASTRecordLayout &
1994 ASTContext::getASTObjCImplementationLayout(
1995 const ObjCImplementationDecl *D) const {
1996 return getObjCLayout(D->getClassInterface(), D);
1999 //===----------------------------------------------------------------------===//
2000 // Type creation/memoization methods
2001 //===----------------------------------------------------------------------===//
2004 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2005 unsigned fastQuals = quals.getFastQualifiers();
2006 quals.removeFastQualifiers();
2008 // Check if we've already instantiated this type.
2009 llvm::FoldingSetNodeID ID;
2010 ExtQuals::Profile(ID, baseType, quals);
2011 void *insertPos = nullptr;
2012 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2013 assert(eq->getQualifiers() == quals);
2014 return QualType(eq, fastQuals);
2017 // If the base type is not canonical, make the appropriate canonical type.
2019 if (!baseType->isCanonicalUnqualified()) {
2020 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2021 canonSplit.Quals.addConsistentQualifiers(quals);
2022 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2024 // Re-find the insert position.
2025 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2028 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2029 ExtQualNodes.InsertNode(eq, insertPos);
2030 return QualType(eq, fastQuals);
2034 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2035 QualType CanT = getCanonicalType(T);
2036 if (CanT.getAddressSpace() == AddressSpace)
2039 // If we are composing extended qualifiers together, merge together
2040 // into one ExtQuals node.
2041 QualifierCollector Quals;
2042 const Type *TypeNode = Quals.strip(T);
2044 // If this type already has an address space specified, it cannot get
2046 assert(!Quals.hasAddressSpace() &&
2047 "Type cannot be in multiple addr spaces!");
2048 Quals.addAddressSpace(AddressSpace);
2050 return getExtQualType(TypeNode, Quals);
2053 QualType ASTContext::getObjCGCQualType(QualType T,
2054 Qualifiers::GC GCAttr) const {
2055 QualType CanT = getCanonicalType(T);
2056 if (CanT.getObjCGCAttr() == GCAttr)
2059 if (const PointerType *ptr = T->getAs<PointerType>()) {
2060 QualType Pointee = ptr->getPointeeType();
2061 if (Pointee->isAnyPointerType()) {
2062 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2063 return getPointerType(ResultType);
2067 // If we are composing extended qualifiers together, merge together
2068 // into one ExtQuals node.
2069 QualifierCollector Quals;
2070 const Type *TypeNode = Quals.strip(T);
2072 // If this type already has an ObjCGC specified, it cannot get
2074 assert(!Quals.hasObjCGCAttr() &&
2075 "Type cannot have multiple ObjCGCs!");
2076 Quals.addObjCGCAttr(GCAttr);
2078 return getExtQualType(TypeNode, Quals);
2081 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2082 FunctionType::ExtInfo Info) {
2083 if (T->getExtInfo() == Info)
2087 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2088 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2090 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2093 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2096 return cast<FunctionType>(Result.getTypePtr());
2099 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2100 QualType ResultType) {
2101 FD = FD->getMostRecentDecl();
2103 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2104 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2105 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2106 if (FunctionDecl *Next = FD->getPreviousDecl())
2111 if (ASTMutationListener *L = getASTMutationListener())
2112 L->DeducedReturnType(FD, ResultType);
2115 /// Get a function type and produce the equivalent function type with the
2116 /// specified exception specification. Type sugar that can be present on a
2117 /// declaration of a function with an exception specification is permitted
2118 /// and preserved. Other type sugar (for instance, typedefs) is not.
2119 static QualType getFunctionTypeWithExceptionSpec(
2120 ASTContext &Context, QualType Orig,
2121 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2122 // Might have some parens.
2123 if (auto *PT = dyn_cast<ParenType>(Orig))
2124 return Context.getParenType(
2125 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2127 // Might have a calling-convention attribute.
2128 if (auto *AT = dyn_cast<AttributedType>(Orig))
2129 return Context.getAttributedType(
2131 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2132 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2135 // Anything else must be a function type. Rebuild it with the new exception
2137 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2138 return Context.getFunctionType(
2139 Proto->getReturnType(), Proto->getParamTypes(),
2140 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2143 void ASTContext::adjustExceptionSpec(
2144 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2148 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2149 FD->setType(Updated);
2154 // Update the type in the type source information too.
2155 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2156 // If the type and the type-as-written differ, we may need to update
2157 // the type-as-written too.
2158 if (TSInfo->getType() != FD->getType())
2159 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2161 // FIXME: When we get proper type location information for exceptions,
2162 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2163 // up the TypeSourceInfo;
2164 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2165 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2166 "TypeLoc size mismatch from updating exception specification");
2167 TSInfo->overrideType(Updated);
2171 /// getComplexType - Return the uniqued reference to the type for a complex
2172 /// number with the specified element type.
2173 QualType ASTContext::getComplexType(QualType T) const {
2174 // Unique pointers, to guarantee there is only one pointer of a particular
2176 llvm::FoldingSetNodeID ID;
2177 ComplexType::Profile(ID, T);
2179 void *InsertPos = nullptr;
2180 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2181 return QualType(CT, 0);
2183 // If the pointee type isn't canonical, this won't be a canonical type either,
2184 // so fill in the canonical type field.
2186 if (!T.isCanonical()) {
2187 Canonical = getComplexType(getCanonicalType(T));
2189 // Get the new insert position for the node we care about.
2190 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2191 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2193 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2194 Types.push_back(New);
2195 ComplexTypes.InsertNode(New, InsertPos);
2196 return QualType(New, 0);
2199 /// getPointerType - Return the uniqued reference to the type for a pointer to
2200 /// the specified type.
2201 QualType ASTContext::getPointerType(QualType T) const {
2202 // Unique pointers, to guarantee there is only one pointer of a particular
2204 llvm::FoldingSetNodeID ID;
2205 PointerType::Profile(ID, T);
2207 void *InsertPos = nullptr;
2208 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2209 return QualType(PT, 0);
2211 // If the pointee type isn't canonical, this won't be a canonical type either,
2212 // so fill in the canonical type field.
2214 if (!T.isCanonical()) {
2215 Canonical = getPointerType(getCanonicalType(T));
2217 // Get the new insert position for the node we care about.
2218 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2219 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2221 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2222 Types.push_back(New);
2223 PointerTypes.InsertNode(New, InsertPos);
2224 return QualType(New, 0);
2227 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2228 llvm::FoldingSetNodeID ID;
2229 AdjustedType::Profile(ID, Orig, New);
2230 void *InsertPos = nullptr;
2231 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2233 return QualType(AT, 0);
2235 QualType Canonical = getCanonicalType(New);
2237 // Get the new insert position for the node we care about.
2238 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2239 assert(!AT && "Shouldn't be in the map!");
2241 AT = new (*this, TypeAlignment)
2242 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2243 Types.push_back(AT);
2244 AdjustedTypes.InsertNode(AT, InsertPos);
2245 return QualType(AT, 0);
2248 QualType ASTContext::getDecayedType(QualType T) const {
2249 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2254 // A declaration of a parameter as "array of type" shall be
2255 // adjusted to "qualified pointer to type", where the type
2256 // qualifiers (if any) are those specified within the [ and ] of
2257 // the array type derivation.
2258 if (T->isArrayType())
2259 Decayed = getArrayDecayedType(T);
2262 // A declaration of a parameter as "function returning type"
2263 // shall be adjusted to "pointer to function returning type", as
2265 if (T->isFunctionType())
2266 Decayed = getPointerType(T);
2268 llvm::FoldingSetNodeID ID;
2269 AdjustedType::Profile(ID, T, Decayed);
2270 void *InsertPos = nullptr;
2271 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2273 return QualType(AT, 0);
2275 QualType Canonical = getCanonicalType(Decayed);
2277 // Get the new insert position for the node we care about.
2278 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2279 assert(!AT && "Shouldn't be in the map!");
2281 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2282 Types.push_back(AT);
2283 AdjustedTypes.InsertNode(AT, InsertPos);
2284 return QualType(AT, 0);
2287 /// getBlockPointerType - Return the uniqued reference to the type for
2288 /// a pointer to the specified block.
2289 QualType ASTContext::getBlockPointerType(QualType T) const {
2290 assert(T->isFunctionType() && "block of function types only");
2291 // Unique pointers, to guarantee there is only one block of a particular
2293 llvm::FoldingSetNodeID ID;
2294 BlockPointerType::Profile(ID, T);
2296 void *InsertPos = nullptr;
2297 if (BlockPointerType *PT =
2298 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2299 return QualType(PT, 0);
2301 // If the block pointee type isn't canonical, this won't be a canonical
2302 // type either so fill in the canonical type field.
2304 if (!T.isCanonical()) {
2305 Canonical = getBlockPointerType(getCanonicalType(T));
2307 // Get the new insert position for the node we care about.
2308 BlockPointerType *NewIP =
2309 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2310 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2312 BlockPointerType *New
2313 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2314 Types.push_back(New);
2315 BlockPointerTypes.InsertNode(New, InsertPos);
2316 return QualType(New, 0);
2319 /// getLValueReferenceType - Return the uniqued reference to the type for an
2320 /// lvalue reference to the specified type.
2322 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2323 assert(getCanonicalType(T) != OverloadTy &&
2324 "Unresolved overloaded function type");
2326 // Unique pointers, to guarantee there is only one pointer of a particular
2328 llvm::FoldingSetNodeID ID;
2329 ReferenceType::Profile(ID, T, SpelledAsLValue);
2331 void *InsertPos = nullptr;
2332 if (LValueReferenceType *RT =
2333 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2334 return QualType(RT, 0);
2336 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2338 // If the referencee type isn't canonical, this won't be a canonical type
2339 // either, so fill in the canonical type field.
2341 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2342 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2343 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2345 // Get the new insert position for the node we care about.
2346 LValueReferenceType *NewIP =
2347 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2348 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2351 LValueReferenceType *New
2352 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2354 Types.push_back(New);
2355 LValueReferenceTypes.InsertNode(New, InsertPos);
2357 return QualType(New, 0);
2360 /// getRValueReferenceType - Return the uniqued reference to the type for an
2361 /// rvalue reference to the specified type.
2362 QualType ASTContext::getRValueReferenceType(QualType T) const {
2363 // Unique pointers, to guarantee there is only one pointer of a particular
2365 llvm::FoldingSetNodeID ID;
2366 ReferenceType::Profile(ID, T, false);
2368 void *InsertPos = nullptr;
2369 if (RValueReferenceType *RT =
2370 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2371 return QualType(RT, 0);
2373 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2375 // If the referencee type isn't canonical, this won't be a canonical type
2376 // either, so fill in the canonical type field.
2378 if (InnerRef || !T.isCanonical()) {
2379 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2380 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2382 // Get the new insert position for the node we care about.
2383 RValueReferenceType *NewIP =
2384 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2385 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2388 RValueReferenceType *New
2389 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2390 Types.push_back(New);
2391 RValueReferenceTypes.InsertNode(New, InsertPos);
2392 return QualType(New, 0);
2395 /// getMemberPointerType - Return the uniqued reference to the type for a
2396 /// member pointer to the specified type, in the specified class.
2397 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2398 // Unique pointers, to guarantee there is only one pointer of a particular
2400 llvm::FoldingSetNodeID ID;
2401 MemberPointerType::Profile(ID, T, Cls);
2403 void *InsertPos = nullptr;
2404 if (MemberPointerType *PT =
2405 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2406 return QualType(PT, 0);
2408 // If the pointee or class type isn't canonical, this won't be a canonical
2409 // type either, so fill in the canonical type field.
2411 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2412 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2414 // Get the new insert position for the node we care about.
2415 MemberPointerType *NewIP =
2416 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2417 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2419 MemberPointerType *New
2420 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2421 Types.push_back(New);
2422 MemberPointerTypes.InsertNode(New, InsertPos);
2423 return QualType(New, 0);
2426 /// getConstantArrayType - Return the unique reference to the type for an
2427 /// array of the specified element type.
2428 QualType ASTContext::getConstantArrayType(QualType EltTy,
2429 const llvm::APInt &ArySizeIn,
2430 ArrayType::ArraySizeModifier ASM,
2431 unsigned IndexTypeQuals) const {
2432 assert((EltTy->isDependentType() ||
2433 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2434 "Constant array of VLAs is illegal!");
2436 // Convert the array size into a canonical width matching the pointer size for
2438 llvm::APInt ArySize(ArySizeIn);
2440 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2442 llvm::FoldingSetNodeID ID;
2443 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2445 void *InsertPos = nullptr;
2446 if (ConstantArrayType *ATP =
2447 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2448 return QualType(ATP, 0);
2450 // If the element type isn't canonical or has qualifiers, this won't
2451 // be a canonical type either, so fill in the canonical type field.
2453 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2454 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2455 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2456 ASM, IndexTypeQuals);
2457 Canon = getQualifiedType(Canon, canonSplit.Quals);
2459 // Get the new insert position for the node we care about.
2460 ConstantArrayType *NewIP =
2461 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2462 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2465 ConstantArrayType *New = new(*this,TypeAlignment)
2466 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2467 ConstantArrayTypes.InsertNode(New, InsertPos);
2468 Types.push_back(New);
2469 return QualType(New, 0);
2472 /// getVariableArrayDecayedType - Turns the given type, which may be
2473 /// variably-modified, into the corresponding type with all the known
2474 /// sizes replaced with [*].
2475 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2476 // Vastly most common case.
2477 if (!type->isVariablyModifiedType()) return type;
2481 SplitQualType split = type.getSplitDesugaredType();
2482 const Type *ty = split.Ty;
2483 switch (ty->getTypeClass()) {
2484 #define TYPE(Class, Base)
2485 #define ABSTRACT_TYPE(Class, Base)
2486 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2487 #include "clang/AST/TypeNodes.def"
2488 llvm_unreachable("didn't desugar past all non-canonical types?");
2490 // These types should never be variably-modified.
2494 case Type::ExtVector:
2495 case Type::DependentSizedExtVector:
2496 case Type::ObjCObject:
2497 case Type::ObjCInterface:
2498 case Type::ObjCObjectPointer:
2501 case Type::UnresolvedUsing:
2502 case Type::TypeOfExpr:
2504 case Type::Decltype:
2505 case Type::UnaryTransform:
2506 case Type::DependentName:
2507 case Type::InjectedClassName:
2508 case Type::TemplateSpecialization:
2509 case Type::DependentTemplateSpecialization:
2510 case Type::TemplateTypeParm:
2511 case Type::SubstTemplateTypeParmPack:
2513 case Type::PackExpansion:
2514 llvm_unreachable("type should never be variably-modified");
2516 // These types can be variably-modified but should never need to
2518 case Type::FunctionNoProto:
2519 case Type::FunctionProto:
2520 case Type::BlockPointer:
2521 case Type::MemberPointer:
2524 // These types can be variably-modified. All these modifications
2525 // preserve structure except as noted by comments.
2526 // TODO: if we ever care about optimizing VLAs, there are no-op
2527 // optimizations available here.
2529 result = getPointerType(getVariableArrayDecayedType(
2530 cast<PointerType>(ty)->getPointeeType()));
2533 case Type::LValueReference: {
2534 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2535 result = getLValueReferenceType(
2536 getVariableArrayDecayedType(lv->getPointeeType()),
2537 lv->isSpelledAsLValue());
2541 case Type::RValueReference: {
2542 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2543 result = getRValueReferenceType(
2544 getVariableArrayDecayedType(lv->getPointeeType()));
2548 case Type::Atomic: {
2549 const AtomicType *at = cast<AtomicType>(ty);
2550 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2554 case Type::ConstantArray: {
2555 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2556 result = getConstantArrayType(
2557 getVariableArrayDecayedType(cat->getElementType()),
2559 cat->getSizeModifier(),
2560 cat->getIndexTypeCVRQualifiers());
2564 case Type::DependentSizedArray: {
2565 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2566 result = getDependentSizedArrayType(
2567 getVariableArrayDecayedType(dat->getElementType()),
2569 dat->getSizeModifier(),
2570 dat->getIndexTypeCVRQualifiers(),
2571 dat->getBracketsRange());
2575 // Turn incomplete types into [*] types.
2576 case Type::IncompleteArray: {
2577 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2578 result = getVariableArrayType(
2579 getVariableArrayDecayedType(iat->getElementType()),
2582 iat->getIndexTypeCVRQualifiers(),
2587 // Turn VLA types into [*] types.
2588 case Type::VariableArray: {
2589 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2590 result = getVariableArrayType(
2591 getVariableArrayDecayedType(vat->getElementType()),
2594 vat->getIndexTypeCVRQualifiers(),
2595 vat->getBracketsRange());
2600 // Apply the top-level qualifiers from the original.
2601 return getQualifiedType(result, split.Quals);
2604 /// getVariableArrayType - Returns a non-unique reference to the type for a
2605 /// variable array of the specified element type.
2606 QualType ASTContext::getVariableArrayType(QualType EltTy,
2608 ArrayType::ArraySizeModifier ASM,
2609 unsigned IndexTypeQuals,
2610 SourceRange Brackets) const {
2611 // Since we don't unique expressions, it isn't possible to unique VLA's
2612 // that have an expression provided for their size.
2615 // Be sure to pull qualifiers off the element type.
2616 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2617 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2618 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2619 IndexTypeQuals, Brackets);
2620 Canon = getQualifiedType(Canon, canonSplit.Quals);
2623 VariableArrayType *New = new(*this, TypeAlignment)
2624 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2626 VariableArrayTypes.push_back(New);
2627 Types.push_back(New);
2628 return QualType(New, 0);
2631 /// getDependentSizedArrayType - Returns a non-unique reference to
2632 /// the type for a dependently-sized array of the specified element
2634 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2636 ArrayType::ArraySizeModifier ASM,
2637 unsigned elementTypeQuals,
2638 SourceRange brackets) const {
2639 assert((!numElements || numElements->isTypeDependent() ||
2640 numElements->isValueDependent()) &&
2641 "Size must be type- or value-dependent!");
2643 // Dependently-sized array types that do not have a specified number
2644 // of elements will have their sizes deduced from a dependent
2645 // initializer. We do no canonicalization here at all, which is okay
2646 // because they can't be used in most locations.
2648 DependentSizedArrayType *newType
2649 = new (*this, TypeAlignment)
2650 DependentSizedArrayType(*this, elementType, QualType(),
2651 numElements, ASM, elementTypeQuals,
2653 Types.push_back(newType);
2654 return QualType(newType, 0);
2657 // Otherwise, we actually build a new type every time, but we
2658 // also build a canonical type.
2660 SplitQualType canonElementType = getCanonicalType(elementType).split();
2662 void *insertPos = nullptr;
2663 llvm::FoldingSetNodeID ID;
2664 DependentSizedArrayType::Profile(ID, *this,
2665 QualType(canonElementType.Ty, 0),
2666 ASM, elementTypeQuals, numElements);
2668 // Look for an existing type with these properties.
2669 DependentSizedArrayType *canonTy =
2670 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2672 // If we don't have one, build one.
2674 canonTy = new (*this, TypeAlignment)
2675 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2676 QualType(), numElements, ASM, elementTypeQuals,
2678 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2679 Types.push_back(canonTy);
2682 // Apply qualifiers from the element type to the array.
2683 QualType canon = getQualifiedType(QualType(canonTy,0),
2684 canonElementType.Quals);
2686 // If we didn't need extra canonicalization for the element type,
2687 // then just use that as our result.
2688 if (QualType(canonElementType.Ty, 0) == elementType)
2691 // Otherwise, we need to build a type which follows the spelling
2692 // of the element type.
2693 DependentSizedArrayType *sugaredType
2694 = new (*this, TypeAlignment)
2695 DependentSizedArrayType(*this, elementType, canon, numElements,
2696 ASM, elementTypeQuals, brackets);
2697 Types.push_back(sugaredType);
2698 return QualType(sugaredType, 0);
2701 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2702 ArrayType::ArraySizeModifier ASM,
2703 unsigned elementTypeQuals) const {
2704 llvm::FoldingSetNodeID ID;
2705 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2707 void *insertPos = nullptr;
2708 if (IncompleteArrayType *iat =
2709 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2710 return QualType(iat, 0);
2712 // If the element type isn't canonical, this won't be a canonical type
2713 // either, so fill in the canonical type field. We also have to pull
2714 // qualifiers off the element type.
2717 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2718 SplitQualType canonSplit = getCanonicalType(elementType).split();
2719 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2720 ASM, elementTypeQuals);
2721 canon = getQualifiedType(canon, canonSplit.Quals);
2723 // Get the new insert position for the node we care about.
2724 IncompleteArrayType *existing =
2725 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2726 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2729 IncompleteArrayType *newType = new (*this, TypeAlignment)
2730 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2732 IncompleteArrayTypes.InsertNode(newType, insertPos);
2733 Types.push_back(newType);
2734 return QualType(newType, 0);
2737 /// getVectorType - Return the unique reference to a vector type of
2738 /// the specified element type and size. VectorType must be a built-in type.
2739 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2740 VectorType::VectorKind VecKind) const {
2741 assert(vecType->isBuiltinType());
2743 // Check if we've already instantiated a vector of this type.
2744 llvm::FoldingSetNodeID ID;
2745 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2747 void *InsertPos = nullptr;
2748 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2749 return QualType(VTP, 0);
2751 // If the element type isn't canonical, this won't be a canonical type either,
2752 // so fill in the canonical type field.
2754 if (!vecType.isCanonical()) {
2755 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2757 // Get the new insert position for the node we care about.
2758 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2759 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2761 VectorType *New = new (*this, TypeAlignment)
2762 VectorType(vecType, NumElts, Canonical, VecKind);
2763 VectorTypes.InsertNode(New, InsertPos);
2764 Types.push_back(New);
2765 return QualType(New, 0);
2768 /// getExtVectorType - Return the unique reference to an extended vector type of
2769 /// the specified element type and size. VectorType must be a built-in type.
2771 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2772 assert(vecType->isBuiltinType() || vecType->isDependentType());
2774 // Check if we've already instantiated a vector of this type.
2775 llvm::FoldingSetNodeID ID;
2776 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2777 VectorType::GenericVector);
2778 void *InsertPos = nullptr;
2779 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2780 return QualType(VTP, 0);
2782 // If the element type isn't canonical, this won't be a canonical type either,
2783 // so fill in the canonical type field.
2785 if (!vecType.isCanonical()) {
2786 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2788 // Get the new insert position for the node we care about.
2789 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2790 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2792 ExtVectorType *New = new (*this, TypeAlignment)
2793 ExtVectorType(vecType, NumElts, Canonical);
2794 VectorTypes.InsertNode(New, InsertPos);
2795 Types.push_back(New);
2796 return QualType(New, 0);
2800 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2802 SourceLocation AttrLoc) const {
2803 llvm::FoldingSetNodeID ID;
2804 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2807 void *InsertPos = nullptr;
2808 DependentSizedExtVectorType *Canon
2809 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2810 DependentSizedExtVectorType *New;
2812 // We already have a canonical version of this array type; use it as
2813 // the canonical type for a newly-built type.
2814 New = new (*this, TypeAlignment)
2815 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2818 QualType CanonVecTy = getCanonicalType(vecType);
2819 if (CanonVecTy == vecType) {
2820 New = new (*this, TypeAlignment)
2821 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2824 DependentSizedExtVectorType *CanonCheck
2825 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2826 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2828 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2830 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2832 New = new (*this, TypeAlignment)
2833 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2837 Types.push_back(New);
2838 return QualType(New, 0);
2841 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2844 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2845 const FunctionType::ExtInfo &Info) const {
2846 const CallingConv CallConv = Info.getCC();
2848 // Unique functions, to guarantee there is only one function of a particular
2850 llvm::FoldingSetNodeID ID;
2851 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2853 void *InsertPos = nullptr;
2854 if (FunctionNoProtoType *FT =
2855 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2856 return QualType(FT, 0);
2859 if (!ResultTy.isCanonical()) {
2860 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2862 // Get the new insert position for the node we care about.
2863 FunctionNoProtoType *NewIP =
2864 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2868 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2869 FunctionNoProtoType *New = new (*this, TypeAlignment)
2870 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2871 Types.push_back(New);
2872 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2873 return QualType(New, 0);
2876 /// \brief Determine whether \p T is canonical as the result type of a function.
2877 static bool isCanonicalResultType(QualType T) {
2878 return T.isCanonical() &&
2879 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2880 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2884 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2885 const FunctionProtoType::ExtProtoInfo &EPI) const {
2886 size_t NumArgs = ArgArray.size();
2888 // Unique functions, to guarantee there is only one function of a particular
2890 llvm::FoldingSetNodeID ID;
2891 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2894 void *InsertPos = nullptr;
2895 if (FunctionProtoType *FTP =
2896 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2897 return QualType(FTP, 0);
2899 // Determine whether the type being created is already canonical or not.
2901 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
2902 !EPI.HasTrailingReturn;
2903 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2904 if (!ArgArray[i].isCanonicalAsParam())
2905 isCanonical = false;
2907 // If this type isn't canonical, get the canonical version of it.
2908 // The exception spec is not part of the canonical type.
2911 SmallVector<QualType, 16> CanonicalArgs;
2912 CanonicalArgs.reserve(NumArgs);
2913 for (unsigned i = 0; i != NumArgs; ++i)
2914 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2916 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2917 CanonicalEPI.HasTrailingReturn = false;
2918 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
2920 // Result types do not have ARC lifetime qualifiers.
2921 QualType CanResultTy = getCanonicalType(ResultTy);
2922 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2923 Qualifiers Qs = CanResultTy.getQualifiers();
2924 Qs.removeObjCLifetime();
2925 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2928 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2930 // Get the new insert position for the node we care about.
2931 FunctionProtoType *NewIP =
2932 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2936 // FunctionProtoType objects are allocated with extra bytes after
2937 // them for three variable size arrays at the end:
2938 // - parameter types
2939 // - exception types
2940 // - consumed-arguments flags
2941 // Instead of the exception types, there could be a noexcept
2942 // expression, or information used to resolve the exception
2944 size_t Size = sizeof(FunctionProtoType) +
2945 NumArgs * sizeof(QualType);
2946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2947 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2948 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
2949 Size += sizeof(Expr*);
2950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
2951 Size += 2 * sizeof(FunctionDecl*);
2952 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
2953 Size += sizeof(FunctionDecl*);
2955 if (EPI.ConsumedParameters)
2956 Size += NumArgs * sizeof(bool);
2958 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2959 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2960 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2961 Types.push_back(FTP);
2962 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2963 return QualType(FTP, 0);
2967 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2968 if (!isa<CXXRecordDecl>(D)) return false;
2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2970 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2972 if (RD->getDescribedClassTemplate() &&
2973 !isa<ClassTemplateSpecializationDecl>(RD))
2979 /// getInjectedClassNameType - Return the unique reference to the
2980 /// injected class name type for the specified templated declaration.
2981 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2982 QualType TST) const {
2983 assert(NeedsInjectedClassNameType(Decl));
2984 if (Decl->TypeForDecl) {
2985 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2986 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2987 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2988 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2989 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2992 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2993 Decl->TypeForDecl = newType;
2994 Types.push_back(newType);
2996 return QualType(Decl->TypeForDecl, 0);
2999 /// getTypeDeclType - Return the unique reference to the type for the
3000 /// specified type declaration.
3001 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3002 assert(Decl && "Passed null for Decl param");
3003 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3005 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3006 return getTypedefType(Typedef);
3008 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3009 "Template type parameter types are always available.");
3011 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3012 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3013 assert(!NeedsInjectedClassNameType(Record));
3014 return getRecordType(Record);
3015 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3016 assert(Enum->isFirstDecl() && "enum has previous declaration");
3017 return getEnumType(Enum);
3018 } else if (const UnresolvedUsingTypenameDecl *Using =
3019 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3020 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3021 Decl->TypeForDecl = newType;
3022 Types.push_back(newType);
3024 llvm_unreachable("TypeDecl without a type?");
3026 return QualType(Decl->TypeForDecl, 0);
3029 /// getTypedefType - Return the unique reference to the type for the
3030 /// specified typedef name decl.
3032 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3033 QualType Canonical) const {
3034 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3036 if (Canonical.isNull())
3037 Canonical = getCanonicalType(Decl->getUnderlyingType());
3038 TypedefType *newType = new(*this, TypeAlignment)
3039 TypedefType(Type::Typedef, Decl, Canonical);
3040 Decl->TypeForDecl = newType;
3041 Types.push_back(newType);
3042 return QualType(newType, 0);
3045 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3048 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3049 if (PrevDecl->TypeForDecl)
3050 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3052 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3053 Decl->TypeForDecl = newType;
3054 Types.push_back(newType);
3055 return QualType(newType, 0);
3058 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3059 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3061 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3062 if (PrevDecl->TypeForDecl)
3063 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3065 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3066 Decl->TypeForDecl = newType;
3067 Types.push_back(newType);
3068 return QualType(newType, 0);
3071 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3072 QualType modifiedType,
3073 QualType equivalentType) {
3074 llvm::FoldingSetNodeID id;
3075 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3077 void *insertPos = nullptr;
3078 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3079 if (type) return QualType(type, 0);
3081 QualType canon = getCanonicalType(equivalentType);
3082 type = new (*this, TypeAlignment)
3083 AttributedType(canon, attrKind, modifiedType, equivalentType);
3085 Types.push_back(type);
3086 AttributedTypes.InsertNode(type, insertPos);
3088 return QualType(type, 0);
3092 /// \brief Retrieve a substitution-result type.
3094 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3095 QualType Replacement) const {
3096 assert(Replacement.isCanonical()
3097 && "replacement types must always be canonical");
3099 llvm::FoldingSetNodeID ID;
3100 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3101 void *InsertPos = nullptr;
3102 SubstTemplateTypeParmType *SubstParm
3103 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3106 SubstParm = new (*this, TypeAlignment)
3107 SubstTemplateTypeParmType(Parm, Replacement);
3108 Types.push_back(SubstParm);
3109 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3112 return QualType(SubstParm, 0);
3115 /// \brief Retrieve a
3116 QualType ASTContext::getSubstTemplateTypeParmPackType(
3117 const TemplateTypeParmType *Parm,
3118 const TemplateArgument &ArgPack) {
3120 for (const auto &P : ArgPack.pack_elements()) {
3121 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3122 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3126 llvm::FoldingSetNodeID ID;
3127 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3128 void *InsertPos = nullptr;
3129 if (SubstTemplateTypeParmPackType *SubstParm
3130 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3131 return QualType(SubstParm, 0);
3134 if (!Parm->isCanonicalUnqualified()) {
3135 Canon = getCanonicalType(QualType(Parm, 0));
3136 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3138 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3141 SubstTemplateTypeParmPackType *SubstParm
3142 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3144 Types.push_back(SubstParm);
3145 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3146 return QualType(SubstParm, 0);
3149 /// \brief Retrieve the template type parameter type for a template
3150 /// parameter or parameter pack with the given depth, index, and (optionally)
3152 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3154 TemplateTypeParmDecl *TTPDecl) const {
3155 llvm::FoldingSetNodeID ID;
3156 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3157 void *InsertPos = nullptr;
3158 TemplateTypeParmType *TypeParm
3159 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3162 return QualType(TypeParm, 0);
3165 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3166 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3168 TemplateTypeParmType *TypeCheck
3169 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3170 assert(!TypeCheck && "Template type parameter canonical type broken");
3173 TypeParm = new (*this, TypeAlignment)
3174 TemplateTypeParmType(Depth, Index, ParameterPack);
3176 Types.push_back(TypeParm);
3177 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3179 return QualType(TypeParm, 0);
3183 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3184 SourceLocation NameLoc,
3185 const TemplateArgumentListInfo &Args,
3186 QualType Underlying) const {
3187 assert(!Name.getAsDependentTemplateName() &&
3188 "No dependent template names here!");
3189 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3191 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3192 TemplateSpecializationTypeLoc TL =
3193 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3194 TL.setTemplateKeywordLoc(SourceLocation());
3195 TL.setTemplateNameLoc(NameLoc);
3196 TL.setLAngleLoc(Args.getLAngleLoc());
3197 TL.setRAngleLoc(Args.getRAngleLoc());
3198 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3199 TL.setArgLocInfo(i, Args[i].getLocInfo());
3204 ASTContext::getTemplateSpecializationType(TemplateName Template,
3205 const TemplateArgumentListInfo &Args,
3206 QualType Underlying) const {
3207 assert(!Template.getAsDependentTemplateName() &&
3208 "No dependent template names here!");
3210 unsigned NumArgs = Args.size();
3212 SmallVector<TemplateArgument, 4> ArgVec;
3213 ArgVec.reserve(NumArgs);
3214 for (unsigned i = 0; i != NumArgs; ++i)
3215 ArgVec.push_back(Args[i].getArgument());
3217 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3222 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3224 for (unsigned I = 0; I != NumArgs; ++I)
3225 if (Args[I].isPackExpansion())
3233 ASTContext::getTemplateSpecializationType(TemplateName Template,
3234 const TemplateArgument *Args,
3236 QualType Underlying) const {
3237 assert(!Template.getAsDependentTemplateName() &&
3238 "No dependent template names here!");
3239 // Look through qualified template names.
3240 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3241 Template = TemplateName(QTN->getTemplateDecl());
3244 Template.getAsTemplateDecl() &&
3245 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3247 if (!Underlying.isNull())
3248 CanonType = getCanonicalType(Underlying);
3250 // We can get here with an alias template when the specialization contains
3251 // a pack expansion that does not match up with a parameter pack.
3252 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3253 "Caller must compute aliased type");
3254 IsTypeAlias = false;
3255 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3259 // Allocate the (non-canonical) template specialization type, but don't
3260 // try to unique it: these types typically have location information that
3261 // we don't unique and don't want to lose.
3262 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3263 sizeof(TemplateArgument) * NumArgs +
3264 (IsTypeAlias? sizeof(QualType) : 0),
3266 TemplateSpecializationType *Spec
3267 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3268 IsTypeAlias ? Underlying : QualType());
3270 Types.push_back(Spec);
3271 return QualType(Spec, 0);
3275 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3276 const TemplateArgument *Args,
3277 unsigned NumArgs) const {
3278 assert(!Template.getAsDependentTemplateName() &&
3279 "No dependent template names here!");
3281 // Look through qualified template names.
3282 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3283 Template = TemplateName(QTN->getTemplateDecl());
3285 // Build the canonical template specialization type.
3286 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3287 SmallVector<TemplateArgument, 4> CanonArgs;
3288 CanonArgs.reserve(NumArgs);
3289 for (unsigned I = 0; I != NumArgs; ++I)
3290 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3292 // Determine whether this canonical template specialization type already
3294 llvm::FoldingSetNodeID ID;
3295 TemplateSpecializationType::Profile(ID, CanonTemplate,
3296 CanonArgs.data(), NumArgs, *this);
3298 void *InsertPos = nullptr;
3299 TemplateSpecializationType *Spec
3300 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3303 // Allocate a new canonical template specialization type.
3304 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3305 sizeof(TemplateArgument) * NumArgs),
3307 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3308 CanonArgs.data(), NumArgs,
3309 QualType(), QualType());
3310 Types.push_back(Spec);
3311 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3314 assert(Spec->isDependentType() &&
3315 "Non-dependent template-id type must have a canonical type");
3316 return QualType(Spec, 0);
3320 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3321 NestedNameSpecifier *NNS,
3322 QualType NamedType) const {
3323 llvm::FoldingSetNodeID ID;
3324 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3326 void *InsertPos = nullptr;
3327 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3329 return QualType(T, 0);
3331 QualType Canon = NamedType;
3332 if (!Canon.isCanonical()) {
3333 Canon = getCanonicalType(NamedType);
3334 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3335 assert(!CheckT && "Elaborated canonical type broken");
3339 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3341 ElaboratedTypes.InsertNode(T, InsertPos);
3342 return QualType(T, 0);
3346 ASTContext::getParenType(QualType InnerType) const {
3347 llvm::FoldingSetNodeID ID;
3348 ParenType::Profile(ID, InnerType);
3350 void *InsertPos = nullptr;
3351 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3353 return QualType(T, 0);
3355 QualType Canon = InnerType;
3356 if (!Canon.isCanonical()) {
3357 Canon = getCanonicalType(InnerType);
3358 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3359 assert(!CheckT && "Paren canonical type broken");
3363 T = new (*this) ParenType(InnerType, Canon);
3365 ParenTypes.InsertNode(T, InsertPos);
3366 return QualType(T, 0);
3369 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3370 NestedNameSpecifier *NNS,
3371 const IdentifierInfo *Name,
3372 QualType Canon) const {
3373 if (Canon.isNull()) {
3374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3375 ElaboratedTypeKeyword CanonKeyword = Keyword;
3376 if (Keyword == ETK_None)
3377 CanonKeyword = ETK_Typename;
3379 if (CanonNNS != NNS || CanonKeyword != Keyword)
3380 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3383 llvm::FoldingSetNodeID ID;
3384 DependentNameType::Profile(ID, Keyword, NNS, Name);
3386 void *InsertPos = nullptr;
3387 DependentNameType *T
3388 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3390 return QualType(T, 0);
3392 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3394 DependentNameTypes.InsertNode(T, InsertPos);
3395 return QualType(T, 0);
3399 ASTContext::getDependentTemplateSpecializationType(
3400 ElaboratedTypeKeyword Keyword,
3401 NestedNameSpecifier *NNS,
3402 const IdentifierInfo *Name,
3403 const TemplateArgumentListInfo &Args) const {
3404 // TODO: avoid this copy
3405 SmallVector<TemplateArgument, 16> ArgCopy;
3406 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3407 ArgCopy.push_back(Args[I].getArgument());
3408 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3414 ASTContext::getDependentTemplateSpecializationType(
3415 ElaboratedTypeKeyword Keyword,
3416 NestedNameSpecifier *NNS,
3417 const IdentifierInfo *Name,
3419 const TemplateArgument *Args) const {
3420 assert((!NNS || NNS->isDependent()) &&
3421 "nested-name-specifier must be dependent");
3423 llvm::FoldingSetNodeID ID;
3424 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3425 Name, NumArgs, Args);
3427 void *InsertPos = nullptr;
3428 DependentTemplateSpecializationType *T
3429 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3431 return QualType(T, 0);
3433 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3435 ElaboratedTypeKeyword CanonKeyword = Keyword;
3436 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3438 bool AnyNonCanonArgs = false;
3439 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3440 for (unsigned I = 0; I != NumArgs; ++I) {
3441 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3442 if (!CanonArgs[I].structurallyEquals(Args[I]))
3443 AnyNonCanonArgs = true;
3447 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3448 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3452 // Find the insert position again.
3453 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3456 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3457 sizeof(TemplateArgument) * NumArgs),
3459 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3460 Name, NumArgs, Args, Canon);
3462 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3463 return QualType(T, 0);
3466 QualType ASTContext::getPackExpansionType(QualType Pattern,
3467 Optional<unsigned> NumExpansions) {
3468 llvm::FoldingSetNodeID ID;
3469 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3471 assert(Pattern->containsUnexpandedParameterPack() &&
3472 "Pack expansions must expand one or more parameter packs");
3473 void *InsertPos = nullptr;
3474 PackExpansionType *T
3475 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3477 return QualType(T, 0);
3480 if (!Pattern.isCanonical()) {
3481 Canon = getCanonicalType(Pattern);
3482 // The canonical type might not contain an unexpanded parameter pack, if it
3483 // contains an alias template specialization which ignores one of its
3485 if (Canon->containsUnexpandedParameterPack()) {
3486 Canon = getPackExpansionType(Canon, NumExpansions);
3488 // Find the insert position again, in case we inserted an element into
3489 // PackExpansionTypes and invalidated our insert position.
3490 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3494 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3496 PackExpansionTypes.InsertNode(T, InsertPos);
3497 return QualType(T, 0);
3500 /// CmpProtocolNames - Comparison predicate for sorting protocols
3502 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3503 const ObjCProtocolDecl *RHS) {
3504 return LHS->getDeclName() < RHS->getDeclName();
3507 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3508 unsigned NumProtocols) {
3509 if (NumProtocols == 0) return true;
3511 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3514 for (unsigned i = 1; i != NumProtocols; ++i)
3515 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3516 Protocols[i]->getCanonicalDecl() != Protocols[i])
3521 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3522 unsigned &NumProtocols) {
3523 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3525 // Sort protocols, keyed by name.
3526 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3529 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3530 Protocols[I] = Protocols[I]->getCanonicalDecl();
3532 // Remove duplicates.
3533 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3534 NumProtocols = ProtocolsEnd-Protocols;
3537 QualType ASTContext::getObjCObjectType(QualType BaseType,
3538 ObjCProtocolDecl * const *Protocols,
3539 unsigned NumProtocols) const {
3540 // If the base type is an interface and there aren't any protocols
3541 // to add, then the interface type will do just fine.
3542 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3545 // Look in the folding set for an existing type.
3546 llvm::FoldingSetNodeID ID;
3547 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3548 void *InsertPos = nullptr;
3549 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3550 return QualType(QT, 0);
3552 // Build the canonical type, which has the canonical base type and
3553 // a sorted-and-uniqued list of protocols.
3555 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3556 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3557 if (!ProtocolsSorted) {
3558 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3559 Protocols + NumProtocols);
3560 unsigned UniqueCount = NumProtocols;
3562 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3563 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3564 &Sorted[0], UniqueCount);
3566 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3567 Protocols, NumProtocols);
3570 // Regenerate InsertPos.
3571 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3574 unsigned Size = sizeof(ObjCObjectTypeImpl);
3575 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3576 void *Mem = Allocate(Size, TypeAlignment);
3577 ObjCObjectTypeImpl *T =
3578 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3581 ObjCObjectTypes.InsertNode(T, InsertPos);
3582 return QualType(T, 0);
3585 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3586 /// protocol list adopt all protocols in QT's qualified-id protocol
3588 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3589 ObjCInterfaceDecl *IC) {
3590 if (!QT->isObjCQualifiedIdType())
3593 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3594 // If both the right and left sides have qualifiers.
3595 for (auto *Proto : OPT->quals()) {
3596 if (!IC->ClassImplementsProtocol(Proto, false))
3604 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3605 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3607 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3608 ObjCInterfaceDecl *IDecl) {
3609 if (!QT->isObjCQualifiedIdType())
3611 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3614 if (!IDecl->hasDefinition())
3616 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3617 CollectInheritedProtocols(IDecl, InheritedProtocols);
3618 if (InheritedProtocols.empty())
3620 // Check that if every protocol in list of id<plist> conforms to a protcol
3621 // of IDecl's, then bridge casting is ok.
3622 bool Conforms = false;
3623 for (auto *Proto : OPT->quals()) {
3625 for (auto *PI : InheritedProtocols) {
3626 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3637 for (auto *PI : InheritedProtocols) {
3638 // If both the right and left sides have qualifiers.
3639 bool Adopts = false;
3640 for (auto *Proto : OPT->quals()) {
3641 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3642 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3651 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3652 /// the given object type.
3653 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3654 llvm::FoldingSetNodeID ID;
3655 ObjCObjectPointerType::Profile(ID, ObjectT);
3657 void *InsertPos = nullptr;
3658 if (ObjCObjectPointerType *QT =
3659 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3660 return QualType(QT, 0);
3662 // Find the canonical object type.
3664 if (!ObjectT.isCanonical()) {
3665 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3667 // Regenerate InsertPos.
3668 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3672 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3673 ObjCObjectPointerType *QType =
3674 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3676 Types.push_back(QType);
3677 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3678 return QualType(QType, 0);
3681 /// getObjCInterfaceType - Return the unique reference to the type for the
3682 /// specified ObjC interface decl. The list of protocols is optional.
3683 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3684 ObjCInterfaceDecl *PrevDecl) const {
3685 if (Decl->TypeForDecl)
3686 return QualType(Decl->TypeForDecl, 0);
3689 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3690 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3691 return QualType(PrevDecl->TypeForDecl, 0);
3694 // Prefer the definition, if there is one.
3695 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3698 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3699 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3700 Decl->TypeForDecl = T;
3702 return QualType(T, 0);
3705 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3706 /// TypeOfExprType AST's (since expression's are never shared). For example,
3707 /// multiple declarations that refer to "typeof(x)" all contain different
3708 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3709 /// on canonical type's (which are always unique).
3710 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3711 TypeOfExprType *toe;
3712 if (tofExpr->isTypeDependent()) {
3713 llvm::FoldingSetNodeID ID;
3714 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3716 void *InsertPos = nullptr;
3717 DependentTypeOfExprType *Canon
3718 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3720 // We already have a "canonical" version of an identical, dependent
3721 // typeof(expr) type. Use that as our canonical type.
3722 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3723 QualType((TypeOfExprType*)Canon, 0));
3725 // Build a new, canonical typeof(expr) type.
3727 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3728 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3732 QualType Canonical = getCanonicalType(tofExpr->getType());
3733 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3735 Types.push_back(toe);
3736 return QualType(toe, 0);
3739 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3740 /// TypeOfType nodes. The only motivation to unique these nodes would be
3741 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3742 /// an issue. This doesn't affect the type checker, since it operates
3743 /// on canonical types (which are always unique).
3744 QualType ASTContext::getTypeOfType(QualType tofType) const {
3745 QualType Canonical = getCanonicalType(tofType);
3746 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3747 Types.push_back(tot);
3748 return QualType(tot, 0);
3752 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3753 /// nodes. This would never be helpful, since each such type has its own
3754 /// expression, and would not give a significant memory saving, since there
3755 /// is an Expr tree under each such type.
3756 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3759 // C++11 [temp.type]p2:
3760 // If an expression e involves a template parameter, decltype(e) denotes a
3761 // unique dependent type. Two such decltype-specifiers refer to the same
3762 // type only if their expressions are equivalent (14.5.6.1).
3763 if (e->isInstantiationDependent()) {
3764 llvm::FoldingSetNodeID ID;
3765 DependentDecltypeType::Profile(ID, *this, e);
3767 void *InsertPos = nullptr;
3768 DependentDecltypeType *Canon
3769 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3771 // Build a new, canonical typeof(expr) type.
3772 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3773 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3775 dt = new (*this, TypeAlignment)
3776 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3778 dt = new (*this, TypeAlignment)
3779 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3781 Types.push_back(dt);
3782 return QualType(dt, 0);
3785 /// getUnaryTransformationType - We don't unique these, since the memory
3786 /// savings are minimal and these are rare.
3787 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3788 QualType UnderlyingType,
3789 UnaryTransformType::UTTKind Kind)
3791 UnaryTransformType *Ty =
3792 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3794 UnderlyingType->isDependentType() ?
3795 QualType() : getCanonicalType(UnderlyingType));
3796 Types.push_back(Ty);
3797 return QualType(Ty, 0);
3800 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3801 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3802 /// canonical deduced-but-dependent 'auto' type.
3803 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3804 bool IsDependent) const {
3805 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3806 return getAutoDeductType();
3808 // Look in the folding set for an existing type.
3809 void *InsertPos = nullptr;
3810 llvm::FoldingSetNodeID ID;
3811 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3812 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(AT, 0);
3815 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3818 Types.push_back(AT);
3820 AutoTypes.InsertNode(AT, InsertPos);
3821 return QualType(AT, 0);
3824 /// getAtomicType - Return the uniqued reference to the atomic type for
3825 /// the given value type.
3826 QualType ASTContext::getAtomicType(QualType T) const {
3827 // Unique pointers, to guarantee there is only one pointer of a particular
3829 llvm::FoldingSetNodeID ID;
3830 AtomicType::Profile(ID, T);
3832 void *InsertPos = nullptr;
3833 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3834 return QualType(AT, 0);
3836 // If the atomic value type isn't canonical, this won't be a canonical type
3837 // either, so fill in the canonical type field.
3839 if (!T.isCanonical()) {
3840 Canonical = getAtomicType(getCanonicalType(T));
3842 // Get the new insert position for the node we care about.
3843 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3844 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3846 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3847 Types.push_back(New);
3848 AtomicTypes.InsertNode(New, InsertPos);
3849 return QualType(New, 0);
3852 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3853 QualType ASTContext::getAutoDeductType() const {
3854 if (AutoDeductTy.isNull())
3855 AutoDeductTy = QualType(
3856 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3857 /*dependent*/false),
3859 return AutoDeductTy;
3862 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3863 QualType ASTContext::getAutoRRefDeductType() const {
3864 if (AutoRRefDeductTy.isNull())
3865 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3866 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3867 return AutoRRefDeductTy;
3870 /// getTagDeclType - Return the unique reference to the type for the
3871 /// specified TagDecl (struct/union/class/enum) decl.
3872 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3874 // FIXME: What is the design on getTagDeclType when it requires casting
3875 // away const? mutable?
3876 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3879 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3880 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3881 /// needs to agree with the definition in <stddef.h>.
3882 CanQualType ASTContext::getSizeType() const {
3883 return getFromTargetType(Target->getSizeType());
3886 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3887 CanQualType ASTContext::getIntMaxType() const {
3888 return getFromTargetType(Target->getIntMaxType());
3891 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3892 CanQualType ASTContext::getUIntMaxType() const {
3893 return getFromTargetType(Target->getUIntMaxType());
3896 /// getSignedWCharType - Return the type of "signed wchar_t".
3897 /// Used when in C++, as a GCC extension.
3898 QualType ASTContext::getSignedWCharType() const {
3899 // FIXME: derive from "Target" ?
3903 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3904 /// Used when in C++, as a GCC extension.
3905 QualType ASTContext::getUnsignedWCharType() const {
3906 // FIXME: derive from "Target" ?
3907 return UnsignedIntTy;
3910 QualType ASTContext::getIntPtrType() const {
3911 return getFromTargetType(Target->getIntPtrType());
3914 QualType ASTContext::getUIntPtrType() const {
3915 return getCorrespondingUnsignedType(getIntPtrType());
3918 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3919 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3920 QualType ASTContext::getPointerDiffType() const {
3921 return getFromTargetType(Target->getPtrDiffType(0));
3924 /// \brief Return the unique type for "pid_t" defined in
3925 /// <sys/types.h>. We need this to compute the correct type for vfork().
3926 QualType ASTContext::getProcessIDType() const {
3927 return getFromTargetType(Target->getProcessIDType());
3930 //===----------------------------------------------------------------------===//
3932 //===----------------------------------------------------------------------===//
3934 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3935 // Push qualifiers into arrays, and then discard any remaining
3937 T = getCanonicalType(T);
3938 T = getVariableArrayDecayedType(T);
3939 const Type *Ty = T.getTypePtr();
3941 if (isa<ArrayType>(Ty)) {
3942 Result = getArrayDecayedType(QualType(Ty,0));
3943 } else if (isa<FunctionType>(Ty)) {
3944 Result = getPointerType(QualType(Ty, 0));
3946 Result = QualType(Ty, 0);
3949 return CanQualType::CreateUnsafe(Result);
3952 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3953 Qualifiers &quals) {
3954 SplitQualType splitType = type.getSplitUnqualifiedType();
3956 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3957 // the unqualified desugared type and then drops it on the floor.
3958 // We then have to strip that sugar back off with
3959 // getUnqualifiedDesugaredType(), which is silly.
3960 const ArrayType *AT =
3961 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3963 // If we don't have an array, just use the results in splitType.
3965 quals = splitType.Quals;
3966 return QualType(splitType.Ty, 0);
3969 // Otherwise, recurse on the array's element type.
3970 QualType elementType = AT->getElementType();
3971 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3973 // If that didn't change the element type, AT has no qualifiers, so we
3974 // can just use the results in splitType.
3975 if (elementType == unqualElementType) {
3976 assert(quals.empty()); // from the recursive call
3977 quals = splitType.Quals;
3978 return QualType(splitType.Ty, 0);
3981 // Otherwise, add in the qualifiers from the outermost type, then
3982 // build the type back up.
3983 quals.addConsistentQualifiers(splitType.Quals);
3985 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3986 return getConstantArrayType(unqualElementType, CAT->getSize(),
3987 CAT->getSizeModifier(), 0);
3990 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3991 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3994 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3995 return getVariableArrayType(unqualElementType,
3997 VAT->getSizeModifier(),
3998 VAT->getIndexTypeCVRQualifiers(),
3999 VAT->getBracketsRange());
4002 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4003 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4004 DSAT->getSizeModifier(), 0,
4008 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4009 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4010 /// they point to and return true. If T1 and T2 aren't pointer types
4011 /// or pointer-to-member types, or if they are not similar at this
4012 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4013 /// qualifiers on T1 and T2 are ignored. This function will typically
4014 /// be called in a loop that successively "unwraps" pointer and
4015 /// pointer-to-member types to compare them at each level.
4016 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4017 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4018 *T2PtrType = T2->getAs<PointerType>();
4019 if (T1PtrType && T2PtrType) {
4020 T1 = T1PtrType->getPointeeType();
4021 T2 = T2PtrType->getPointeeType();
4025 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4026 *T2MPType = T2->getAs<MemberPointerType>();
4027 if (T1MPType && T2MPType &&
4028 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4029 QualType(T2MPType->getClass(), 0))) {
4030 T1 = T1MPType->getPointeeType();
4031 T2 = T2MPType->getPointeeType();
4035 if (getLangOpts().ObjC1) {
4036 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4037 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4038 if (T1OPType && T2OPType) {
4039 T1 = T1OPType->getPointeeType();
4040 T2 = T2OPType->getPointeeType();
4045 // FIXME: Block pointers, too?
4051 ASTContext::getNameForTemplate(TemplateName Name,
4052 SourceLocation NameLoc) const {
4053 switch (Name.getKind()) {
4054 case TemplateName::QualifiedTemplate:
4055 case TemplateName::Template:
4056 // DNInfo work in progress: CHECKME: what about DNLoc?
4057 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4060 case TemplateName::OverloadedTemplate: {
4061 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4062 // DNInfo work in progress: CHECKME: what about DNLoc?
4063 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4066 case TemplateName::DependentTemplate: {
4067 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4068 DeclarationName DName;
4069 if (DTN->isIdentifier()) {
4070 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4071 return DeclarationNameInfo(DName, NameLoc);
4073 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4074 // DNInfo work in progress: FIXME: source locations?
4075 DeclarationNameLoc DNLoc;
4076 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4077 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4078 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4082 case TemplateName::SubstTemplateTemplateParm: {
4083 SubstTemplateTemplateParmStorage *subst
4084 = Name.getAsSubstTemplateTemplateParm();
4085 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4089 case TemplateName::SubstTemplateTemplateParmPack: {
4090 SubstTemplateTemplateParmPackStorage *subst
4091 = Name.getAsSubstTemplateTemplateParmPack();
4092 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4097 llvm_unreachable("bad template name kind!");
4100 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4101 switch (Name.getKind()) {
4102 case TemplateName::QualifiedTemplate:
4103 case TemplateName::Template: {
4104 TemplateDecl *Template = Name.getAsTemplateDecl();
4105 if (TemplateTemplateParmDecl *TTP
4106 = dyn_cast<TemplateTemplateParmDecl>(Template))
4107 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4109 // The canonical template name is the canonical template declaration.
4110 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4113 case TemplateName::OverloadedTemplate:
4114 llvm_unreachable("cannot canonicalize overloaded template");
4116 case TemplateName::DependentTemplate: {
4117 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4118 assert(DTN && "Non-dependent template names must refer to template decls.");
4119 return DTN->CanonicalTemplateName;
4122 case TemplateName::SubstTemplateTemplateParm: {
4123 SubstTemplateTemplateParmStorage *subst
4124 = Name.getAsSubstTemplateTemplateParm();
4125 return getCanonicalTemplateName(subst->getReplacement());
4128 case TemplateName::SubstTemplateTemplateParmPack: {
4129 SubstTemplateTemplateParmPackStorage *subst
4130 = Name.getAsSubstTemplateTemplateParmPack();
4131 TemplateTemplateParmDecl *canonParameter
4132 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4133 TemplateArgument canonArgPack
4134 = getCanonicalTemplateArgument(subst->getArgumentPack());
4135 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4139 llvm_unreachable("bad template name!");
4142 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4143 X = getCanonicalTemplateName(X);
4144 Y = getCanonicalTemplateName(Y);
4145 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4149 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4150 switch (Arg.getKind()) {
4151 case TemplateArgument::Null:
4154 case TemplateArgument::Expression:
4157 case TemplateArgument::Declaration: {
4158 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4159 return TemplateArgument(D, Arg.getParamTypeForDecl());
4162 case TemplateArgument::NullPtr:
4163 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4166 case TemplateArgument::Template:
4167 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4169 case TemplateArgument::TemplateExpansion:
4170 return TemplateArgument(getCanonicalTemplateName(
4171 Arg.getAsTemplateOrTemplatePattern()),
4172 Arg.getNumTemplateExpansions());
4174 case TemplateArgument::Integral:
4175 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4177 case TemplateArgument::Type:
4178 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4180 case TemplateArgument::Pack: {
4181 if (Arg.pack_size() == 0)
4184 TemplateArgument *CanonArgs
4185 = new (*this) TemplateArgument[Arg.pack_size()];
4187 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4188 AEnd = Arg.pack_end();
4189 A != AEnd; (void)++A, ++Idx)
4190 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4192 return TemplateArgument(CanonArgs, Arg.pack_size());
4196 // Silence GCC warning
4197 llvm_unreachable("Unhandled template argument kind");
4200 NestedNameSpecifier *
4201 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4205 switch (NNS->getKind()) {
4206 case NestedNameSpecifier::Identifier:
4207 // Canonicalize the prefix but keep the identifier the same.
4208 return NestedNameSpecifier::Create(*this,
4209 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4210 NNS->getAsIdentifier());
4212 case NestedNameSpecifier::Namespace:
4213 // A namespace is canonical; build a nested-name-specifier with
4214 // this namespace and no prefix.
4215 return NestedNameSpecifier::Create(*this, nullptr,
4216 NNS->getAsNamespace()->getOriginalNamespace());
4218 case NestedNameSpecifier::NamespaceAlias:
4219 // A namespace is canonical; build a nested-name-specifier with
4220 // this namespace and no prefix.
4221 return NestedNameSpecifier::Create(*this, nullptr,
4222 NNS->getAsNamespaceAlias()->getNamespace()
4223 ->getOriginalNamespace());
4225 case NestedNameSpecifier::TypeSpec:
4226 case NestedNameSpecifier::TypeSpecWithTemplate: {
4227 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4229 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4230 // break it apart into its prefix and identifier, then reconsititute those
4231 // as the canonical nested-name-specifier. This is required to canonicalize
4232 // a dependent nested-name-specifier involving typedefs of dependent-name
4234 // typedef typename T::type T1;
4235 // typedef typename T1::type T2;
4236 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4237 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4238 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4240 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4241 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4243 return NestedNameSpecifier::Create(*this, nullptr, false,
4244 const_cast<Type *>(T.getTypePtr()));
4247 case NestedNameSpecifier::Global:
4248 case NestedNameSpecifier::Super:
4249 // The global specifier and __super specifer are canonical and unique.
4253 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4257 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4258 // Handle the non-qualified case efficiently.
4259 if (!T.hasLocalQualifiers()) {
4260 // Handle the common positive case fast.
4261 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4265 // Handle the common negative case fast.
4266 if (!isa<ArrayType>(T.getCanonicalType()))
4269 // Apply any qualifiers from the array type to the element type. This
4270 // implements C99 6.7.3p8: "If the specification of an array type includes
4271 // any type qualifiers, the element type is so qualified, not the array type."
4273 // If we get here, we either have type qualifiers on the type, or we have
4274 // sugar such as a typedef in the way. If we have type qualifiers on the type
4275 // we must propagate them down into the element type.
4277 SplitQualType split = T.getSplitDesugaredType();
4278 Qualifiers qs = split.Quals;
4280 // If we have a simple case, just return now.
4281 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4282 if (!ATy || qs.empty())
4285 // Otherwise, we have an array and we have qualifiers on it. Push the
4286 // qualifiers into the array element type and return a new array type.
4287 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4289 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4290 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4291 CAT->getSizeModifier(),
4292 CAT->getIndexTypeCVRQualifiers()));
4293 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4294 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4295 IAT->getSizeModifier(),
4296 IAT->getIndexTypeCVRQualifiers()));
4298 if (const DependentSizedArrayType *DSAT
4299 = dyn_cast<DependentSizedArrayType>(ATy))
4300 return cast<ArrayType>(
4301 getDependentSizedArrayType(NewEltTy,
4302 DSAT->getSizeExpr(),
4303 DSAT->getSizeModifier(),
4304 DSAT->getIndexTypeCVRQualifiers(),
4305 DSAT->getBracketsRange()));
4307 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4308 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4310 VAT->getSizeModifier(),
4311 VAT->getIndexTypeCVRQualifiers(),
4312 VAT->getBracketsRange()));
4315 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4316 if (T->isArrayType() || T->isFunctionType())
4317 return getDecayedType(T);
4321 QualType ASTContext::getSignatureParameterType(QualType T) const {
4322 T = getVariableArrayDecayedType(T);
4323 T = getAdjustedParameterType(T);
4324 return T.getUnqualifiedType();
4327 /// getArrayDecayedType - Return the properly qualified result of decaying the
4328 /// specified array type to a pointer. This operation is non-trivial when
4329 /// handling typedefs etc. The canonical type of "T" must be an array type,
4330 /// this returns a pointer to a properly qualified element of the array.
4332 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4333 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4334 // Get the element type with 'getAsArrayType' so that we don't lose any
4335 // typedefs in the element type of the array. This also handles propagation
4336 // of type qualifiers from the array type into the element type if present
4338 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4339 assert(PrettyArrayType && "Not an array type!");
4341 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4343 // int x[restrict 4] -> int *restrict
4344 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4347 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4348 return getBaseElementType(array->getElementType());
4351 QualType ASTContext::getBaseElementType(QualType type) const {
4354 SplitQualType split = type.getSplitDesugaredType();
4355 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4358 type = array->getElementType();
4359 qs.addConsistentQualifiers(split.Quals);
4362 return getQualifiedType(type, qs);
4365 /// getConstantArrayElementCount - Returns number of constant array elements.
4367 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4368 uint64_t ElementCount = 1;
4370 ElementCount *= CA->getSize().getZExtValue();
4371 CA = dyn_cast_or_null<ConstantArrayType>(
4372 CA->getElementType()->getAsArrayTypeUnsafe());
4374 return ElementCount;
4377 /// getFloatingRank - Return a relative rank for floating point types.
4378 /// This routine will assert if passed a built-in type that isn't a float.
4379 static FloatingRank getFloatingRank(QualType T) {
4380 if (const ComplexType *CT = T->getAs<ComplexType>())
4381 return getFloatingRank(CT->getElementType());
4383 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4384 switch (T->getAs<BuiltinType>()->getKind()) {
4385 default: llvm_unreachable("getFloatingRank(): not a floating type");
4386 case BuiltinType::Half: return HalfRank;
4387 case BuiltinType::Float: return FloatRank;
4388 case BuiltinType::Double: return DoubleRank;
4389 case BuiltinType::LongDouble: return LongDoubleRank;
4393 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4394 /// point or a complex type (based on typeDomain/typeSize).
4395 /// 'typeDomain' is a real floating point or complex type.
4396 /// 'typeSize' is a real floating point or complex type.
4397 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4398 QualType Domain) const {
4399 FloatingRank EltRank = getFloatingRank(Size);
4400 if (Domain->isComplexType()) {
4402 case HalfRank: llvm_unreachable("Complex half is not supported");
4403 case FloatRank: return FloatComplexTy;
4404 case DoubleRank: return DoubleComplexTy;
4405 case LongDoubleRank: return LongDoubleComplexTy;
4409 assert(Domain->isRealFloatingType() && "Unknown domain!");
4411 case HalfRank: return HalfTy;
4412 case FloatRank: return FloatTy;
4413 case DoubleRank: return DoubleTy;
4414 case LongDoubleRank: return LongDoubleTy;
4416 llvm_unreachable("getFloatingRank(): illegal value for rank");
4419 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4420 /// point types, ignoring the domain of the type (i.e. 'double' ==
4421 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4422 /// LHS < RHS, return -1.
4423 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4424 FloatingRank LHSR = getFloatingRank(LHS);
4425 FloatingRank RHSR = getFloatingRank(RHS);
4434 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4435 /// routine will assert if passed a built-in type that isn't an integer or enum,
4436 /// or if it is not canonicalized.
4437 unsigned ASTContext::getIntegerRank(const Type *T) const {
4438 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4440 switch (cast<BuiltinType>(T)->getKind()) {
4441 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4442 case BuiltinType::Bool:
4443 return 1 + (getIntWidth(BoolTy) << 3);
4444 case BuiltinType::Char_S:
4445 case BuiltinType::Char_U:
4446 case BuiltinType::SChar:
4447 case BuiltinType::UChar:
4448 return 2 + (getIntWidth(CharTy) << 3);
4449 case BuiltinType::Short:
4450 case BuiltinType::UShort:
4451 return 3 + (getIntWidth(ShortTy) << 3);
4452 case BuiltinType::Int:
4453 case BuiltinType::UInt:
4454 return 4 + (getIntWidth(IntTy) << 3);
4455 case BuiltinType::Long:
4456 case BuiltinType::ULong:
4457 return 5 + (getIntWidth(LongTy) << 3);
4458 case BuiltinType::LongLong:
4459 case BuiltinType::ULongLong:
4460 return 6 + (getIntWidth(LongLongTy) << 3);
4461 case BuiltinType::Int128:
4462 case BuiltinType::UInt128:
4463 return 7 + (getIntWidth(Int128Ty) << 3);
4467 /// \brief Whether this is a promotable bitfield reference according
4468 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4470 /// \returns the type this bit-field will promote to, or NULL if no
4471 /// promotion occurs.
4472 QualType ASTContext::isPromotableBitField(Expr *E) const {
4473 if (E->isTypeDependent() || E->isValueDependent())
4476 // FIXME: We should not do this unless E->refersToBitField() is true. This
4477 // matters in C where getSourceBitField() will find bit-fields for various
4478 // cases where the source expression is not a bit-field designator.
4480 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4484 QualType FT = Field->getType();
4486 uint64_t BitWidth = Field->getBitWidthValue(*this);
4487 uint64_t IntSize = getTypeSize(IntTy);
4488 // C++ [conv.prom]p5:
4489 // A prvalue for an integral bit-field can be converted to a prvalue of type
4490 // int if int can represent all the values of the bit-field; otherwise, it
4491 // can be converted to unsigned int if unsigned int can represent all the
4492 // values of the bit-field. If the bit-field is larger yet, no integral
4493 // promotion applies to it.
4495 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4496 // If an int can represent all values of the original type (as restricted by
4497 // the width, for a bit-field), the value is converted to an int; otherwise,
4498 // it is converted to an unsigned int.
4500 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4501 // We perform that promotion here to match GCC and C++.
4502 if (BitWidth < IntSize)
4505 if (BitWidth == IntSize)
4506 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4508 // Types bigger than int are not subject to promotions, and therefore act
4509 // like the base type. GCC has some weird bugs in this area that we
4510 // deliberately do not follow (GCC follows a pre-standard resolution to
4511 // C's DR315 which treats bit-width as being part of the type, and this leaks
4512 // into their semantics in some cases).
4516 /// getPromotedIntegerType - Returns the type that Promotable will
4517 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4519 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4520 assert(!Promotable.isNull());
4521 assert(Promotable->isPromotableIntegerType());
4522 if (const EnumType *ET = Promotable->getAs<EnumType>())
4523 return ET->getDecl()->getPromotionType();
4525 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4526 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4527 // (3.9.1) can be converted to a prvalue of the first of the following
4528 // types that can represent all the values of its underlying type:
4529 // int, unsigned int, long int, unsigned long int, long long int, or
4530 // unsigned long long int [...]
4531 // FIXME: Is there some better way to compute this?
4532 if (BT->getKind() == BuiltinType::WChar_S ||
4533 BT->getKind() == BuiltinType::WChar_U ||
4534 BT->getKind() == BuiltinType::Char16 ||
4535 BT->getKind() == BuiltinType::Char32) {
4536 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4537 uint64_t FromSize = getTypeSize(BT);
4538 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4539 LongLongTy, UnsignedLongLongTy };
4540 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4541 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4542 if (FromSize < ToSize ||
4543 (FromSize == ToSize &&
4544 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4545 return PromoteTypes[Idx];
4547 llvm_unreachable("char type should fit into long long");
4551 // At this point, we should have a signed or unsigned integer type.
4552 if (Promotable->isSignedIntegerType())
4554 uint64_t PromotableSize = getIntWidth(Promotable);
4555 uint64_t IntSize = getIntWidth(IntTy);
4556 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4557 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4560 /// \brief Recurses in pointer/array types until it finds an objc retainable
4561 /// type and returns its ownership.
4562 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4563 while (!T.isNull()) {
4564 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4565 return T.getObjCLifetime();
4566 if (T->isArrayType())
4567 T = getBaseElementType(T);
4568 else if (const PointerType *PT = T->getAs<PointerType>())
4569 T = PT->getPointeeType();
4570 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4571 T = RT->getPointeeType();
4576 return Qualifiers::OCL_None;
4579 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4580 // Incomplete enum types are not treated as integer types.
4581 // FIXME: In C++, enum types are never integer types.
4582 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4583 return ET->getDecl()->getIntegerType().getTypePtr();
4587 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4588 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4589 /// LHS < RHS, return -1.
4590 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4591 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4592 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4594 // Unwrap enums to their underlying type.
4595 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4596 LHSC = getIntegerTypeForEnum(ET);
4597 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4598 RHSC = getIntegerTypeForEnum(ET);
4600 if (LHSC == RHSC) return 0;
4602 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4603 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4605 unsigned LHSRank = getIntegerRank(LHSC);
4606 unsigned RHSRank = getIntegerRank(RHSC);
4608 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4609 if (LHSRank == RHSRank) return 0;
4610 return LHSRank > RHSRank ? 1 : -1;
4613 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4615 // If the unsigned [LHS] type is larger, return it.
4616 if (LHSRank >= RHSRank)
4619 // If the signed type can represent all values of the unsigned type, it
4620 // wins. Because we are dealing with 2's complement and types that are
4621 // powers of two larger than each other, this is always safe.
4625 // If the unsigned [RHS] type is larger, return it.
4626 if (RHSRank >= LHSRank)
4629 // If the signed type can represent all values of the unsigned type, it
4630 // wins. Because we are dealing with 2's complement and types that are
4631 // powers of two larger than each other, this is always safe.
4635 // getCFConstantStringType - Return the type used for constant CFStrings.
4636 QualType ASTContext::getCFConstantStringType() const {
4637 if (!CFConstantStringTypeDecl) {
4638 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4639 CFConstantStringTypeDecl->startDefinition();
4641 QualType FieldTypes[4];
4644 FieldTypes[0] = getPointerType(IntTy.withConst());
4646 FieldTypes[1] = IntTy;
4648 FieldTypes[2] = getPointerType(CharTy.withConst());
4650 FieldTypes[3] = LongTy;
4653 for (unsigned i = 0; i < 4; ++i) {
4654 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4656 SourceLocation(), nullptr,
4657 FieldTypes[i], /*TInfo=*/nullptr,
4658 /*BitWidth=*/nullptr,
4661 Field->setAccess(AS_public);
4662 CFConstantStringTypeDecl->addDecl(Field);
4665 CFConstantStringTypeDecl->completeDefinition();
4668 return getTagDeclType(CFConstantStringTypeDecl);
4671 QualType ASTContext::getObjCSuperType() const {
4672 if (ObjCSuperType.isNull()) {
4673 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4674 TUDecl->addDecl(ObjCSuperTypeDecl);
4675 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4677 return ObjCSuperType;
4680 void ASTContext::setCFConstantStringType(QualType T) {
4681 const RecordType *Rec = T->getAs<RecordType>();
4682 assert(Rec && "Invalid CFConstantStringType");
4683 CFConstantStringTypeDecl = Rec->getDecl();
4686 QualType ASTContext::getBlockDescriptorType() const {
4687 if (BlockDescriptorType)
4688 return getTagDeclType(BlockDescriptorType);
4691 // FIXME: Needs the FlagAppleBlock bit.
4692 RD = buildImplicitRecord("__block_descriptor");
4693 RD->startDefinition();
4695 QualType FieldTypes[] = {
4700 static const char *const FieldNames[] = {
4705 for (size_t i = 0; i < 2; ++i) {
4706 FieldDecl *Field = FieldDecl::Create(
4707 *this, RD, SourceLocation(), SourceLocation(),
4708 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4709 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4710 Field->setAccess(AS_public);
4714 RD->completeDefinition();
4716 BlockDescriptorType = RD;
4718 return getTagDeclType(BlockDescriptorType);
4721 QualType ASTContext::getBlockDescriptorExtendedType() const {
4722 if (BlockDescriptorExtendedType)
4723 return getTagDeclType(BlockDescriptorExtendedType);
4726 // FIXME: Needs the FlagAppleBlock bit.
4727 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4728 RD->startDefinition();
4730 QualType FieldTypes[] = {
4733 getPointerType(VoidPtrTy),
4734 getPointerType(VoidPtrTy)
4737 static const char *const FieldNames[] = {
4744 for (size_t i = 0; i < 4; ++i) {
4745 FieldDecl *Field = FieldDecl::Create(
4746 *this, RD, SourceLocation(), SourceLocation(),
4747 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4748 /*BitWidth=*/nullptr,
4749 /*Mutable=*/false, ICIS_NoInit);
4750 Field->setAccess(AS_public);
4754 RD->completeDefinition();
4756 BlockDescriptorExtendedType = RD;
4757 return getTagDeclType(BlockDescriptorExtendedType);
4760 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4761 /// requires copy/dispose. Note that this must match the logic
4762 /// in buildByrefHelpers.
4763 bool ASTContext::BlockRequiresCopying(QualType Ty,
4765 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4766 const Expr *copyExpr = getBlockVarCopyInits(D);
4767 if (!copyExpr && record->hasTrivialDestructor()) return false;
4772 if (!Ty->isObjCRetainableType()) return false;
4774 Qualifiers qs = Ty.getQualifiers();
4776 // If we have lifetime, that dominates.
4777 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4778 assert(getLangOpts().ObjCAutoRefCount);
4781 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4783 // These are just bits as far as the runtime is concerned.
4784 case Qualifiers::OCL_ExplicitNone:
4785 case Qualifiers::OCL_Autoreleasing:
4788 // Tell the runtime that this is ARC __weak, called by the
4790 case Qualifiers::OCL_Weak:
4791 // ARC __strong __block variables need to be retained.
4792 case Qualifiers::OCL_Strong:
4795 llvm_unreachable("fell out of lifetime switch!");
4797 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4798 Ty->isObjCObjectPointerType());
4801 bool ASTContext::getByrefLifetime(QualType Ty,
4802 Qualifiers::ObjCLifetime &LifeTime,
4803 bool &HasByrefExtendedLayout) const {
4805 if (!getLangOpts().ObjC1 ||
4806 getLangOpts().getGC() != LangOptions::NonGC)
4809 HasByrefExtendedLayout = false;
4810 if (Ty->isRecordType()) {
4811 HasByrefExtendedLayout = true;
4812 LifeTime = Qualifiers::OCL_None;
4814 else if (getLangOpts().ObjCAutoRefCount)
4815 LifeTime = Ty.getObjCLifetime();
4817 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4818 LifeTime = Qualifiers::OCL_ExplicitNone;
4820 LifeTime = Qualifiers::OCL_None;
4824 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4825 if (!ObjCInstanceTypeDecl)
4826 ObjCInstanceTypeDecl =
4827 buildImplicitTypedef(getObjCIdType(), "instancetype");
4828 return ObjCInstanceTypeDecl;
4831 // This returns true if a type has been typedefed to BOOL:
4832 // typedef <type> BOOL;
4833 static bool isTypeTypedefedAsBOOL(QualType T) {
4834 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4835 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4836 return II->isStr("BOOL");
4841 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4843 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4844 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4845 return CharUnits::Zero();
4847 CharUnits sz = getTypeSizeInChars(type);
4849 // Make all integer and enum types at least as large as an int
4850 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4851 sz = std::max(sz, getTypeSizeInChars(IntTy));
4852 // Treat arrays as pointers, since that's how they're passed in.
4853 else if (type->isArrayType())
4854 sz = getTypeSizeInChars(VoidPtrTy);
4858 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4859 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4860 VD->getType()->isIntegralOrEnumerationType() &&
4861 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4865 std::string charUnitsToString(const CharUnits &CU) {
4866 return llvm::itostr(CU.getQuantity());
4869 /// getObjCEncodingForBlock - Return the encoded type for this block
4871 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4874 const BlockDecl *Decl = Expr->getBlockDecl();
4876 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4877 // Encode result type.
4878 if (getLangOpts().EncodeExtendedBlockSig)
4879 getObjCEncodingForMethodParameter(
4880 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4883 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
4884 // Compute size of all parameters.
4885 // Start with computing size of a pointer in number of bytes.
4886 // FIXME: There might(should) be a better way of doing this computation!
4888 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4889 CharUnits ParmOffset = PtrSize;
4890 for (auto PI : Decl->params()) {
4891 QualType PType = PI->getType();
4892 CharUnits sz = getObjCEncodingTypeSize(PType);
4895 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4898 // Size of the argument frame
4899 S += charUnitsToString(ParmOffset);
4900 // Block pointer and offset.
4904 ParmOffset = PtrSize;
4905 for (auto PVDecl : Decl->params()) {
4906 QualType PType = PVDecl->getOriginalType();
4907 if (const ArrayType *AT =
4908 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4909 // Use array's original type only if it has known number of
4911 if (!isa<ConstantArrayType>(AT))
4912 PType = PVDecl->getType();
4913 } else if (PType->isFunctionType())
4914 PType = PVDecl->getType();
4915 if (getLangOpts().EncodeExtendedBlockSig)
4916 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4917 S, true /*Extended*/);
4919 getObjCEncodingForType(PType, S);
4920 S += charUnitsToString(ParmOffset);
4921 ParmOffset += getObjCEncodingTypeSize(PType);
4927 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4929 // Encode result type.
4930 getObjCEncodingForType(Decl->getReturnType(), S);
4931 CharUnits ParmOffset;
4932 // Compute size of all parameters.
4933 for (auto PI : Decl->params()) {
4934 QualType PType = PI->getType();
4935 CharUnits sz = getObjCEncodingTypeSize(PType);
4939 assert (sz.isPositive() &&
4940 "getObjCEncodingForFunctionDecl - Incomplete param type");
4943 S += charUnitsToString(ParmOffset);
4944 ParmOffset = CharUnits::Zero();
4947 for (auto PVDecl : Decl->params()) {
4948 QualType PType = PVDecl->getOriginalType();
4949 if (const ArrayType *AT =
4950 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4951 // Use array's original type only if it has known number of
4953 if (!isa<ConstantArrayType>(AT))
4954 PType = PVDecl->getType();
4955 } else if (PType->isFunctionType())
4956 PType = PVDecl->getType();
4957 getObjCEncodingForType(PType, S);
4958 S += charUnitsToString(ParmOffset);
4959 ParmOffset += getObjCEncodingTypeSize(PType);
4965 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4966 /// method parameter or return type. If Extended, include class names and
4967 /// block object types.
4968 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4969 QualType T, std::string& S,
4970 bool Extended) const {
4971 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4972 getObjCEncodingForTypeQualifier(QT, S);
4973 // Encode parameter type.
4974 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
4975 true /*OutermostType*/,
4976 false /*EncodingProperty*/,
4977 false /*StructField*/,
4978 Extended /*EncodeBlockParameters*/,
4979 Extended /*EncodeClassNames*/);
4982 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4984 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4986 bool Extended) const {
4987 // FIXME: This is not very efficient.
4988 // Encode return type.
4989 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4990 Decl->getReturnType(), S, Extended);
4991 // Compute size of all parameters.
4992 // Start with computing size of a pointer in number of bytes.
4993 // FIXME: There might(should) be a better way of doing this computation!
4995 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4996 // The first two arguments (self and _cmd) are pointers; account for
4998 CharUnits ParmOffset = 2 * PtrSize;
4999 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5000 E = Decl->sel_param_end(); PI != E; ++PI) {
5001 QualType PType = (*PI)->getType();
5002 CharUnits sz = getObjCEncodingTypeSize(PType);
5006 assert (sz.isPositive() &&
5007 "getObjCEncodingForMethodDecl - Incomplete param type");
5010 S += charUnitsToString(ParmOffset);
5012 S += charUnitsToString(PtrSize);
5015 ParmOffset = 2 * PtrSize;
5016 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5017 E = Decl->sel_param_end(); PI != E; ++PI) {
5018 const ParmVarDecl *PVDecl = *PI;
5019 QualType PType = PVDecl->getOriginalType();
5020 if (const ArrayType *AT =
5021 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5022 // Use array's original type only if it has known number of
5024 if (!isa<ConstantArrayType>(AT))
5025 PType = PVDecl->getType();
5026 } else if (PType->isFunctionType())
5027 PType = PVDecl->getType();
5028 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5029 PType, S, Extended);
5030 S += charUnitsToString(ParmOffset);
5031 ParmOffset += getObjCEncodingTypeSize(PType);
5037 ObjCPropertyImplDecl *
5038 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5039 const ObjCPropertyDecl *PD,
5040 const Decl *Container) const {
5043 if (const ObjCCategoryImplDecl *CID =
5044 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5045 for (auto *PID : CID->property_impls())
5046 if (PID->getPropertyDecl() == PD)
5049 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5050 for (auto *PID : OID->property_impls())
5051 if (PID->getPropertyDecl() == PD)
5057 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5058 /// property declaration. If non-NULL, Container must be either an
5059 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5060 /// NULL when getting encodings for protocol properties.
5061 /// Property attributes are stored as a comma-delimited C string. The simple
5062 /// attributes readonly and bycopy are encoded as single characters. The
5063 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5064 /// encoded as single characters, followed by an identifier. Property types
5065 /// are also encoded as a parametrized attribute. The characters used to encode
5066 /// these attributes are defined by the following enumeration:
5068 /// enum PropertyAttributes {
5069 /// kPropertyReadOnly = 'R', // property is read-only.
5070 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5071 /// kPropertyByref = '&', // property is a reference to the value last assigned
5072 /// kPropertyDynamic = 'D', // property is dynamic
5073 /// kPropertyGetter = 'G', // followed by getter selector name
5074 /// kPropertySetter = 'S', // followed by setter selector name
5075 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5076 /// kPropertyType = 'T' // followed by old-style type encoding.
5077 /// kPropertyWeak = 'W' // 'weak' property
5078 /// kPropertyStrong = 'P' // property GC'able
5079 /// kPropertyNonAtomic = 'N' // property non-atomic
5082 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5083 const Decl *Container,
5084 std::string& S) const {
5085 // Collect information from the property implementation decl(s).
5086 bool Dynamic = false;
5087 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5089 if (ObjCPropertyImplDecl *PropertyImpDecl =
5090 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5091 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5094 SynthesizePID = PropertyImpDecl;
5097 // FIXME: This is not very efficient.
5100 // Encode result type.
5101 // GCC has some special rules regarding encoding of properties which
5102 // closely resembles encoding of ivars.
5103 getObjCEncodingForPropertyType(PD->getType(), S);
5105 if (PD->isReadOnly()) {
5107 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5109 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5111 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5114 switch (PD->getSetterKind()) {
5115 case ObjCPropertyDecl::Assign: break;
5116 case ObjCPropertyDecl::Copy: S += ",C"; break;
5117 case ObjCPropertyDecl::Retain: S += ",&"; break;
5118 case ObjCPropertyDecl::Weak: S += ",W"; break;
5122 // It really isn't clear at all what this means, since properties
5123 // are "dynamic by default".
5127 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5130 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5132 S += PD->getGetterName().getAsString();
5135 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5137 S += PD->getSetterName().getAsString();
5140 if (SynthesizePID) {
5141 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5143 S += OID->getNameAsString();
5146 // FIXME: OBJCGC: weak & strong
5149 /// getLegacyIntegralTypeEncoding -
5150 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5151 /// 'l' or 'L' , but not always. For typedefs, we need to use
5152 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5154 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5155 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5156 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5157 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5158 PointeeTy = UnsignedIntTy;
5160 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5166 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5167 const FieldDecl *Field,
5168 QualType *NotEncodedT) const {
5169 // We follow the behavior of gcc, expanding structures which are
5170 // directly pointed to, and expanding embedded structures. Note that
5171 // these rules are sufficient to prevent recursive encoding of the
5173 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5174 true /* outermost type */, false, false,
5175 false, false, false, NotEncodedT);
5178 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5179 std::string& S) const {
5180 // Encode result type.
5181 // GCC has some special rules regarding encoding of properties which
5182 // closely resembles encoding of ivars.
5183 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5184 true /* outermost type */,
5185 true /* encoding property */);
5188 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5189 BuiltinType::Kind kind) {
5191 case BuiltinType::Void: return 'v';
5192 case BuiltinType::Bool: return 'B';
5193 case BuiltinType::Char_U:
5194 case BuiltinType::UChar: return 'C';
5195 case BuiltinType::Char16:
5196 case BuiltinType::UShort: return 'S';
5197 case BuiltinType::Char32:
5198 case BuiltinType::UInt: return 'I';
5199 case BuiltinType::ULong:
5200 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5201 case BuiltinType::UInt128: return 'T';
5202 case BuiltinType::ULongLong: return 'Q';
5203 case BuiltinType::Char_S:
5204 case BuiltinType::SChar: return 'c';
5205 case BuiltinType::Short: return 's';
5206 case BuiltinType::WChar_S:
5207 case BuiltinType::WChar_U:
5208 case BuiltinType::Int: return 'i';
5209 case BuiltinType::Long:
5210 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5211 case BuiltinType::LongLong: return 'q';
5212 case BuiltinType::Int128: return 't';
5213 case BuiltinType::Float: return 'f';
5214 case BuiltinType::Double: return 'd';
5215 case BuiltinType::LongDouble: return 'D';
5216 case BuiltinType::NullPtr: return '*'; // like char*
5218 case BuiltinType::Half:
5219 // FIXME: potentially need @encodes for these!
5222 case BuiltinType::ObjCId:
5223 case BuiltinType::ObjCClass:
5224 case BuiltinType::ObjCSel:
5225 llvm_unreachable("@encoding ObjC primitive type");
5227 // OpenCL and placeholder types don't need @encodings.
5228 case BuiltinType::OCLImage1d:
5229 case BuiltinType::OCLImage1dArray:
5230 case BuiltinType::OCLImage1dBuffer:
5231 case BuiltinType::OCLImage2d:
5232 case BuiltinType::OCLImage2dArray:
5233 case BuiltinType::OCLImage3d:
5234 case BuiltinType::OCLEvent:
5235 case BuiltinType::OCLSampler:
5236 case BuiltinType::Dependent:
5237 #define BUILTIN_TYPE(KIND, ID)
5238 #define PLACEHOLDER_TYPE(KIND, ID) \
5239 case BuiltinType::KIND:
5240 #include "clang/AST/BuiltinTypes.def"
5241 llvm_unreachable("invalid builtin type for @encode");
5243 llvm_unreachable("invalid BuiltinType::Kind value");
5246 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5247 EnumDecl *Enum = ET->getDecl();
5249 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5250 if (!Enum->isFixed())
5253 // The encoding of a fixed enum type matches its fixed underlying type.
5254 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5255 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5258 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5259 QualType T, const FieldDecl *FD) {
5260 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5262 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5263 // The GNU runtime requires more information; bitfields are encoded as b,
5264 // then the offset (in bits) of the first element, then the type of the
5265 // bitfield, then the size in bits. For example, in this structure:
5272 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5273 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5274 // information is not especially sensible, but we're stuck with it for
5275 // compatibility with GCC, although providing it breaks anything that
5276 // actually uses runtime introspection and wants to work on both runtimes...
5277 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5278 const RecordDecl *RD = FD->getParent();
5279 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5280 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5281 if (const EnumType *ET = T->getAs<EnumType>())
5282 S += ObjCEncodingForEnumType(Ctx, ET);
5284 const BuiltinType *BT = T->castAs<BuiltinType>();
5285 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5288 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5291 // FIXME: Use SmallString for accumulating string.
5292 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5293 bool ExpandPointedToStructures,
5294 bool ExpandStructures,
5295 const FieldDecl *FD,
5297 bool EncodingProperty,
5299 bool EncodeBlockParameters,
5300 bool EncodeClassNames,
5301 bool EncodePointerToObjCTypedef,
5302 QualType *NotEncodedT) const {
5303 CanQualType CT = getCanonicalType(T);
5304 switch (CT->getTypeClass()) {
5307 if (FD && FD->isBitField())
5308 return EncodeBitField(this, S, T, FD);
5309 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5310 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5312 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5315 case Type::Complex: {
5316 const ComplexType *CT = T->castAs<ComplexType>();
5318 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5322 case Type::Atomic: {
5323 const AtomicType *AT = T->castAs<AtomicType>();
5325 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5329 // encoding for pointer or reference types.
5331 case Type::LValueReference:
5332 case Type::RValueReference: {
5334 if (isa<PointerType>(CT)) {
5335 const PointerType *PT = T->castAs<PointerType>();
5336 if (PT->isObjCSelType()) {
5340 PointeeTy = PT->getPointeeType();
5342 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5345 bool isReadOnly = false;
5346 // For historical/compatibility reasons, the read-only qualifier of the
5347 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5348 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5349 // Also, do not emit the 'r' for anything but the outermost type!
5350 if (isa<TypedefType>(T.getTypePtr())) {
5351 if (OutermostType && T.isConstQualified()) {
5355 } else if (OutermostType) {
5356 QualType P = PointeeTy;
5357 while (P->getAs<PointerType>())
5358 P = P->getAs<PointerType>()->getPointeeType();
5359 if (P.isConstQualified()) {
5365 // Another legacy compatibility encoding. Some ObjC qualifier and type
5366 // combinations need to be rearranged.
5367 // Rewrite "in const" from "nr" to "rn"
5368 if (StringRef(S).endswith("nr"))
5369 S.replace(S.end()-2, S.end(), "rn");
5372 if (PointeeTy->isCharType()) {
5373 // char pointer types should be encoded as '*' unless it is a
5374 // type that has been typedef'd to 'BOOL'.
5375 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5379 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5380 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5381 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5385 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5386 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5393 getLegacyIntegralTypeEncoding(PointeeTy);
5395 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5396 nullptr, false, false, false, false, false, false,
5401 case Type::ConstantArray:
5402 case Type::IncompleteArray:
5403 case Type::VariableArray: {
5404 const ArrayType *AT = cast<ArrayType>(CT);
5406 if (isa<IncompleteArrayType>(AT) && !StructField) {
5407 // Incomplete arrays are encoded as a pointer to the array element.
5410 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5411 false, ExpandStructures, FD);
5415 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5416 S += llvm::utostr(CAT->getSize().getZExtValue());
5418 //Variable length arrays are encoded as a regular array with 0 elements.
5419 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5420 "Unknown array type!");
5424 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5425 false, ExpandStructures, FD,
5426 false, false, false, false, false, false,
5433 case Type::FunctionNoProto:
5434 case Type::FunctionProto:
5438 case Type::Record: {
5439 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5440 S += RDecl->isUnion() ? '(' : '{';
5441 // Anonymous structures print as '?'
5442 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5444 if (ClassTemplateSpecializationDecl *Spec
5445 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5446 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5447 llvm::raw_string_ostream OS(S);
5448 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5449 TemplateArgs.data(),
5450 TemplateArgs.size(),
5451 (*this).getPrintingPolicy());
5456 if (ExpandStructures) {
5458 if (!RDecl->isUnion()) {
5459 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5461 for (const auto *Field : RDecl->fields()) {
5464 S += Field->getNameAsString();
5468 // Special case bit-fields.
5469 if (Field->isBitField()) {
5470 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5473 QualType qt = Field->getType();
5474 getLegacyIntegralTypeEncoding(qt);
5475 getObjCEncodingForTypeImpl(qt, S, false, true,
5476 FD, /*OutermostType*/false,
5477 /*EncodingProperty*/false,
5478 /*StructField*/true,
5479 false, false, false, NotEncodedT);
5484 S += RDecl->isUnion() ? ')' : '}';
5488 case Type::BlockPointer: {
5489 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5490 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5491 if (EncodeBlockParameters) {
5492 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5495 // Block return type
5496 getObjCEncodingForTypeImpl(
5497 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5498 FD, false /* OutermostType */, EncodingProperty,
5499 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5504 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5505 for (const auto &I : FPT->param_types())
5506 getObjCEncodingForTypeImpl(
5507 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5508 false /* OutermostType */, EncodingProperty,
5509 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5510 false, NotEncodedT);
5517 case Type::ObjCObject: {
5518 // hack to match legacy encoding of *id and *Class
5519 QualType Ty = getObjCObjectPointerType(CT);
5520 if (Ty->isObjCIdType()) {
5521 S += "{objc_object=}";
5524 else if (Ty->isObjCClassType()) {
5525 S += "{objc_class=}";
5530 case Type::ObjCInterface: {
5531 // Ignore protocol qualifiers when mangling at this level.
5532 T = T->castAs<ObjCObjectType>()->getBaseType();
5534 // The assumption seems to be that this assert will succeed
5535 // because nested levels will have filtered out 'id' and 'Class'.
5536 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5537 // @encode(class_name)
5538 ObjCInterfaceDecl *OI = OIT->getDecl();
5540 const IdentifierInfo *II = OI->getIdentifier();
5543 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5544 DeepCollectObjCIvars(OI, true, Ivars);
5545 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5546 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5547 if (Field->isBitField())
5548 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5550 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5551 false, false, false, false, false,
5552 EncodePointerToObjCTypedef,
5559 case Type::ObjCObjectPointer: {
5560 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5561 if (OPT->isObjCIdType()) {
5566 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5567 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5568 // Since this is a binary compatibility issue, need to consult with runtime
5569 // folks. Fortunately, this is a *very* obsure construct.
5574 if (OPT->isObjCQualifiedIdType()) {
5575 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5576 ExpandPointedToStructures,
5577 ExpandStructures, FD);
5578 if (FD || EncodingProperty || EncodeClassNames) {
5579 // Note that we do extended encoding of protocol qualifer list
5580 // Only when doing ivar or property encoding.
5582 for (const auto *I : OPT->quals()) {
5584 S += I->getNameAsString();
5592 QualType PointeeTy = OPT->getPointeeType();
5593 if (!EncodingProperty &&
5594 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5595 !EncodePointerToObjCTypedef) {
5596 // Another historical/compatibility reason.
5597 // We encode the underlying type which comes out as
5600 if (FD && OPT->getInterfaceDecl()) {
5601 // Prevent recursive encoding of fields in some rare cases.
5602 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5603 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5604 DeepCollectObjCIvars(OI, true, Ivars);
5605 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5606 if (cast<FieldDecl>(Ivars[i]) == FD) {
5608 S += OI->getIdentifier()->getName();
5614 getObjCEncodingForTypeImpl(PointeeTy, S,
5615 false, ExpandPointedToStructures,
5617 false, false, false, false, false,
5618 /*EncodePointerToObjCTypedef*/true);
5623 if (OPT->getInterfaceDecl() &&
5624 (FD || EncodingProperty || EncodeClassNames)) {
5626 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5627 for (const auto *I : OPT->quals()) {
5629 S += I->getNameAsString();
5637 // gcc just blithely ignores member pointers.
5638 // FIXME: we shoul do better than that. 'M' is available.
5639 case Type::MemberPointer:
5640 // This matches gcc's encoding, even though technically it is insufficient.
5641 //FIXME. We should do a better job than gcc.
5643 case Type::ExtVector:
5644 // Until we have a coherent encoding of these three types, issue warning.
5650 // We could see an undeduced auto type here during error recovery.
5656 #define ABSTRACT_TYPE(KIND, BASE)
5657 #define TYPE(KIND, BASE)
5658 #define DEPENDENT_TYPE(KIND, BASE) \
5660 #define NON_CANONICAL_TYPE(KIND, BASE) \
5662 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5664 #include "clang/AST/TypeNodes.def"
5665 llvm_unreachable("@encode for dependent type!");
5667 llvm_unreachable("bad type kind!");
5670 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5672 const FieldDecl *FD,
5674 QualType *NotEncodedT) const {
5675 assert(RDecl && "Expected non-null RecordDecl");
5676 assert(!RDecl->isUnion() && "Should not be called for unions");
5677 if (!RDecl->getDefinition())
5680 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5681 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5682 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5685 for (const auto &BI : CXXRec->bases()) {
5686 if (!BI.isVirtual()) {
5687 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5688 if (base->isEmpty())
5690 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5691 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5692 std::make_pair(offs, base));
5698 for (auto *Field : RDecl->fields()) {
5699 uint64_t offs = layout.getFieldOffset(i);
5700 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5701 std::make_pair(offs, Field));
5705 if (CXXRec && includeVBases) {
5706 for (const auto &BI : CXXRec->vbases()) {
5707 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5708 if (base->isEmpty())
5710 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5711 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5712 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5713 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5714 std::make_pair(offs, base));
5720 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5722 size = layout.getSize();
5726 uint64_t CurOffs = 0;
5728 std::multimap<uint64_t, NamedDecl *>::iterator
5729 CurLayObj = FieldOrBaseOffsets.begin();
5731 if (CXXRec && CXXRec->isDynamicClass() &&
5732 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5735 std::string recname = CXXRec->getNameAsString();
5736 if (recname.empty()) recname = "?";
5742 CurOffs += getTypeSize(VoidPtrTy);
5746 if (!RDecl->hasFlexibleArrayMember()) {
5747 // Mark the end of the structure.
5748 uint64_t offs = toBits(size);
5749 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5750 std::make_pair(offs, nullptr));
5753 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5755 assert(CurOffs <= CurLayObj->first);
5756 if (CurOffs < CurLayObj->first) {
5757 uint64_t padding = CurLayObj->first - CurOffs;
5758 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5759 // packing/alignment of members is different that normal, in which case
5760 // the encoding will be out-of-sync with the real layout.
5761 // If the runtime switches to just consider the size of types without
5762 // taking into account alignment, we could make padding explicit in the
5763 // encoding (e.g. using arrays of chars). The encoding strings would be
5764 // longer then though.
5769 NamedDecl *dcl = CurLayObj->second;
5771 break; // reached end of structure.
5773 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5774 // We expand the bases without their virtual bases since those are going
5775 // in the initial structure. Note that this differs from gcc which
5776 // expands virtual bases each time one is encountered in the hierarchy,
5777 // making the encoding type bigger than it really is.
5778 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5780 assert(!base->isEmpty());
5782 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5785 FieldDecl *field = cast<FieldDecl>(dcl);
5788 S += field->getNameAsString();
5792 if (field->isBitField()) {
5793 EncodeBitField(this, S, field->getType(), field);
5795 CurOffs += field->getBitWidthValue(*this);
5798 QualType qt = field->getType();
5799 getLegacyIntegralTypeEncoding(qt);
5800 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5801 /*OutermostType*/false,
5802 /*EncodingProperty*/false,
5803 /*StructField*/true,
5804 false, false, false, NotEncodedT);
5806 CurOffs += getTypeSize(field->getType());
5813 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5814 std::string& S) const {
5815 if (QT & Decl::OBJC_TQ_In)
5817 if (QT & Decl::OBJC_TQ_Inout)
5819 if (QT & Decl::OBJC_TQ_Out)
5821 if (QT & Decl::OBJC_TQ_Bycopy)
5823 if (QT & Decl::OBJC_TQ_Byref)
5825 if (QT & Decl::OBJC_TQ_Oneway)
5829 TypedefDecl *ASTContext::getObjCIdDecl() const {
5831 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
5832 T = getObjCObjectPointerType(T);
5833 ObjCIdDecl = buildImplicitTypedef(T, "id");
5838 TypedefDecl *ASTContext::getObjCSelDecl() const {
5840 QualType T = getPointerType(ObjCBuiltinSelTy);
5841 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5846 TypedefDecl *ASTContext::getObjCClassDecl() const {
5847 if (!ObjCClassDecl) {
5848 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
5849 T = getObjCObjectPointerType(T);
5850 ObjCClassDecl = buildImplicitTypedef(T, "Class");
5852 return ObjCClassDecl;
5855 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5856 if (!ObjCProtocolClassDecl) {
5857 ObjCProtocolClassDecl
5858 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5860 &Idents.get("Protocol"),
5861 /*PrevDecl=*/nullptr,
5862 SourceLocation(), true);
5865 return ObjCProtocolClassDecl;
5868 //===----------------------------------------------------------------------===//
5869 // __builtin_va_list Construction Functions
5870 //===----------------------------------------------------------------------===//
5872 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5873 // typedef char* __builtin_va_list;
5874 QualType T = Context->getPointerType(Context->CharTy);
5875 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5878 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5879 // typedef void* __builtin_va_list;
5880 QualType T = Context->getPointerType(Context->VoidTy);
5881 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5884 static TypedefDecl *
5885 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5887 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
5888 if (Context->getLangOpts().CPlusPlus) {
5889 // namespace std { struct __va_list {
5891 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5892 Context->getTranslationUnitDecl(),
5893 /*Inline*/ false, SourceLocation(),
5894 SourceLocation(), &Context->Idents.get("std"),
5895 /*PrevDecl*/ nullptr);
5897 VaListTagDecl->setDeclContext(NS);
5900 VaListTagDecl->startDefinition();
5902 const size_t NumFields = 5;
5903 QualType FieldTypes[NumFields];
5904 const char *FieldNames[NumFields];
5907 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5908 FieldNames[0] = "__stack";
5911 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5912 FieldNames[1] = "__gr_top";
5915 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5916 FieldNames[2] = "__vr_top";
5919 FieldTypes[3] = Context->IntTy;
5920 FieldNames[3] = "__gr_offs";
5923 FieldTypes[4] = Context->IntTy;
5924 FieldNames[4] = "__vr_offs";
5927 for (unsigned i = 0; i < NumFields; ++i) {
5928 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5932 &Context->Idents.get(FieldNames[i]),
5933 FieldTypes[i], /*TInfo=*/nullptr,
5934 /*BitWidth=*/nullptr,
5937 Field->setAccess(AS_public);
5938 VaListTagDecl->addDecl(Field);
5940 VaListTagDecl->completeDefinition();
5941 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5942 Context->VaListTagTy = VaListTagType;
5944 // } __builtin_va_list;
5945 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
5948 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5949 // typedef struct __va_list_tag {
5950 RecordDecl *VaListTagDecl;
5952 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5953 VaListTagDecl->startDefinition();
5955 const size_t NumFields = 5;
5956 QualType FieldTypes[NumFields];
5957 const char *FieldNames[NumFields];
5959 // unsigned char gpr;
5960 FieldTypes[0] = Context->UnsignedCharTy;
5961 FieldNames[0] = "gpr";
5963 // unsigned char fpr;
5964 FieldTypes[1] = Context->UnsignedCharTy;
5965 FieldNames[1] = "fpr";
5967 // unsigned short reserved;
5968 FieldTypes[2] = Context->UnsignedShortTy;
5969 FieldNames[2] = "reserved";
5971 // void* overflow_arg_area;
5972 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5973 FieldNames[3] = "overflow_arg_area";
5975 // void* reg_save_area;
5976 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5977 FieldNames[4] = "reg_save_area";
5980 for (unsigned i = 0; i < NumFields; ++i) {
5981 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5984 &Context->Idents.get(FieldNames[i]),
5985 FieldTypes[i], /*TInfo=*/nullptr,
5986 /*BitWidth=*/nullptr,
5989 Field->setAccess(AS_public);
5990 VaListTagDecl->addDecl(Field);
5992 VaListTagDecl->completeDefinition();
5993 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5994 Context->VaListTagTy = VaListTagType;
5997 TypedefDecl *VaListTagTypedefDecl =
5998 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6000 QualType VaListTagTypedefType =
6001 Context->getTypedefType(VaListTagTypedefDecl);
6003 // typedef __va_list_tag __builtin_va_list[1];
6004 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6005 QualType VaListTagArrayType
6006 = Context->getConstantArrayType(VaListTagTypedefType,
6007 Size, ArrayType::Normal, 0);
6008 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6011 static TypedefDecl *
6012 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6013 // typedef struct __va_list_tag {
6014 RecordDecl *VaListTagDecl;
6015 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6016 VaListTagDecl->startDefinition();
6018 const size_t NumFields = 4;
6019 QualType FieldTypes[NumFields];
6020 const char *FieldNames[NumFields];
6022 // unsigned gp_offset;
6023 FieldTypes[0] = Context->UnsignedIntTy;
6024 FieldNames[0] = "gp_offset";
6026 // unsigned fp_offset;
6027 FieldTypes[1] = Context->UnsignedIntTy;
6028 FieldNames[1] = "fp_offset";
6030 // void* overflow_arg_area;
6031 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6032 FieldNames[2] = "overflow_arg_area";
6034 // void* reg_save_area;
6035 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6036 FieldNames[3] = "reg_save_area";
6039 for (unsigned i = 0; i < NumFields; ++i) {
6040 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6044 &Context->Idents.get(FieldNames[i]),
6045 FieldTypes[i], /*TInfo=*/nullptr,
6046 /*BitWidth=*/nullptr,
6049 Field->setAccess(AS_public);
6050 VaListTagDecl->addDecl(Field);
6052 VaListTagDecl->completeDefinition();
6053 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6054 Context->VaListTagTy = VaListTagType;
6057 TypedefDecl *VaListTagTypedefDecl =
6058 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6060 QualType VaListTagTypedefType =
6061 Context->getTypedefType(VaListTagTypedefDecl);
6063 // typedef __va_list_tag __builtin_va_list[1];
6064 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6065 QualType VaListTagArrayType
6066 = Context->getConstantArrayType(VaListTagTypedefType,
6067 Size, ArrayType::Normal,0);
6068 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6071 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6072 // typedef int __builtin_va_list[4];
6073 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6074 QualType IntArrayType
6075 = Context->getConstantArrayType(Context->IntTy,
6076 Size, ArrayType::Normal, 0);
6077 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6080 static TypedefDecl *
6081 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6083 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6084 if (Context->getLangOpts().CPlusPlus) {
6085 // namespace std { struct __va_list {
6087 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6088 Context->getTranslationUnitDecl(),
6089 /*Inline*/false, SourceLocation(),
6090 SourceLocation(), &Context->Idents.get("std"),
6091 /*PrevDecl*/ nullptr);
6093 VaListDecl->setDeclContext(NS);
6096 VaListDecl->startDefinition();
6099 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6103 &Context->Idents.get("__ap"),
6104 Context->getPointerType(Context->VoidTy),
6106 /*BitWidth=*/nullptr,
6109 Field->setAccess(AS_public);
6110 VaListDecl->addDecl(Field);
6113 VaListDecl->completeDefinition();
6115 // typedef struct __va_list __builtin_va_list;
6116 QualType T = Context->getRecordType(VaListDecl);
6117 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6120 static TypedefDecl *
6121 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6122 // typedef struct __va_list_tag {
6123 RecordDecl *VaListTagDecl;
6124 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6125 VaListTagDecl->startDefinition();
6127 const size_t NumFields = 4;
6128 QualType FieldTypes[NumFields];
6129 const char *FieldNames[NumFields];
6132 FieldTypes[0] = Context->LongTy;
6133 FieldNames[0] = "__gpr";
6136 FieldTypes[1] = Context->LongTy;
6137 FieldNames[1] = "__fpr";
6139 // void *__overflow_arg_area;
6140 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6141 FieldNames[2] = "__overflow_arg_area";
6143 // void *__reg_save_area;
6144 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6145 FieldNames[3] = "__reg_save_area";
6148 for (unsigned i = 0; i < NumFields; ++i) {
6149 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6153 &Context->Idents.get(FieldNames[i]),
6154 FieldTypes[i], /*TInfo=*/nullptr,
6155 /*BitWidth=*/nullptr,
6158 Field->setAccess(AS_public);
6159 VaListTagDecl->addDecl(Field);
6161 VaListTagDecl->completeDefinition();
6162 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6163 Context->VaListTagTy = VaListTagType;
6166 TypedefDecl *VaListTagTypedefDecl =
6167 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6168 QualType VaListTagTypedefType =
6169 Context->getTypedefType(VaListTagTypedefDecl);
6171 // typedef __va_list_tag __builtin_va_list[1];
6172 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6173 QualType VaListTagArrayType
6174 = Context->getConstantArrayType(VaListTagTypedefType,
6175 Size, ArrayType::Normal,0);
6177 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6180 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6181 TargetInfo::BuiltinVaListKind Kind) {
6183 case TargetInfo::CharPtrBuiltinVaList:
6184 return CreateCharPtrBuiltinVaListDecl(Context);
6185 case TargetInfo::VoidPtrBuiltinVaList:
6186 return CreateVoidPtrBuiltinVaListDecl(Context);
6187 case TargetInfo::AArch64ABIBuiltinVaList:
6188 return CreateAArch64ABIBuiltinVaListDecl(Context);
6189 case TargetInfo::PowerABIBuiltinVaList:
6190 return CreatePowerABIBuiltinVaListDecl(Context);
6191 case TargetInfo::X86_64ABIBuiltinVaList:
6192 return CreateX86_64ABIBuiltinVaListDecl(Context);
6193 case TargetInfo::PNaClABIBuiltinVaList:
6194 return CreatePNaClABIBuiltinVaListDecl(Context);
6195 case TargetInfo::AAPCSABIBuiltinVaList:
6196 return CreateAAPCSABIBuiltinVaListDecl(Context);
6197 case TargetInfo::SystemZBuiltinVaList:
6198 return CreateSystemZBuiltinVaListDecl(Context);
6201 llvm_unreachable("Unhandled __builtin_va_list type kind");
6204 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6205 if (!BuiltinVaListDecl) {
6206 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6207 assert(BuiltinVaListDecl->isImplicit());
6210 return BuiltinVaListDecl;
6213 QualType ASTContext::getVaListTagType() const {
6214 // Force the creation of VaListTagTy by building the __builtin_va_list
6216 if (VaListTagTy.isNull())
6217 (void) getBuiltinVaListDecl();
6222 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6223 assert(ObjCConstantStringType.isNull() &&
6224 "'NSConstantString' type already set!");
6226 ObjCConstantStringType = getObjCInterfaceType(Decl);
6229 /// \brief Retrieve the template name that corresponds to a non-empty
6232 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6233 UnresolvedSetIterator End) const {
6234 unsigned size = End - Begin;
6235 assert(size > 1 && "set is not overloaded!");
6237 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6238 size * sizeof(FunctionTemplateDecl*));
6239 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6241 NamedDecl **Storage = OT->getStorage();
6242 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6244 assert(isa<FunctionTemplateDecl>(D) ||
6245 (isa<UsingShadowDecl>(D) &&
6246 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6250 return TemplateName(OT);
6253 /// \brief Retrieve the template name that represents a qualified
6254 /// template name such as \c std::vector.
6256 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6257 bool TemplateKeyword,
6258 TemplateDecl *Template) const {
6259 assert(NNS && "Missing nested-name-specifier in qualified template name");
6261 // FIXME: Canonicalization?
6262 llvm::FoldingSetNodeID ID;
6263 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6265 void *InsertPos = nullptr;
6266 QualifiedTemplateName *QTN =
6267 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6269 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6270 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6271 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6274 return TemplateName(QTN);
6277 /// \brief Retrieve the template name that represents a dependent
6278 /// template name such as \c MetaFun::template apply.
6280 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6281 const IdentifierInfo *Name) const {
6282 assert((!NNS || NNS->isDependent()) &&
6283 "Nested name specifier must be dependent");
6285 llvm::FoldingSetNodeID ID;
6286 DependentTemplateName::Profile(ID, NNS, Name);
6288 void *InsertPos = nullptr;
6289 DependentTemplateName *QTN =
6290 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6293 return TemplateName(QTN);
6295 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6296 if (CanonNNS == NNS) {
6297 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6298 DependentTemplateName(NNS, Name);
6300 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6301 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6302 DependentTemplateName(NNS, Name, Canon);
6303 DependentTemplateName *CheckQTN =
6304 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6305 assert(!CheckQTN && "Dependent type name canonicalization broken");
6309 DependentTemplateNames.InsertNode(QTN, InsertPos);
6310 return TemplateName(QTN);
6313 /// \brief Retrieve the template name that represents a dependent
6314 /// template name such as \c MetaFun::template operator+.
6316 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6317 OverloadedOperatorKind Operator) const {
6318 assert((!NNS || NNS->isDependent()) &&
6319 "Nested name specifier must be dependent");
6321 llvm::FoldingSetNodeID ID;
6322 DependentTemplateName::Profile(ID, NNS, Operator);
6324 void *InsertPos = nullptr;
6325 DependentTemplateName *QTN
6326 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6329 return TemplateName(QTN);
6331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6332 if (CanonNNS == NNS) {
6333 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6334 DependentTemplateName(NNS, Operator);
6336 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6337 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6338 DependentTemplateName(NNS, Operator, Canon);
6340 DependentTemplateName *CheckQTN
6341 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6342 assert(!CheckQTN && "Dependent template name canonicalization broken");
6346 DependentTemplateNames.InsertNode(QTN, InsertPos);
6347 return TemplateName(QTN);
6351 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6352 TemplateName replacement) const {
6353 llvm::FoldingSetNodeID ID;
6354 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6356 void *insertPos = nullptr;
6357 SubstTemplateTemplateParmStorage *subst
6358 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6361 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6362 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6365 return TemplateName(subst);
6369 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6370 const TemplateArgument &ArgPack) const {
6371 ASTContext &Self = const_cast<ASTContext &>(*this);
6372 llvm::FoldingSetNodeID ID;
6373 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6375 void *InsertPos = nullptr;
6376 SubstTemplateTemplateParmPackStorage *Subst
6377 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6380 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6381 ArgPack.pack_size(),
6382 ArgPack.pack_begin());
6383 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6386 return TemplateName(Subst);
6389 /// getFromTargetType - Given one of the integer types provided by
6390 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6391 /// is actually a value of type @c TargetInfo::IntType.
6392 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6394 case TargetInfo::NoInt: return CanQualType();
6395 case TargetInfo::SignedChar: return SignedCharTy;
6396 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6397 case TargetInfo::SignedShort: return ShortTy;
6398 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6399 case TargetInfo::SignedInt: return IntTy;
6400 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6401 case TargetInfo::SignedLong: return LongTy;
6402 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6403 case TargetInfo::SignedLongLong: return LongLongTy;
6404 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6407 llvm_unreachable("Unhandled TargetInfo::IntType value");
6410 //===----------------------------------------------------------------------===//
6412 //===----------------------------------------------------------------------===//
6414 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6415 /// garbage collection attribute.
6417 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6418 if (getLangOpts().getGC() == LangOptions::NonGC)
6419 return Qualifiers::GCNone;
6421 assert(getLangOpts().ObjC1);
6422 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6424 // Default behaviour under objective-C's gc is for ObjC pointers
6425 // (or pointers to them) be treated as though they were declared
6427 if (GCAttrs == Qualifiers::GCNone) {
6428 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6429 return Qualifiers::Strong;
6430 else if (Ty->isPointerType())
6431 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6433 // It's not valid to set GC attributes on anything that isn't a
6436 QualType CT = Ty->getCanonicalTypeInternal();
6437 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6438 CT = AT->getElementType();
6439 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6445 //===----------------------------------------------------------------------===//
6446 // Type Compatibility Testing
6447 //===----------------------------------------------------------------------===//
6449 /// areCompatVectorTypes - Return true if the two specified vector types are
6451 static bool areCompatVectorTypes(const VectorType *LHS,
6452 const VectorType *RHS) {
6453 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6454 return LHS->getElementType() == RHS->getElementType() &&
6455 LHS->getNumElements() == RHS->getNumElements();
6458 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6459 QualType SecondVec) {
6460 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6461 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6463 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6466 // Treat Neon vector types and most AltiVec vector types as if they are the
6467 // equivalent GCC vector types.
6468 const VectorType *First = FirstVec->getAs<VectorType>();
6469 const VectorType *Second = SecondVec->getAs<VectorType>();
6470 if (First->getNumElements() == Second->getNumElements() &&
6471 hasSameType(First->getElementType(), Second->getElementType()) &&
6472 First->getVectorKind() != VectorType::AltiVecPixel &&
6473 First->getVectorKind() != VectorType::AltiVecBool &&
6474 Second->getVectorKind() != VectorType::AltiVecPixel &&
6475 Second->getVectorKind() != VectorType::AltiVecBool)
6481 //===----------------------------------------------------------------------===//
6482 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6483 //===----------------------------------------------------------------------===//
6485 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6486 /// inheritance hierarchy of 'rProto'.
6488 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6489 ObjCProtocolDecl *rProto) const {
6490 if (declaresSameEntity(lProto, rProto))
6492 for (auto *PI : rProto->protocols())
6493 if (ProtocolCompatibleWithProtocol(lProto, PI))
6498 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6499 /// Class<pr1, ...>.
6500 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6502 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6503 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6504 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6506 for (auto *lhsProto : lhsQID->quals()) {
6508 for (auto *rhsProto : rhsOPT->quals()) {
6509 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6520 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6521 /// ObjCQualifiedIDType.
6522 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6524 // Allow id<P..> and an 'id' or void* type in all cases.
6525 if (lhs->isVoidPointerType() ||
6526 lhs->isObjCIdType() || lhs->isObjCClassType())
6528 else if (rhs->isVoidPointerType() ||
6529 rhs->isObjCIdType() || rhs->isObjCClassType())
6532 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6533 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6535 if (!rhsOPT) return false;
6537 if (rhsOPT->qual_empty()) {
6538 // If the RHS is a unqualified interface pointer "NSString*",
6539 // make sure we check the class hierarchy.
6540 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6541 for (auto *I : lhsQID->quals()) {
6542 // when comparing an id<P> on lhs with a static type on rhs,
6543 // see if static class implements all of id's protocols, directly or
6544 // through its super class and categories.
6545 if (!rhsID->ClassImplementsProtocol(I, true))
6549 // If there are no qualifiers and no interface, we have an 'id'.
6552 // Both the right and left sides have qualifiers.
6553 for (auto *lhsProto : lhsQID->quals()) {
6556 // when comparing an id<P> on lhs with a static type on rhs,
6557 // see if static class implements all of id's protocols, directly or
6558 // through its super class and categories.
6559 for (auto *rhsProto : rhsOPT->quals()) {
6560 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6561 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6566 // If the RHS is a qualified interface pointer "NSString<P>*",
6567 // make sure we check the class hierarchy.
6568 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6569 for (auto *I : lhsQID->quals()) {
6570 // when comparing an id<P> on lhs with a static type on rhs,
6571 // see if static class implements all of id's protocols, directly or
6572 // through its super class and categories.
6573 if (rhsID->ClassImplementsProtocol(I, true)) {
6586 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6587 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6589 if (const ObjCObjectPointerType *lhsOPT =
6590 lhs->getAsObjCInterfacePointerType()) {
6591 // If both the right and left sides have qualifiers.
6592 for (auto *lhsProto : lhsOPT->quals()) {
6595 // when comparing an id<P> on rhs with a static type on lhs,
6596 // see if static class implements all of id's protocols, directly or
6597 // through its super class and categories.
6598 // First, lhs protocols in the qualifier list must be found, direct
6599 // or indirect in rhs's qualifier list or it is a mismatch.
6600 for (auto *rhsProto : rhsQID->quals()) {
6601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6602 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6611 // Static class's protocols, or its super class or category protocols
6612 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6613 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6614 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6615 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6616 // This is rather dubious but matches gcc's behavior. If lhs has
6617 // no type qualifier and its class has no static protocol(s)
6618 // assume that it is mismatch.
6619 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6621 for (auto *lhsProto : LHSInheritedProtocols) {
6623 for (auto *rhsProto : rhsQID->quals()) {
6624 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6625 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6639 /// canAssignObjCInterfaces - Return true if the two interface types are
6640 /// compatible for assignment from RHS to LHS. This handles validation of any
6641 /// protocol qualifiers on the LHS or RHS.
6643 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6644 const ObjCObjectPointerType *RHSOPT) {
6645 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6646 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6648 // If either type represents the built-in 'id' or 'Class' types, return true.
6649 if (LHS->isObjCUnqualifiedIdOrClass() ||
6650 RHS->isObjCUnqualifiedIdOrClass())
6653 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6654 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6658 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6659 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6660 QualType(RHSOPT,0));
6662 // If we have 2 user-defined types, fall into that path.
6663 if (LHS->getInterface() && RHS->getInterface())
6664 return canAssignObjCInterfaces(LHS, RHS);
6669 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6670 /// for providing type-safety for objective-c pointers used to pass/return
6671 /// arguments in block literals. When passed as arguments, passing 'A*' where
6672 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6673 /// not OK. For the return type, the opposite is not OK.
6674 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6675 const ObjCObjectPointerType *LHSOPT,
6676 const ObjCObjectPointerType *RHSOPT,
6677 bool BlockReturnType) {
6678 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6681 if (LHSOPT->isObjCBuiltinType()) {
6682 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6685 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6686 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6690 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6691 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6692 if (LHS && RHS) { // We have 2 user-defined types.
6694 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6695 return BlockReturnType;
6696 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6697 return !BlockReturnType;
6705 /// getIntersectionOfProtocols - This routine finds the intersection of set
6706 /// of protocols inherited from two distinct objective-c pointer objects.
6707 /// It is used to build composite qualifier list of the composite type of
6708 /// the conditional expression involving two objective-c pointer objects.
6710 void getIntersectionOfProtocols(ASTContext &Context,
6711 const ObjCObjectPointerType *LHSOPT,
6712 const ObjCObjectPointerType *RHSOPT,
6713 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6715 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6716 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6717 assert(LHS->getInterface() && "LHS must have an interface base");
6718 assert(RHS->getInterface() && "RHS must have an interface base");
6720 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6721 unsigned LHSNumProtocols = LHS->getNumProtocols();
6722 if (LHSNumProtocols > 0)
6723 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6725 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6726 Context.CollectInheritedProtocols(LHS->getInterface(),
6727 LHSInheritedProtocols);
6728 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6729 LHSInheritedProtocols.end());
6732 unsigned RHSNumProtocols = RHS->getNumProtocols();
6733 if (RHSNumProtocols > 0) {
6734 ObjCProtocolDecl **RHSProtocols =
6735 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6736 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6737 if (InheritedProtocolSet.count(RHSProtocols[i]))
6738 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6741 Context.CollectInheritedProtocols(RHS->getInterface(),
6742 RHSInheritedProtocols);
6743 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6744 if (InheritedProtocolSet.count(ProtDecl))
6745 IntersectionOfProtocols.push_back(ProtDecl);
6749 /// areCommonBaseCompatible - Returns common base class of the two classes if
6750 /// one found. Note that this is O'2 algorithm. But it will be called as the
6751 /// last type comparison in a ?-exp of ObjC pointer types before a
6752 /// warning is issued. So, its invokation is extremely rare.
6753 QualType ASTContext::areCommonBaseCompatible(
6754 const ObjCObjectPointerType *Lptr,
6755 const ObjCObjectPointerType *Rptr) {
6756 const ObjCObjectType *LHS = Lptr->getObjectType();
6757 const ObjCObjectType *RHS = Rptr->getObjectType();
6758 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6759 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6760 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6764 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6765 if (canAssignObjCInterfaces(LHS, RHS)) {
6766 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6767 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6769 QualType Result = QualType(LHS, 0);
6770 if (!Protocols.empty())
6771 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6772 Result = getObjCObjectPointerType(Result);
6775 } while ((LDecl = LDecl->getSuperClass()));
6780 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6781 const ObjCObjectType *RHS) {
6782 assert(LHS->getInterface() && "LHS is not an interface type");
6783 assert(RHS->getInterface() && "RHS is not an interface type");
6785 // Verify that the base decls are compatible: the RHS must be a subclass of
6787 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6790 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6791 // protocol qualified at all, then we are good.
6792 if (LHS->getNumProtocols() == 0)
6795 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6796 // More detailed analysis is required.
6797 // OK, if LHS is same or a superclass of RHS *and*
6798 // this LHS, or as RHS's super class is assignment compatible with LHS.
6800 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6802 // OK if conversion of LHS to SuperClass results in narrowing of types
6803 // ; i.e., SuperClass may implement at least one of the protocols
6804 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6805 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6806 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6807 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6808 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6810 for (auto *RHSPI : RHS->quals())
6811 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6812 // If there is no protocols associated with RHS, it is not a match.
6813 if (SuperClassInheritedProtocols.empty())
6816 for (const auto *LHSProto : LHS->quals()) {
6817 bool SuperImplementsProtocol = false;
6818 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6819 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6820 SuperImplementsProtocol = true;
6823 if (!SuperImplementsProtocol)
6831 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6832 // get the "pointed to" types
6833 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6834 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6836 if (!LHSOPT || !RHSOPT)
6839 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6840 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6843 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6844 return canAssignObjCInterfaces(
6845 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6846 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6849 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6850 /// both shall have the identically qualified version of a compatible type.
6851 /// C99 6.2.7p1: Two types have compatible types if their types are the
6852 /// same. See 6.7.[2,3,5] for additional rules.
6853 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6854 bool CompareUnqualified) {
6855 if (getLangOpts().CPlusPlus)
6856 return hasSameType(LHS, RHS);
6858 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6861 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6862 return typesAreCompatible(LHS, RHS);
6865 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6866 return !mergeTypes(LHS, RHS, true).isNull();
6869 /// mergeTransparentUnionType - if T is a transparent union type and a member
6870 /// of T is compatible with SubType, return the merged type, else return
6872 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6873 bool OfBlockPointer,
6875 if (const RecordType *UT = T->getAsUnionType()) {
6876 RecordDecl *UD = UT->getDecl();
6877 if (UD->hasAttr<TransparentUnionAttr>()) {
6878 for (const auto *I : UD->fields()) {
6879 QualType ET = I->getType().getUnqualifiedType();
6880 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6890 /// mergeFunctionParameterTypes - merge two types which appear as function
6892 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6893 bool OfBlockPointer,
6895 // GNU extension: two types are compatible if they appear as a function
6896 // argument, one of the types is a transparent union type and the other
6897 // type is compatible with a union member
6898 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6900 if (!lmerge.isNull())
6903 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6905 if (!rmerge.isNull())
6908 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6911 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6912 bool OfBlockPointer,
6914 const FunctionType *lbase = lhs->getAs<FunctionType>();
6915 const FunctionType *rbase = rhs->getAs<FunctionType>();
6916 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6917 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6918 bool allLTypes = true;
6919 bool allRTypes = true;
6921 // Check return type
6923 if (OfBlockPointer) {
6924 QualType RHS = rbase->getReturnType();
6925 QualType LHS = lbase->getReturnType();
6926 bool UnqualifiedResult = Unqualified;
6927 if (!UnqualifiedResult)
6928 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6929 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6932 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
6934 if (retType.isNull()) return QualType();
6937 retType = retType.getUnqualifiedType();
6939 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6940 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
6942 LRetType = LRetType.getUnqualifiedType();
6943 RRetType = RRetType.getUnqualifiedType();
6946 if (getCanonicalType(retType) != LRetType)
6948 if (getCanonicalType(retType) != RRetType)
6951 // FIXME: double check this
6952 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6953 // rbase->getRegParmAttr() != 0 &&
6954 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6955 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6956 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6958 // Compatible functions must have compatible calling conventions
6959 if (lbaseInfo.getCC() != rbaseInfo.getCC())
6962 // Regparm is part of the calling convention.
6963 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6965 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6968 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6971 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6972 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6974 if (lbaseInfo.getNoReturn() != NoReturn)
6976 if (rbaseInfo.getNoReturn() != NoReturn)
6979 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6981 if (lproto && rproto) { // two C99 style function prototypes
6982 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6983 "C++ shouldn't be here");
6984 // Compatible functions must have the same number of parameters
6985 if (lproto->getNumParams() != rproto->getNumParams())
6988 // Variadic and non-variadic functions aren't compatible
6989 if (lproto->isVariadic() != rproto->isVariadic())
6992 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6995 if (LangOpts.ObjCAutoRefCount &&
6996 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6999 // Check parameter type compatibility
7000 SmallVector<QualType, 10> types;
7001 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7002 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7003 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7004 QualType paramType = mergeFunctionParameterTypes(
7005 lParamType, rParamType, OfBlockPointer, Unqualified);
7006 if (paramType.isNull())
7010 paramType = paramType.getUnqualifiedType();
7012 types.push_back(paramType);
7014 lParamType = lParamType.getUnqualifiedType();
7015 rParamType = rParamType.getUnqualifiedType();
7018 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7020 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7024 if (allLTypes) return lhs;
7025 if (allRTypes) return rhs;
7027 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7028 EPI.ExtInfo = einfo;
7029 return getFunctionType(retType, types, EPI);
7032 if (lproto) allRTypes = false;
7033 if (rproto) allLTypes = false;
7035 const FunctionProtoType *proto = lproto ? lproto : rproto;
7037 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7038 if (proto->isVariadic()) return QualType();
7039 // Check that the types are compatible with the types that
7040 // would result from default argument promotions (C99 6.7.5.3p15).
7041 // The only types actually affected are promotable integer
7042 // types and floats, which would be passed as a different
7043 // type depending on whether the prototype is visible.
7044 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7045 QualType paramTy = proto->getParamType(i);
7047 // Look at the converted type of enum types, since that is the type used
7048 // to pass enum values.
7049 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7050 paramTy = Enum->getDecl()->getIntegerType();
7051 if (paramTy.isNull())
7055 if (paramTy->isPromotableIntegerType() ||
7056 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7060 if (allLTypes) return lhs;
7061 if (allRTypes) return rhs;
7063 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7064 EPI.ExtInfo = einfo;
7065 return getFunctionType(retType, proto->getParamTypes(), EPI);
7068 if (allLTypes) return lhs;
7069 if (allRTypes) return rhs;
7070 return getFunctionNoProtoType(retType, einfo);
7073 /// Given that we have an enum type and a non-enum type, try to merge them.
7074 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7075 QualType other, bool isBlockReturnType) {
7076 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7077 // a signed integer type, or an unsigned integer type.
7078 // Compatibility is based on the underlying type, not the promotion
7080 QualType underlyingType = ET->getDecl()->getIntegerType();
7081 if (underlyingType.isNull()) return QualType();
7082 if (Context.hasSameType(underlyingType, other))
7085 // In block return types, we're more permissive and accept any
7086 // integral type of the same size.
7087 if (isBlockReturnType && other->isIntegerType() &&
7088 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7094 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7095 bool OfBlockPointer,
7096 bool Unqualified, bool BlockReturnType) {
7097 // C++ [expr]: If an expression initially has the type "reference to T", the
7098 // type is adjusted to "T" prior to any further analysis, the expression
7099 // designates the object or function denoted by the reference, and the
7100 // expression is an lvalue unless the reference is an rvalue reference and
7101 // the expression is a function call (possibly inside parentheses).
7102 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7103 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7106 LHS = LHS.getUnqualifiedType();
7107 RHS = RHS.getUnqualifiedType();
7110 QualType LHSCan = getCanonicalType(LHS),
7111 RHSCan = getCanonicalType(RHS);
7113 // If two types are identical, they are compatible.
7114 if (LHSCan == RHSCan)
7117 // If the qualifiers are different, the types aren't compatible... mostly.
7118 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7119 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7120 if (LQuals != RQuals) {
7121 // If any of these qualifiers are different, we have a type
7123 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7124 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7125 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7128 // Exactly one GC qualifier difference is allowed: __strong is
7129 // okay if the other type has no GC qualifier but is an Objective
7130 // C object pointer (i.e. implicitly strong by default). We fix
7131 // this by pretending that the unqualified type was actually
7132 // qualified __strong.
7133 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7134 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7135 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7137 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7140 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7141 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7143 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7144 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7149 // Okay, qualifiers are equal.
7151 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7152 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7154 // We want to consider the two function types to be the same for these
7155 // comparisons, just force one to the other.
7156 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7157 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7159 // Same as above for arrays
7160 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7161 LHSClass = Type::ConstantArray;
7162 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7163 RHSClass = Type::ConstantArray;
7165 // ObjCInterfaces are just specialized ObjCObjects.
7166 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7167 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7169 // Canonicalize ExtVector -> Vector.
7170 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7171 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7173 // If the canonical type classes don't match.
7174 if (LHSClass != RHSClass) {
7175 // Note that we only have special rules for turning block enum
7176 // returns into block int returns, not vice-versa.
7177 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7178 return mergeEnumWithInteger(*this, ETy, RHS, false);
7180 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7181 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7183 // allow block pointer type to match an 'id' type.
7184 if (OfBlockPointer && !BlockReturnType) {
7185 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7187 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7194 // The canonical type classes match.
7196 #define TYPE(Class, Base)
7197 #define ABSTRACT_TYPE(Class, Base)
7198 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7199 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7200 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7201 #include "clang/AST/TypeNodes.def"
7202 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7205 case Type::LValueReference:
7206 case Type::RValueReference:
7207 case Type::MemberPointer:
7208 llvm_unreachable("C++ should never be in mergeTypes");
7210 case Type::ObjCInterface:
7211 case Type::IncompleteArray:
7212 case Type::VariableArray:
7213 case Type::FunctionProto:
7214 case Type::ExtVector:
7215 llvm_unreachable("Types are eliminated above");
7219 // Merge two pointer types, while trying to preserve typedef info
7220 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7221 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7223 LHSPointee = LHSPointee.getUnqualifiedType();
7224 RHSPointee = RHSPointee.getUnqualifiedType();
7226 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7228 if (ResultType.isNull()) return QualType();
7229 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7231 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7233 return getPointerType(ResultType);
7235 case Type::BlockPointer:
7237 // Merge two block pointer types, while trying to preserve typedef info
7238 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7239 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7241 LHSPointee = LHSPointee.getUnqualifiedType();
7242 RHSPointee = RHSPointee.getUnqualifiedType();
7244 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7246 if (ResultType.isNull()) return QualType();
7247 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7249 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7251 return getBlockPointerType(ResultType);
7255 // Merge two pointer types, while trying to preserve typedef info
7256 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7257 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7259 LHSValue = LHSValue.getUnqualifiedType();
7260 RHSValue = RHSValue.getUnqualifiedType();
7262 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7264 if (ResultType.isNull()) return QualType();
7265 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7267 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7269 return getAtomicType(ResultType);
7271 case Type::ConstantArray:
7273 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7274 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7275 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7278 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7279 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7281 LHSElem = LHSElem.getUnqualifiedType();
7282 RHSElem = RHSElem.getUnqualifiedType();
7285 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7286 if (ResultType.isNull()) return QualType();
7287 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7289 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7291 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7292 ArrayType::ArraySizeModifier(), 0);
7293 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7294 ArrayType::ArraySizeModifier(), 0);
7295 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7296 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7297 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7299 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7302 // FIXME: This isn't correct! But tricky to implement because
7303 // the array's size has to be the size of LHS, but the type
7304 // has to be different.
7308 // FIXME: This isn't correct! But tricky to implement because
7309 // the array's size has to be the size of RHS, but the type
7310 // has to be different.
7313 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7314 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7315 return getIncompleteArrayType(ResultType,
7316 ArrayType::ArraySizeModifier(), 0);
7318 case Type::FunctionNoProto:
7319 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7324 // Only exactly equal builtin types are compatible, which is tested above.
7327 // Distinct complex types are incompatible.
7330 // FIXME: The merged type should be an ExtVector!
7331 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7332 RHSCan->getAs<VectorType>()))
7335 case Type::ObjCObject: {
7336 // Check if the types are assignment compatible.
7337 // FIXME: This should be type compatibility, e.g. whether
7338 // "LHS x; RHS x;" at global scope is legal.
7339 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7340 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7341 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7346 case Type::ObjCObjectPointer: {
7347 if (OfBlockPointer) {
7348 if (canAssignObjCInterfacesInBlockPointer(
7349 LHS->getAs<ObjCObjectPointerType>(),
7350 RHS->getAs<ObjCObjectPointerType>(),
7355 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7356 RHS->getAs<ObjCObjectPointerType>()))
7363 llvm_unreachable("Invalid Type::Class!");
7366 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7367 const FunctionProtoType *FromFunctionType,
7368 const FunctionProtoType *ToFunctionType) {
7369 if (FromFunctionType->hasAnyConsumedParams() !=
7370 ToFunctionType->hasAnyConsumedParams())
7372 FunctionProtoType::ExtProtoInfo FromEPI =
7373 FromFunctionType->getExtProtoInfo();
7374 FunctionProtoType::ExtProtoInfo ToEPI =
7375 ToFunctionType->getExtProtoInfo();
7376 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7377 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7378 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7384 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7385 /// 'RHS' attributes and returns the merged version; including for function
7387 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7388 QualType LHSCan = getCanonicalType(LHS),
7389 RHSCan = getCanonicalType(RHS);
7390 // If two types are identical, they are compatible.
7391 if (LHSCan == RHSCan)
7393 if (RHSCan->isFunctionType()) {
7394 if (!LHSCan->isFunctionType())
7396 QualType OldReturnType =
7397 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7398 QualType NewReturnType =
7399 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7400 QualType ResReturnType =
7401 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7402 if (ResReturnType.isNull())
7404 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7405 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7406 // In either case, use OldReturnType to build the new function type.
7407 const FunctionType *F = LHS->getAs<FunctionType>();
7408 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7410 EPI.ExtInfo = getFunctionExtInfo(LHS);
7411 QualType ResultType =
7412 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7419 // If the qualifiers are different, the types can still be merged.
7420 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7421 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7422 if (LQuals != RQuals) {
7423 // If any of these qualifiers are different, we have a type mismatch.
7424 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7425 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7428 // Exactly one GC qualifier difference is allowed: __strong is
7429 // okay if the other type has no GC qualifier but is an Objective
7430 // C object pointer (i.e. implicitly strong by default). We fix
7431 // this by pretending that the unqualified type was actually
7432 // qualified __strong.
7433 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7434 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7435 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7437 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7440 if (GC_L == Qualifiers::Strong)
7442 if (GC_R == Qualifiers::Strong)
7447 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7448 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7449 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7450 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7451 if (ResQT == LHSBaseQT)
7453 if (ResQT == RHSBaseQT)
7459 //===----------------------------------------------------------------------===//
7460 // Integer Predicates
7461 //===----------------------------------------------------------------------===//
7463 unsigned ASTContext::getIntWidth(QualType T) const {
7464 if (const EnumType *ET = T->getAs<EnumType>())
7465 T = ET->getDecl()->getIntegerType();
7466 if (T->isBooleanType())
7468 // For builtin types, just use the standard type sizing method
7469 return (unsigned)getTypeSize(T);
7472 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7473 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7475 // Turn <4 x signed int> -> <4 x unsigned int>
7476 if (const VectorType *VTy = T->getAs<VectorType>())
7477 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7478 VTy->getNumElements(), VTy->getVectorKind());
7480 // For enums, we return the unsigned version of the base type.
7481 if (const EnumType *ETy = T->getAs<EnumType>())
7482 T = ETy->getDecl()->getIntegerType();
7484 const BuiltinType *BTy = T->getAs<BuiltinType>();
7485 assert(BTy && "Unexpected signed integer type");
7486 switch (BTy->getKind()) {
7487 case BuiltinType::Char_S:
7488 case BuiltinType::SChar:
7489 return UnsignedCharTy;
7490 case BuiltinType::Short:
7491 return UnsignedShortTy;
7492 case BuiltinType::Int:
7493 return UnsignedIntTy;
7494 case BuiltinType::Long:
7495 return UnsignedLongTy;
7496 case BuiltinType::LongLong:
7497 return UnsignedLongLongTy;
7498 case BuiltinType::Int128:
7499 return UnsignedInt128Ty;
7501 llvm_unreachable("Unexpected signed integer type");
7505 ASTMutationListener::~ASTMutationListener() { }
7507 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7508 QualType ReturnType) {}
7510 //===----------------------------------------------------------------------===//
7511 // Builtin Type Computation
7512 //===----------------------------------------------------------------------===//
7514 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7515 /// pointer over the consumed characters. This returns the resultant type. If
7516 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7517 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7518 /// a vector of "i*".
7520 /// RequiresICE is filled in on return to indicate whether the value is required
7521 /// to be an Integer Constant Expression.
7522 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7523 ASTContext::GetBuiltinTypeError &Error,
7525 bool AllowTypeModifiers) {
7528 bool Signed = false, Unsigned = false;
7529 RequiresICE = false;
7531 // Read the prefixed modifiers first.
7535 default: Done = true; --Str; break;
7540 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7541 assert(!Signed && "Can't use 'S' modifier multiple times!");
7545 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7546 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7550 assert(HowLong <= 2 && "Can't have LLLL modifier");
7554 // This modifier represents int64 type.
7555 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7556 switch (Context.getTargetInfo().getInt64Type()) {
7558 llvm_unreachable("Unexpected integer type");
7559 case TargetInfo::SignedLong:
7562 case TargetInfo::SignedLongLong:
7571 // Read the base type.
7573 default: llvm_unreachable("Unknown builtin type letter!");
7575 assert(HowLong == 0 && !Signed && !Unsigned &&
7576 "Bad modifiers used with 'v'!");
7577 Type = Context.VoidTy;
7580 assert(HowLong == 0 && !Signed && !Unsigned &&
7581 "Bad modifiers used with 'f'!");
7582 Type = Context.HalfTy;
7585 assert(HowLong == 0 && !Signed && !Unsigned &&
7586 "Bad modifiers used with 'f'!");
7587 Type = Context.FloatTy;
7590 assert(HowLong < 2 && !Signed && !Unsigned &&
7591 "Bad modifiers used with 'd'!");
7593 Type = Context.LongDoubleTy;
7595 Type = Context.DoubleTy;
7598 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7600 Type = Context.UnsignedShortTy;
7602 Type = Context.ShortTy;
7606 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7607 else if (HowLong == 2)
7608 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7609 else if (HowLong == 1)
7610 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7612 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7615 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7617 Type = Context.SignedCharTy;
7619 Type = Context.UnsignedCharTy;
7621 Type = Context.CharTy;
7623 case 'b': // boolean
7624 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7625 Type = Context.BoolTy;
7627 case 'z': // size_t.
7628 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7629 Type = Context.getSizeType();
7632 Type = Context.getCFConstantStringType();
7635 Type = Context.getObjCIdType();
7638 Type = Context.getObjCSelType();
7641 Type = Context.getObjCSuperType();
7644 Type = Context.getBuiltinVaListType();
7645 assert(!Type.isNull() && "builtin va list type not initialized!");
7648 // This is a "reference" to a va_list; however, what exactly
7649 // this means depends on how va_list is defined. There are two
7650 // different kinds of va_list: ones passed by value, and ones
7651 // passed by reference. An example of a by-value va_list is
7652 // x86, where va_list is a char*. An example of by-ref va_list
7653 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7654 // we want this argument to be a char*&; for x86-64, we want
7655 // it to be a __va_list_tag*.
7656 Type = Context.getBuiltinVaListType();
7657 assert(!Type.isNull() && "builtin va list type not initialized!");
7658 if (Type->isArrayType())
7659 Type = Context.getArrayDecayedType(Type);
7661 Type = Context.getLValueReferenceType(Type);
7665 unsigned NumElements = strtoul(Str, &End, 10);
7666 assert(End != Str && "Missing vector size");
7669 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7670 RequiresICE, false);
7671 assert(!RequiresICE && "Can't require vector ICE");
7673 // TODO: No way to make AltiVec vectors in builtins yet.
7674 Type = Context.getVectorType(ElementType, NumElements,
7675 VectorType::GenericVector);
7681 unsigned NumElements = strtoul(Str, &End, 10);
7682 assert(End != Str && "Missing vector size");
7686 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7688 Type = Context.getExtVectorType(ElementType, NumElements);
7692 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7694 assert(!RequiresICE && "Can't require complex ICE");
7695 Type = Context.getComplexType(ElementType);
7699 Type = Context.getPointerDiffType();
7703 Type = Context.getFILEType();
7704 if (Type.isNull()) {
7705 Error = ASTContext::GE_Missing_stdio;
7711 Type = Context.getsigjmp_bufType();
7713 Type = Context.getjmp_bufType();
7715 if (Type.isNull()) {
7716 Error = ASTContext::GE_Missing_setjmp;
7721 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7722 Type = Context.getucontext_tType();
7724 if (Type.isNull()) {
7725 Error = ASTContext::GE_Missing_ucontext;
7730 Type = Context.getProcessIDType();
7734 // If there are modifiers and if we're allowed to parse them, go for it.
7735 Done = !AllowTypeModifiers;
7737 switch (char c = *Str++) {
7738 default: Done = true; --Str; break;
7741 // Both pointers and references can have their pointee types
7742 // qualified with an address space.
7744 unsigned AddrSpace = strtoul(Str, &End, 10);
7745 if (End != Str && AddrSpace != 0) {
7746 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7750 Type = Context.getPointerType(Type);
7752 Type = Context.getLValueReferenceType(Type);
7755 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7757 Type = Type.withConst();
7760 Type = Context.getVolatileType(Type);
7763 Type = Type.withRestrict();
7768 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7769 "Integer constant 'I' type must be an integer");
7774 /// GetBuiltinType - Return the type for the specified builtin.
7775 QualType ASTContext::GetBuiltinType(unsigned Id,
7776 GetBuiltinTypeError &Error,
7777 unsigned *IntegerConstantArgs) const {
7778 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7780 SmallVector<QualType, 8> ArgTypes;
7782 bool RequiresICE = false;
7784 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7786 if (Error != GE_None)
7789 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7791 while (TypeStr[0] && TypeStr[0] != '.') {
7792 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7793 if (Error != GE_None)
7796 // If this argument is required to be an IntegerConstantExpression and the
7797 // caller cares, fill in the bitmask we return.
7798 if (RequiresICE && IntegerConstantArgs)
7799 *IntegerConstantArgs |= 1 << ArgTypes.size();
7801 // Do array -> pointer decay. The builtin should use the decayed type.
7802 if (Ty->isArrayType())
7803 Ty = getArrayDecayedType(Ty);
7805 ArgTypes.push_back(Ty);
7808 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7809 "'.' should only occur at end of builtin type list!");
7811 FunctionType::ExtInfo EI(CC_C);
7812 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7814 bool Variadic = (TypeStr[0] == '.');
7816 // We really shouldn't be making a no-proto type here, especially in C++.
7817 if (ArgTypes.empty() && Variadic)
7818 return getFunctionNoProtoType(ResType, EI);
7820 FunctionProtoType::ExtProtoInfo EPI;
7822 EPI.Variadic = Variadic;
7824 return getFunctionType(ResType, ArgTypes, EPI);
7827 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7828 const FunctionDecl *FD) {
7829 if (!FD->isExternallyVisible())
7830 return GVA_Internal;
7832 GVALinkage External = GVA_StrongExternal;
7833 switch (FD->getTemplateSpecializationKind()) {
7834 case TSK_Undeclared:
7835 case TSK_ExplicitSpecialization:
7836 External = GVA_StrongExternal;
7839 case TSK_ExplicitInstantiationDefinition:
7840 return GVA_StrongODR;
7842 // C++11 [temp.explicit]p10:
7843 // [ Note: The intent is that an inline function that is the subject of
7844 // an explicit instantiation declaration will still be implicitly
7845 // instantiated when used so that the body can be considered for
7846 // inlining, but that no out-of-line copy of the inline function would be
7847 // generated in the translation unit. -- end note ]
7848 case TSK_ExplicitInstantiationDeclaration:
7849 return GVA_AvailableExternally;
7851 case TSK_ImplicitInstantiation:
7852 External = GVA_DiscardableODR;
7856 if (!FD->isInlined())
7859 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7860 !FD->hasAttr<DLLExportAttr>()) ||
7861 FD->hasAttr<GNUInlineAttr>()) {
7862 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7864 // GNU or C99 inline semantics. Determine whether this symbol should be
7865 // externally visible.
7866 if (FD->isInlineDefinitionExternallyVisible())
7869 // C99 inline semantics, where the symbol is not externally visible.
7870 return GVA_AvailableExternally;
7873 // Functions specified with extern and inline in -fms-compatibility mode
7874 // forcibly get emitted. While the body of the function cannot be later
7875 // replaced, the function definition cannot be discarded.
7876 if (FD->getMostRecentDecl()->isMSExternInline())
7877 return GVA_StrongODR;
7879 return GVA_DiscardableODR;
7882 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7883 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7884 // dllexport/dllimport on inline functions.
7885 if (D->hasAttr<DLLImportAttr>()) {
7886 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7887 return GVA_AvailableExternally;
7888 } else if (D->hasAttr<DLLExportAttr>()) {
7889 if (L == GVA_DiscardableODR)
7890 return GVA_StrongODR;
7895 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7896 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7900 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7901 const VarDecl *VD) {
7902 if (!VD->isExternallyVisible())
7903 return GVA_Internal;
7905 if (VD->isStaticLocal()) {
7906 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7907 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7908 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7909 LexicalContext = LexicalContext->getLexicalParent();
7911 // Let the static local variable inherit it's linkage from the nearest
7912 // enclosing function.
7914 StaticLocalLinkage =
7915 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
7917 // GVA_StrongODR function linkage is stronger than what we need,
7918 // downgrade to GVA_DiscardableODR.
7919 // This allows us to discard the variable if we never end up needing it.
7920 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7921 : StaticLocalLinkage;
7924 // MSVC treats in-class initialized static data members as definitions.
7925 // By giving them non-strong linkage, out-of-line definitions won't
7926 // cause link errors.
7927 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7928 return GVA_DiscardableODR;
7930 switch (VD->getTemplateSpecializationKind()) {
7931 case TSK_Undeclared:
7932 case TSK_ExplicitSpecialization:
7933 return GVA_StrongExternal;
7935 case TSK_ExplicitInstantiationDefinition:
7936 return GVA_StrongODR;
7938 case TSK_ExplicitInstantiationDeclaration:
7939 return GVA_AvailableExternally;
7941 case TSK_ImplicitInstantiation:
7942 return GVA_DiscardableODR;
7945 llvm_unreachable("Invalid Linkage!");
7948 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7949 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7953 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7954 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7955 if (!VD->isFileVarDecl())
7957 // Global named register variables (GNU extension) are never emitted.
7958 if (VD->getStorageClass() == SC_Register)
7960 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7961 // We never need to emit an uninstantiated function template.
7962 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7964 } else if (isa<OMPThreadPrivateDecl>(D))
7969 // If this is a member of a class template, we do not need to emit it.
7970 if (D->getDeclContext()->isDependentContext())
7973 // Weak references don't produce any output by themselves.
7974 if (D->hasAttr<WeakRefAttr>())
7977 // Aliases and used decls are required.
7978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7982 // Forward declarations aren't required.
7983 if (!FD->doesThisDeclarationHaveABody())
7984 return FD->doesDeclarationForceExternallyVisibleDefinition();
7986 // Constructors and destructors are required.
7987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7990 // The key function for a class is required. This rule only comes
7991 // into play when inline functions can be key functions, though.
7992 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7993 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7994 const CXXRecordDecl *RD = MD->getParent();
7995 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7996 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7997 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8003 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8005 // static, static inline, always_inline, and extern inline functions can
8006 // always be deferred. Normal inline functions can be deferred in C99/C++.
8007 // Implicit template instantiations can also be deferred in C++.
8008 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8009 Linkage == GVA_DiscardableODR)
8014 const VarDecl *VD = cast<VarDecl>(D);
8015 assert(VD->isFileVarDecl() && "Expected file scoped var");
8017 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8018 !isMSStaticDataMemberInlineDefinition(VD))
8021 // Variables that can be needed in other TUs are required.
8022 GVALinkage L = GetGVALinkageForVariable(VD);
8023 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8024 L != GVA_DiscardableODR)
8027 // Variables that have destruction with side-effects are required.
8028 if (VD->getType().isDestructedType())
8031 // Variables that have initialization with side-effects are required.
8032 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8038 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8039 bool IsCXXMethod) const {
8040 // Pass through to the C++ ABI object
8042 return ABI->getDefaultMethodCallConv(IsVariadic);
8044 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
8047 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8048 // Pass through to the C++ ABI object
8049 return ABI->isNearlyEmpty(RD);
8052 VTableContextBase *ASTContext::getVTableContext() {
8053 if (!VTContext.get()) {
8054 if (Target->getCXXABI().isMicrosoft())
8055 VTContext.reset(new MicrosoftVTableContext(*this));
8057 VTContext.reset(new ItaniumVTableContext(*this));
8059 return VTContext.get();
8062 MangleContext *ASTContext::createMangleContext() {
8063 switch (Target->getCXXABI().getKind()) {
8064 case TargetCXXABI::GenericAArch64:
8065 case TargetCXXABI::GenericItanium:
8066 case TargetCXXABI::GenericARM:
8067 case TargetCXXABI::iOS:
8068 case TargetCXXABI::iOS64:
8069 return ItaniumMangleContext::create(*this, getDiagnostics());
8070 case TargetCXXABI::Microsoft:
8071 return MicrosoftMangleContext::create(*this, getDiagnostics());
8073 llvm_unreachable("Unsupported ABI");
8076 CXXABI::~CXXABI() {}
8078 size_t ASTContext::getSideTableAllocatedMemory() const {
8079 return ASTRecordLayouts.getMemorySize() +
8080 llvm::capacity_in_bytes(ObjCLayouts) +
8081 llvm::capacity_in_bytes(KeyFunctions) +
8082 llvm::capacity_in_bytes(ObjCImpls) +
8083 llvm::capacity_in_bytes(BlockVarCopyInits) +
8084 llvm::capacity_in_bytes(DeclAttrs) +
8085 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8086 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8087 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8088 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8089 llvm::capacity_in_bytes(OverriddenMethods) +
8090 llvm::capacity_in_bytes(Types) +
8091 llvm::capacity_in_bytes(VariableArrayTypes) +
8092 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8095 /// getIntTypeForBitwidth -
8096 /// sets integer QualTy according to specified details:
8097 /// bitwidth, signed/unsigned.
8098 /// Returns empty type if there is no appropriate target types.
8099 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8100 unsigned Signed) const {
8101 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8102 CanQualType QualTy = getFromTargetType(Ty);
8103 if (!QualTy && DestWidth == 128)
8104 return Signed ? Int128Ty : UnsignedInt128Ty;
8108 /// getRealTypeForBitwidth -
8109 /// sets floating point QualTy according to specified bitwidth.
8110 /// Returns empty type if there is no appropriate target types.
8111 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8112 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8114 case TargetInfo::Float:
8116 case TargetInfo::Double:
8118 case TargetInfo::LongDouble:
8119 return LongDoubleTy;
8120 case TargetInfo::NoFloat:
8124 llvm_unreachable("Unhandled TargetInfo::RealType value");
8127 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8129 MangleNumbers[ND] = Number;
8132 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8133 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8134 MangleNumbers.find(ND);
8135 return I != MangleNumbers.end() ? I->second : 1;
8138 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8140 StaticLocalNumbers[VD] = Number;
8143 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8144 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8145 StaticLocalNumbers.find(VD);
8146 return I != StaticLocalNumbers.end() ? I->second : 1;
8149 MangleNumberingContext &
8150 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8151 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8152 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8154 MCtx = createMangleNumberingContext();
8158 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8159 return ABI->createMangleNumberingContext();
8162 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8163 ParamIndices[D] = index;
8166 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8167 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8168 assert(I != ParamIndices.end() &&
8169 "ParmIndices lacks entry set by ParmVarDecl");
8174 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8176 assert(E && E->getStorageDuration() == SD_Static &&
8177 "don't need to cache the computed value for this temporary");
8179 return &MaterializedTemporaryValues[E];
8181 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8182 MaterializedTemporaryValues.find(E);
8183 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
8186 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8187 const llvm::Triple &T = getTargetInfo().getTriple();
8188 if (!T.isOSDarwin())
8191 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8192 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8195 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8196 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8197 uint64_t Size = sizeChars.getQuantity();
8198 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8199 unsigned Align = alignChars.getQuantity();
8200 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8201 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8206 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8207 /// parents as defined by the \c RecursiveASTVisitor.
8209 /// Note that the relationship described here is purely in terms of AST
8210 /// traversal - there are other relationships (for example declaration context)
8211 /// in the AST that are better modeled by special matchers.
8213 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8214 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8217 /// \brief Builds and returns the translation unit's parent map.
8219 /// The caller takes ownership of the returned \c ParentMap.
8220 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8221 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8222 Visitor.TraverseDecl(&TU);
8223 return Visitor.Parents;
8227 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8229 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8232 bool shouldVisitTemplateInstantiations() const {
8235 bool shouldVisitImplicitCode() const {
8238 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8239 // are not triggered during data recursion.
8240 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8244 template <typename T>
8245 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8248 if (ParentStack.size() > 0) {
8249 // FIXME: Currently we add the same parent multiple times, but only
8250 // when no memoization data is available for the type.
8251 // For example when we visit all subexpressions of template
8252 // instantiations; this is suboptimal, but benign: the only way to
8253 // visit those is with hasAncestor / hasParent, and those do not create
8255 // The plan is to enable DynTypedNode to be storable in a map or hash
8256 // map. The main problem there is to implement hash functions /
8257 // comparison operators for all types that DynTypedNode supports that
8258 // do not have pointer identity.
8259 auto &NodeOrVector = (*Parents)[Node];
8260 if (NodeOrVector.isNull()) {
8261 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8263 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8265 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8266 auto *Vector = new ASTContext::ParentVector(1, *Node);
8267 NodeOrVector = Vector;
8270 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8273 NodeOrVector.template get<ASTContext::ParentVector *>();
8274 // Skip duplicates for types that have memoization data.
8275 // We must check that the type has memoization data before calling
8276 // std::find() because DynTypedNode::operator== can't compare all
8278 bool Found = ParentStack.back().getMemoizationData() &&
8279 std::find(Vector->begin(), Vector->end(),
8280 ParentStack.back()) != Vector->end();
8282 Vector->push_back(ParentStack.back());
8285 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8286 bool Result = (this ->* traverse) (Node);
8287 ParentStack.pop_back();
8291 bool TraverseDecl(Decl *DeclNode) {
8292 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8295 bool TraverseStmt(Stmt *StmtNode) {
8296 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8299 ASTContext::ParentMap *Parents;
8300 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8302 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8307 ArrayRef<ast_type_traits::DynTypedNode>
8308 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8309 assert(Node.getMemoizationData() &&
8310 "Invariant broken: only nodes that support memoization may be "
8311 "used in the parent map.");
8313 // We always need to run over the whole translation unit, as
8314 // hasAncestor can escape any subtree.
8316 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8318 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8319 if (I == AllParents->end()) {
8322 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8323 return llvm::makeArrayRef(N, 1);
8325 return *I->second.get<ParentVector *>();
8329 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8330 const ObjCMethodDecl *MethodImpl) {
8331 // No point trying to match an unavailable/deprecated mothod.
8332 if (MethodDecl->hasAttr<UnavailableAttr>()
8333 || MethodDecl->hasAttr<DeprecatedAttr>())
8335 if (MethodDecl->getObjCDeclQualifier() !=
8336 MethodImpl->getObjCDeclQualifier())
8338 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8341 if (MethodDecl->param_size() != MethodImpl->param_size())
8344 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8345 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8346 EF = MethodDecl->param_end();
8347 IM != EM && IF != EF; ++IM, ++IF) {
8348 const ParmVarDecl *DeclVar = (*IF);
8349 const ParmVarDecl *ImplVar = (*IM);
8350 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8352 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8355 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8359 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8360 // doesn't include ASTContext.h
8362 clang::LazyGenerationalUpdatePtr<
8363 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8364 clang::LazyGenerationalUpdatePtr<
8365 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8366 const clang::ASTContext &Ctx, Decl *Value);