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
706 return &FakeAddrSpaceMap;
708 return &T.getAddressSpaceMap();
712 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
713 const LangOptions &LangOpts) {
714 switch (LangOpts.getAddressSpaceMapMangling()) {
715 case LangOptions::ASMM_Target:
716 return TI.useAddressSpaceMapMangling();
717 case LangOptions::ASMM_On:
719 case LangOptions::ASMM_Off:
722 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
725 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
726 IdentifierTable &idents, SelectorTable &sels,
727 Builtin::Context &builtins)
728 : FunctionProtoTypes(this_()),
729 TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
732 GlobalNestedNameSpecifier(nullptr),
733 Int128Decl(nullptr), UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr),
735 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
736 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
739 jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
740 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
741 cudaConfigureCallDecl(nullptr),
742 NullTypeSourceInfo(QualType()),
743 FirstLocalImport(), LastLocalImport(),
744 SourceMgr(SM), LangOpts(LOpts),
745 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
746 Idents(idents), Selectors(sels),
747 BuiltinInfo(builtins),
748 DeclarationNames(*this),
749 ExternalSource(nullptr), Listener(nullptr),
750 Comments(SM), CommentsLoaded(false),
751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
754 TUDecl = TranslationUnitDecl::Create(*this);
757 ASTContext::~ASTContext() {
758 ReleaseParentMapEntries();
760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
764 // Call all of the deallocation functions on all of their targets.
765 for (DeallocationMap::const_iterator I = Deallocations.begin(),
766 E = Deallocations.end(); I != E; ++I)
767 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
768 (I->first)((I->second)[J]);
770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
789 A->second->~AttrVec();
791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
794 void ASTContext::ReleaseParentMapEntries() {
795 if (!AllParents) return;
796 for (const auto &Entry : *AllParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 assert(Entry.second.is<ParentVector *>());
801 delete Entry.second.get<ParentVector *>();
806 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
807 Deallocations[Callback].push_back(Data);
811 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
812 ExternalSource = Source;
815 void ASTContext::PrintStats() const {
816 llvm::errs() << "\n*** AST Context Stats:\n";
817 llvm::errs() << " " << Types.size() << " types total.\n";
819 unsigned counts[] = {
820 #define TYPE(Name, Parent) 0,
821 #define ABSTRACT_TYPE(Name, Parent)
822 #include "clang/AST/TypeNodes.def"
826 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
828 counts[(unsigned)T->getTypeClass()]++;
832 unsigned TotalBytes = 0;
833 #define TYPE(Name, Parent) \
835 llvm::errs() << " " << counts[Idx] << " " << #Name \
837 TotalBytes += counts[Idx] * sizeof(Name##Type); \
839 #define ABSTRACT_TYPE(Name, Parent)
840 #include "clang/AST/TypeNodes.def"
842 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
844 // Implicit special member functions.
845 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
846 << NumImplicitDefaultConstructors
847 << " implicit default constructors created\n";
848 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
849 << NumImplicitCopyConstructors
850 << " implicit copy constructors created\n";
851 if (getLangOpts().CPlusPlus)
852 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
853 << NumImplicitMoveConstructors
854 << " implicit move constructors created\n";
855 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
856 << NumImplicitCopyAssignmentOperators
857 << " implicit copy assignment operators created\n";
858 if (getLangOpts().CPlusPlus)
859 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
860 << NumImplicitMoveAssignmentOperators
861 << " implicit move assignment operators created\n";
862 llvm::errs() << NumImplicitDestructorsDeclared << "/"
863 << NumImplicitDestructors
864 << " implicit destructors created\n";
866 if (ExternalSource) {
867 llvm::errs() << "\n";
868 ExternalSource->PrintStats();
871 BumpAlloc.PrintStats();
874 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
875 RecordDecl::TagKind TK) const {
878 if (getLangOpts().CPlusPlus)
879 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
880 Loc, &Idents.get(Name));
882 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
884 NewDecl->setImplicit();
888 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
889 StringRef Name) const {
890 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
891 TypedefDecl *NewDecl = TypedefDecl::Create(
892 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
893 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
894 NewDecl->setImplicit();
898 TypedefDecl *ASTContext::getInt128Decl() const {
900 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
904 TypedefDecl *ASTContext::getUInt128Decl() const {
906 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
910 TypeDecl *ASTContext::getFloat128StubType() const {
911 assert(LangOpts.CPlusPlus && "should only be called for c++");
912 if (!Float128StubDecl)
913 Float128StubDecl = buildImplicitRecord("__float128");
915 return Float128StubDecl;
918 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
919 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
920 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
924 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
925 assert((!this->Target || this->Target == &Target) &&
926 "Incorrect target reinitialization");
927 assert(VoidTy.isNull() && "Context reinitialized?");
929 this->Target = &Target;
931 ABI.reset(createCXXABI(Target));
932 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
933 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
936 InitBuiltinType(VoidTy, BuiltinType::Void);
939 InitBuiltinType(BoolTy, BuiltinType::Bool);
941 if (LangOpts.CharIsSigned)
942 InitBuiltinType(CharTy, BuiltinType::Char_S);
944 InitBuiltinType(CharTy, BuiltinType::Char_U);
946 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
947 InitBuiltinType(ShortTy, BuiltinType::Short);
948 InitBuiltinType(IntTy, BuiltinType::Int);
949 InitBuiltinType(LongTy, BuiltinType::Long);
950 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
953 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
954 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
955 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
956 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
957 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
960 InitBuiltinType(FloatTy, BuiltinType::Float);
961 InitBuiltinType(DoubleTy, BuiltinType::Double);
962 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
964 // GNU extension, 128-bit integers.
965 InitBuiltinType(Int128Ty, BuiltinType::Int128);
966 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
969 if (TargetInfo::isTypeSigned(Target.getWCharType()))
970 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
971 else // -fshort-wchar makes wchar_t be unsigned.
972 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
973 if (LangOpts.CPlusPlus && LangOpts.WChar)
974 WideCharTy = WCharTy;
976 // C99 (or C++ using -fno-wchar).
977 WideCharTy = getFromTargetType(Target.getWCharType());
980 WIntTy = getFromTargetType(Target.getWIntType());
982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
983 InitBuiltinType(Char16Ty, BuiltinType::Char16);
985 Char16Ty = getFromTargetType(Target.getChar16Type());
987 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
988 InitBuiltinType(Char32Ty, BuiltinType::Char32);
990 Char32Ty = getFromTargetType(Target.getChar32Type());
992 // Placeholder type for type-dependent expressions whose type is
993 // completely unknown. No code should ever check a type against
994 // DependentTy and users should never see it; however, it is here to
995 // help diagnose failures to properly check for type-dependent
997 InitBuiltinType(DependentTy, BuiltinType::Dependent);
999 // Placeholder type for functions.
1000 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1002 // Placeholder type for bound members.
1003 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1005 // Placeholder type for pseudo-objects.
1006 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1008 // "any" type; useful for debugger-like clients.
1009 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1011 // Placeholder type for unbridged ARC casts.
1012 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1014 // Placeholder type for builtin functions.
1015 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1018 FloatComplexTy = getComplexType(FloatTy);
1019 DoubleComplexTy = getComplexType(DoubleTy);
1020 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1022 // Builtin types for 'id', 'Class', and 'SEL'.
1023 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1024 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1025 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1027 if (LangOpts.OpenCL) {
1028 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1029 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1030 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1031 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1032 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1033 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1035 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1036 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1039 // Builtin type for __objc_yes and __objc_no
1040 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1041 SignedCharTy : BoolTy);
1043 ObjCConstantStringType = QualType();
1045 ObjCSuperType = QualType();
1048 VoidPtrTy = getPointerType(VoidTy);
1050 // nullptr type (C++0x 2.14.7)
1051 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1053 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1054 InitBuiltinType(HalfTy, BuiltinType::Half);
1056 // Builtin type used to help define __builtin_va_list.
1057 VaListTagTy = QualType();
1060 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1061 return SourceMgr.getDiagnostics();
1064 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1065 AttrVec *&Result = DeclAttrs[D];
1067 void *Mem = Allocate(sizeof(AttrVec));
1068 Result = new (Mem) AttrVec;
1074 /// \brief Erase the attributes corresponding to the given declaration.
1075 void ASTContext::eraseDeclAttrs(const Decl *D) {
1076 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1077 if (Pos != DeclAttrs.end()) {
1078 Pos->second->~AttrVec();
1079 DeclAttrs.erase(Pos);
1084 MemberSpecializationInfo *
1085 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1086 assert(Var->isStaticDataMember() && "Not a static data member");
1087 return getTemplateOrSpecializationInfo(Var)
1088 .dyn_cast<MemberSpecializationInfo *>();
1091 ASTContext::TemplateOrSpecializationInfo
1092 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1093 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1094 TemplateOrInstantiation.find(Var);
1095 if (Pos == TemplateOrInstantiation.end())
1096 return TemplateOrSpecializationInfo();
1102 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1103 TemplateSpecializationKind TSK,
1104 SourceLocation PointOfInstantiation) {
1105 assert(Inst->isStaticDataMember() && "Not a static data member");
1106 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1107 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1108 Tmpl, TSK, PointOfInstantiation));
1112 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1113 TemplateOrSpecializationInfo TSI) {
1114 assert(!TemplateOrInstantiation[Inst] &&
1115 "Already noted what the variable was instantiated from");
1116 TemplateOrInstantiation[Inst] = TSI;
1119 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1120 const FunctionDecl *FD){
1121 assert(FD && "Specialization is 0");
1122 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1123 = ClassScopeSpecializationPattern.find(FD);
1124 if (Pos == ClassScopeSpecializationPattern.end())
1130 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1131 FunctionDecl *Pattern) {
1132 assert(FD && "Specialization is 0");
1133 assert(Pattern && "Class scope specialization pattern is 0");
1134 ClassScopeSpecializationPattern[FD] = Pattern;
1138 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1139 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1140 = InstantiatedFromUsingDecl.find(UUD);
1141 if (Pos == InstantiatedFromUsingDecl.end())
1148 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1149 assert((isa<UsingDecl>(Pattern) ||
1150 isa<UnresolvedUsingValueDecl>(Pattern) ||
1151 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1152 "pattern decl is not a using decl");
1153 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingDecl[Inst] = Pattern;
1158 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1159 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1160 = InstantiatedFromUsingShadowDecl.find(Inst);
1161 if (Pos == InstantiatedFromUsingShadowDecl.end())
1168 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1169 UsingShadowDecl *Pattern) {
1170 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1171 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1174 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1175 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1176 = InstantiatedFromUnnamedFieldDecl.find(Field);
1177 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1183 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1185 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1186 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1187 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1188 "Already noted what unnamed field was instantiated from");
1190 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1193 ASTContext::overridden_cxx_method_iterator
1194 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1195 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1196 = OverriddenMethods.find(Method->getCanonicalDecl());
1197 if (Pos == OverriddenMethods.end())
1200 return Pos->second.begin();
1203 ASTContext::overridden_cxx_method_iterator
1204 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1205 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1206 = OverriddenMethods.find(Method->getCanonicalDecl());
1207 if (Pos == OverriddenMethods.end())
1210 return Pos->second.end();
1214 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1215 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1216 = OverriddenMethods.find(Method->getCanonicalDecl());
1217 if (Pos == OverriddenMethods.end())
1220 return Pos->second.size();
1223 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1224 const CXXMethodDecl *Overridden) {
1225 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1226 OverriddenMethods[Method].push_back(Overridden);
1229 void ASTContext::getOverriddenMethods(
1231 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1234 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1235 Overridden.append(overridden_methods_begin(CXXMethod),
1236 overridden_methods_end(CXXMethod));
1240 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1244 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1245 Method->getOverriddenMethods(OverDecls);
1246 Overridden.append(OverDecls.begin(), OverDecls.end());
1249 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1250 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1251 assert(!Import->isFromASTFile() && "Non-local import declaration");
1252 if (!FirstLocalImport) {
1253 FirstLocalImport = Import;
1254 LastLocalImport = Import;
1258 LastLocalImport->NextLocalImport = Import;
1259 LastLocalImport = Import;
1262 //===----------------------------------------------------------------------===//
1263 // Type Sizing and Analysis
1264 //===----------------------------------------------------------------------===//
1266 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1267 /// scalar floating point type.
1268 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1269 const BuiltinType *BT = T->getAs<BuiltinType>();
1270 assert(BT && "Not a floating point type!");
1271 switch (BT->getKind()) {
1272 default: llvm_unreachable("Not a floating point type!");
1273 case BuiltinType::Half: return Target->getHalfFormat();
1274 case BuiltinType::Float: return Target->getFloatFormat();
1275 case BuiltinType::Double: return Target->getDoubleFormat();
1276 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1280 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1281 unsigned Align = Target->getCharWidth();
1283 bool UseAlignAttrOnly = false;
1284 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1285 Align = AlignFromAttr;
1287 // __attribute__((aligned)) can increase or decrease alignment
1288 // *except* on a struct or struct member, where it only increases
1289 // alignment unless 'packed' is also specified.
1291 // It is an error for alignas to decrease alignment, so we can
1292 // ignore that possibility; Sema should diagnose it.
1293 if (isa<FieldDecl>(D)) {
1294 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1295 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1297 UseAlignAttrOnly = true;
1300 else if (isa<FieldDecl>(D))
1302 D->hasAttr<PackedAttr>() ||
1303 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1305 // If we're using the align attribute only, just ignore everything
1306 // else about the declaration and its type.
1307 if (UseAlignAttrOnly) {
1310 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1311 QualType T = VD->getType();
1312 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1314 T = RT->getPointeeType();
1316 T = getPointerType(RT->getPointeeType());
1318 QualType BaseT = getBaseElementType(T);
1319 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1320 // Adjust alignments of declarations with array type by the
1321 // large-array alignment on the target.
1322 if (const ArrayType *arrayType = getAsArrayType(T)) {
1323 unsigned MinWidth = Target->getLargeArrayMinWidth();
1324 if (!ForAlignof && MinWidth) {
1325 if (isa<VariableArrayType>(arrayType))
1326 Align = std::max(Align, Target->getLargeArrayAlign());
1327 else if (isa<ConstantArrayType>(arrayType) &&
1328 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1329 Align = std::max(Align, Target->getLargeArrayAlign());
1332 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1333 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1334 if (VD->hasGlobalStorage())
1335 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1339 // Fields can be subject to extra alignment constraints, like if
1340 // the field is packed, the struct is packed, or the struct has a
1341 // a max-field-alignment constraint (#pragma pack). So calculate
1342 // the actual alignment of the field within the struct, and then
1343 // (as we're expected to) constrain that by the alignment of the type.
1344 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1345 const RecordDecl *Parent = Field->getParent();
1346 // We can only produce a sensible answer if the record is valid.
1347 if (!Parent->isInvalidDecl()) {
1348 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1350 // Start with the record's overall alignment.
1351 unsigned FieldAlign = toBits(Layout.getAlignment());
1353 // Use the GCD of that and the offset within the record.
1354 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1356 // Alignment is always a power of 2, so the GCD will be a power of 2,
1357 // which means we get to do this crazy thing instead of Euclid's.
1358 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1359 if (LowBitOfOffset < FieldAlign)
1360 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1363 Align = std::min(Align, FieldAlign);
1368 return toCharUnitsFromBits(Align);
1371 // getTypeInfoDataSizeInChars - Return the size of a type, in
1372 // chars. If the type is a record, its data size is returned. This is
1373 // the size of the memcpy that's performed when assigning this type
1374 // using a trivial copy/move assignment operator.
1375 std::pair<CharUnits, CharUnits>
1376 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1377 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1379 // In C++, objects can sometimes be allocated into the tail padding
1380 // of a base-class subobject. We decide whether that's possible
1381 // during class layout, so here we can just trust the layout results.
1382 if (getLangOpts().CPlusPlus) {
1383 if (const RecordType *RT = T->getAs<RecordType>()) {
1384 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1385 sizeAndAlign.first = layout.getDataSize();
1389 return sizeAndAlign;
1392 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1393 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1394 std::pair<CharUnits, CharUnits>
1395 static getConstantArrayInfoInChars(const ASTContext &Context,
1396 const ConstantArrayType *CAT) {
1397 std::pair<CharUnits, CharUnits> EltInfo =
1398 Context.getTypeInfoInChars(CAT->getElementType());
1399 uint64_t Size = CAT->getSize().getZExtValue();
1400 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1401 (uint64_t)(-1)/Size) &&
1402 "Overflow in array type char size evaluation");
1403 uint64_t Width = EltInfo.first.getQuantity() * Size;
1404 unsigned Align = EltInfo.second.getQuantity();
1405 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1406 Context.getTargetInfo().getPointerWidth(0) == 64)
1407 Width = llvm::RoundUpToAlignment(Width, Align);
1408 return std::make_pair(CharUnits::fromQuantity(Width),
1409 CharUnits::fromQuantity(Align));
1412 std::pair<CharUnits, CharUnits>
1413 ASTContext::getTypeInfoInChars(const Type *T) const {
1414 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1415 return getConstantArrayInfoInChars(*this, CAT);
1416 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1417 return std::make_pair(toCharUnitsFromBits(Info.first),
1418 toCharUnitsFromBits(Info.second));
1421 std::pair<CharUnits, CharUnits>
1422 ASTContext::getTypeInfoInChars(QualType T) const {
1423 return getTypeInfoInChars(T.getTypePtr());
1426 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1427 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1428 if (it != MemoizedTypeInfo.end())
1431 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1432 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1436 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1437 /// method does not work on incomplete types.
1439 /// FIXME: Pointers into different addr spaces could have different sizes and
1440 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1441 /// should take a QualType, &c.
1442 std::pair<uint64_t, unsigned>
1443 ASTContext::getTypeInfoImpl(const Type *T) const {
1446 switch (T->getTypeClass()) {
1447 #define TYPE(Class, Base)
1448 #define ABSTRACT_TYPE(Class, Base)
1449 #define NON_CANONICAL_TYPE(Class, Base)
1450 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1451 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1453 assert(!T->isDependentType() && "should not see dependent types here"); \
1454 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1455 #include "clang/AST/TypeNodes.def"
1456 llvm_unreachable("Should not see dependent types");
1458 case Type::FunctionNoProto:
1459 case Type::FunctionProto:
1460 // GCC extension: alignof(function) = 32 bits
1465 case Type::IncompleteArray:
1466 case Type::VariableArray:
1468 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1471 case Type::ConstantArray: {
1472 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1474 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1475 uint64_t Size = CAT->getSize().getZExtValue();
1476 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1477 "Overflow in array type bit size evaluation");
1478 Width = EltInfo.first*Size;
1479 Align = EltInfo.second;
1480 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1481 getTargetInfo().getPointerWidth(0) == 64)
1482 Width = llvm::RoundUpToAlignment(Width, Align);
1485 case Type::ExtVector:
1486 case Type::Vector: {
1487 const VectorType *VT = cast<VectorType>(T);
1488 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1489 Width = EltInfo.first*VT->getNumElements();
1491 // If the alignment is not a power of 2, round up to the next power of 2.
1492 // This happens for non-power-of-2 length vectors.
1493 if (Align & (Align-1)) {
1494 Align = llvm::NextPowerOf2(Align);
1495 Width = llvm::RoundUpToAlignment(Width, Align);
1497 // Adjust the alignment based on the target max.
1498 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1499 if (TargetVectorAlign && TargetVectorAlign < Align)
1500 Align = TargetVectorAlign;
1505 switch (cast<BuiltinType>(T)->getKind()) {
1506 default: llvm_unreachable("Unknown builtin type!");
1507 case BuiltinType::Void:
1508 // GCC extension: alignof(void) = 8 bits.
1513 case BuiltinType::Bool:
1514 Width = Target->getBoolWidth();
1515 Align = Target->getBoolAlign();
1517 case BuiltinType::Char_S:
1518 case BuiltinType::Char_U:
1519 case BuiltinType::UChar:
1520 case BuiltinType::SChar:
1521 Width = Target->getCharWidth();
1522 Align = Target->getCharAlign();
1524 case BuiltinType::WChar_S:
1525 case BuiltinType::WChar_U:
1526 Width = Target->getWCharWidth();
1527 Align = Target->getWCharAlign();
1529 case BuiltinType::Char16:
1530 Width = Target->getChar16Width();
1531 Align = Target->getChar16Align();
1533 case BuiltinType::Char32:
1534 Width = Target->getChar32Width();
1535 Align = Target->getChar32Align();
1537 case BuiltinType::UShort:
1538 case BuiltinType::Short:
1539 Width = Target->getShortWidth();
1540 Align = Target->getShortAlign();
1542 case BuiltinType::UInt:
1543 case BuiltinType::Int:
1544 Width = Target->getIntWidth();
1545 Align = Target->getIntAlign();
1547 case BuiltinType::ULong:
1548 case BuiltinType::Long:
1549 Width = Target->getLongWidth();
1550 Align = Target->getLongAlign();
1552 case BuiltinType::ULongLong:
1553 case BuiltinType::LongLong:
1554 Width = Target->getLongLongWidth();
1555 Align = Target->getLongLongAlign();
1557 case BuiltinType::Int128:
1558 case BuiltinType::UInt128:
1560 Align = 128; // int128_t is 128-bit aligned on all targets.
1562 case BuiltinType::Half:
1563 Width = Target->getHalfWidth();
1564 Align = Target->getHalfAlign();
1566 case BuiltinType::Float:
1567 Width = Target->getFloatWidth();
1568 Align = Target->getFloatAlign();
1570 case BuiltinType::Double:
1571 Width = Target->getDoubleWidth();
1572 Align = Target->getDoubleAlign();
1574 case BuiltinType::LongDouble:
1575 Width = Target->getLongDoubleWidth();
1576 Align = Target->getLongDoubleAlign();
1578 case BuiltinType::NullPtr:
1579 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1580 Align = Target->getPointerAlign(0); // == sizeof(void*)
1582 case BuiltinType::ObjCId:
1583 case BuiltinType::ObjCClass:
1584 case BuiltinType::ObjCSel:
1585 Width = Target->getPointerWidth(0);
1586 Align = Target->getPointerAlign(0);
1588 case BuiltinType::OCLSampler:
1589 // Samplers are modeled as integers.
1590 Width = Target->getIntWidth();
1591 Align = Target->getIntAlign();
1593 case BuiltinType::OCLEvent:
1594 case BuiltinType::OCLImage1d:
1595 case BuiltinType::OCLImage1dArray:
1596 case BuiltinType::OCLImage1dBuffer:
1597 case BuiltinType::OCLImage2d:
1598 case BuiltinType::OCLImage2dArray:
1599 case BuiltinType::OCLImage3d:
1600 // Currently these types are pointers to opaque types.
1601 Width = Target->getPointerWidth(0);
1602 Align = Target->getPointerAlign(0);
1606 case Type::ObjCObjectPointer:
1607 Width = Target->getPointerWidth(0);
1608 Align = Target->getPointerAlign(0);
1610 case Type::BlockPointer: {
1611 unsigned AS = getTargetAddressSpace(
1612 cast<BlockPointerType>(T)->getPointeeType());
1613 Width = Target->getPointerWidth(AS);
1614 Align = Target->getPointerAlign(AS);
1617 case Type::LValueReference:
1618 case Type::RValueReference: {
1619 // alignof and sizeof should never enter this code path here, so we go
1620 // the pointer route.
1621 unsigned AS = getTargetAddressSpace(
1622 cast<ReferenceType>(T)->getPointeeType());
1623 Width = Target->getPointerWidth(AS);
1624 Align = Target->getPointerAlign(AS);
1627 case Type::Pointer: {
1628 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1629 Width = Target->getPointerWidth(AS);
1630 Align = Target->getPointerAlign(AS);
1633 case Type::MemberPointer: {
1634 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1635 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1638 case Type::Complex: {
1639 // Complex types have the same alignment as their elements, but twice the
1641 std::pair<uint64_t, unsigned> EltInfo =
1642 getTypeInfo(cast<ComplexType>(T)->getElementType());
1643 Width = EltInfo.first*2;
1644 Align = EltInfo.second;
1647 case Type::ObjCObject:
1648 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1649 case Type::Adjusted:
1651 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1652 case Type::ObjCInterface: {
1653 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1654 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1655 Width = toBits(Layout.getSize());
1656 Align = toBits(Layout.getAlignment());
1661 const TagType *TT = cast<TagType>(T);
1663 if (TT->getDecl()->isInvalidDecl()) {
1669 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1670 return getTypeInfo(ET->getDecl()->getIntegerType());
1672 const RecordType *RT = cast<RecordType>(TT);
1673 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1674 Width = toBits(Layout.getSize());
1675 Align = toBits(Layout.getAlignment());
1679 case Type::SubstTemplateTypeParm:
1680 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1681 getReplacementType().getTypePtr());
1684 const AutoType *A = cast<AutoType>(T);
1685 assert(!A->getDeducedType().isNull() &&
1686 "cannot request the size of an undeduced or dependent auto type");
1687 return getTypeInfo(A->getDeducedType().getTypePtr());
1691 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1693 case Type::Typedef: {
1694 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1695 std::pair<uint64_t, unsigned> Info
1696 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1697 // If the typedef has an aligned attribute on it, it overrides any computed
1698 // alignment we have. This violates the GCC documentation (which says that
1699 // attribute(aligned) can only round up) but matches its implementation.
1700 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1703 Align = Info.second;
1708 case Type::Elaborated:
1709 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1711 case Type::Attributed:
1713 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1715 case Type::Atomic: {
1716 // Start with the base type information.
1717 std::pair<uint64_t, unsigned> Info
1718 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1720 Align = Info.second;
1722 // If the size of the type doesn't exceed the platform's max
1723 // atomic promotion width, make the size and alignment more
1724 // favorable to atomic operations:
1725 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1726 // Round the size up to a power of 2.
1727 if (!llvm::isPowerOf2_64(Width))
1728 Width = llvm::NextPowerOf2(Width);
1730 // Set the alignment equal to the size.
1731 Align = static_cast<unsigned>(Width);
1737 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1738 return std::make_pair(Width, Align);
1741 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1742 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1743 return CharUnits::fromQuantity(BitSize / getCharWidth());
1746 /// toBits - Convert a size in characters to a size in characters.
1747 int64_t ASTContext::toBits(CharUnits CharSize) const {
1748 return CharSize.getQuantity() * getCharWidth();
1751 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1752 /// This method does not work on incomplete types.
1753 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1754 return getTypeInfoInChars(T).first;
1756 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1757 return getTypeInfoInChars(T).first;
1760 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1761 /// characters. This method does not work on incomplete types.
1762 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1763 return toCharUnitsFromBits(getTypeAlign(T));
1765 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1766 return toCharUnitsFromBits(getTypeAlign(T));
1769 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1770 /// type for the current target in bits. This can be different than the ABI
1771 /// alignment in cases where it is beneficial for performance to overalign
1773 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1774 unsigned ABIAlign = getTypeAlign(T);
1776 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1777 return ABIAlign; // Never overalign on XCore.
1779 const TypedefType *TT = T->getAs<TypedefType>();
1781 // Double and long long should be naturally aligned if possible.
1782 T = T->getBaseElementTypeUnsafe();
1783 if (const ComplexType *CT = T->getAs<ComplexType>())
1784 T = CT->getElementType().getTypePtr();
1785 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1786 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1787 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1788 // Don't increase the alignment if an alignment attribute was specified on a
1789 // typedef declaration.
1790 if (!TT || !TT->getDecl()->getMaxAlignment())
1791 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1796 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1797 /// to a global variable of the specified type.
1798 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1799 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1802 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1803 /// should be given to a global variable of the specified type.
1804 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1805 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1808 /// DeepCollectObjCIvars -
1809 /// This routine first collects all declared, but not synthesized, ivars in
1810 /// super class and then collects all ivars, including those synthesized for
1811 /// current class. This routine is used for implementation of current class
1812 /// when all ivars, declared and synthesized are known.
1814 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1816 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1817 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1818 DeepCollectObjCIvars(SuperClass, false, Ivars);
1820 for (const auto *I : OI->ivars())
1823 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1824 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1825 Iv= Iv->getNextIvar())
1826 Ivars.push_back(Iv);
1830 /// CollectInheritedProtocols - Collect all protocols in current class and
1831 /// those inherited by it.
1832 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1833 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1834 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1835 // We can use protocol_iterator here instead of
1836 // all_referenced_protocol_iterator since we are walking all categories.
1837 for (auto *Proto : OI->all_referenced_protocols()) {
1838 Protocols.insert(Proto->getCanonicalDecl());
1839 for (auto *P : Proto->protocols()) {
1840 Protocols.insert(P->getCanonicalDecl());
1841 CollectInheritedProtocols(P, Protocols);
1845 // Categories of this Interface.
1846 for (const auto *Cat : OI->visible_categories())
1847 CollectInheritedProtocols(Cat, Protocols);
1849 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1851 CollectInheritedProtocols(SD, Protocols);
1852 SD = SD->getSuperClass();
1854 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1855 for (auto *Proto : OC->protocols()) {
1856 Protocols.insert(Proto->getCanonicalDecl());
1857 for (const auto *P : Proto->protocols())
1858 CollectInheritedProtocols(P, Protocols);
1860 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1861 for (auto *Proto : OP->protocols()) {
1862 Protocols.insert(Proto->getCanonicalDecl());
1863 for (const auto *P : Proto->protocols())
1864 CollectInheritedProtocols(P, Protocols);
1869 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1871 // Count ivars declared in class extension.
1872 for (const auto *Ext : OI->known_extensions())
1873 count += Ext->ivar_size();
1875 // Count ivar defined in this class's implementation. This
1876 // includes synthesized ivars.
1877 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1878 count += ImplDecl->ivar_size();
1883 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1887 // nullptr_t is always treated as null.
1888 if (E->getType()->isNullPtrType()) return true;
1890 if (E->getType()->isAnyPointerType() &&
1891 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1892 Expr::NPC_ValueDependentIsNull))
1895 // Unfortunately, __null has type 'int'.
1896 if (isa<GNUNullExpr>(E)) return true;
1901 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1902 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1903 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1904 I = ObjCImpls.find(D);
1905 if (I != ObjCImpls.end())
1906 return cast<ObjCImplementationDecl>(I->second);
1909 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1910 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1912 I = ObjCImpls.find(D);
1913 if (I != ObjCImpls.end())
1914 return cast<ObjCCategoryImplDecl>(I->second);
1918 /// \brief Set the implementation of ObjCInterfaceDecl.
1919 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1920 ObjCImplementationDecl *ImplD) {
1921 assert(IFaceD && ImplD && "Passed null params");
1922 ObjCImpls[IFaceD] = ImplD;
1924 /// \brief Set the implementation of ObjCCategoryDecl.
1925 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1926 ObjCCategoryImplDecl *ImplD) {
1927 assert(CatD && ImplD && "Passed null params");
1928 ObjCImpls[CatD] = ImplD;
1931 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1932 const NamedDecl *ND) const {
1933 if (const ObjCInterfaceDecl *ID =
1934 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1936 if (const ObjCCategoryDecl *CD =
1937 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1938 return CD->getClassInterface();
1939 if (const ObjCImplDecl *IMD =
1940 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1941 return IMD->getClassInterface();
1946 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1948 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1949 assert(VD && "Passed null params");
1950 assert(VD->hasAttr<BlocksAttr>() &&
1951 "getBlockVarCopyInits - not __block var");
1952 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1953 I = BlockVarCopyInits.find(VD);
1954 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
1957 /// \brief Set the copy inialization expression of a block var decl.
1958 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1959 assert(VD && Init && "Passed null params");
1960 assert(VD->hasAttr<BlocksAttr>() &&
1961 "setBlockVarCopyInits - not __block var");
1962 BlockVarCopyInits[VD] = Init;
1965 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1966 unsigned DataSize) const {
1968 DataSize = TypeLoc::getFullDataSizeForType(T);
1970 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1971 "incorrect data size provided to CreateTypeSourceInfo!");
1973 TypeSourceInfo *TInfo =
1974 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1975 new (TInfo) TypeSourceInfo(T);
1979 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1980 SourceLocation L) const {
1981 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1982 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1986 const ASTRecordLayout &
1987 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1988 return getObjCLayout(D, nullptr);
1991 const ASTRecordLayout &
1992 ASTContext::getASTObjCImplementationLayout(
1993 const ObjCImplementationDecl *D) const {
1994 return getObjCLayout(D->getClassInterface(), D);
1997 //===----------------------------------------------------------------------===//
1998 // Type creation/memoization methods
1999 //===----------------------------------------------------------------------===//
2002 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2003 unsigned fastQuals = quals.getFastQualifiers();
2004 quals.removeFastQualifiers();
2006 // Check if we've already instantiated this type.
2007 llvm::FoldingSetNodeID ID;
2008 ExtQuals::Profile(ID, baseType, quals);
2009 void *insertPos = nullptr;
2010 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2011 assert(eq->getQualifiers() == quals);
2012 return QualType(eq, fastQuals);
2015 // If the base type is not canonical, make the appropriate canonical type.
2017 if (!baseType->isCanonicalUnqualified()) {
2018 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2019 canonSplit.Quals.addConsistentQualifiers(quals);
2020 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2022 // Re-find the insert position.
2023 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2026 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2027 ExtQualNodes.InsertNode(eq, insertPos);
2028 return QualType(eq, fastQuals);
2032 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2033 QualType CanT = getCanonicalType(T);
2034 if (CanT.getAddressSpace() == AddressSpace)
2037 // If we are composing extended qualifiers together, merge together
2038 // into one ExtQuals node.
2039 QualifierCollector Quals;
2040 const Type *TypeNode = Quals.strip(T);
2042 // If this type already has an address space specified, it cannot get
2044 assert(!Quals.hasAddressSpace() &&
2045 "Type cannot be in multiple addr spaces!");
2046 Quals.addAddressSpace(AddressSpace);
2048 return getExtQualType(TypeNode, Quals);
2051 QualType ASTContext::getObjCGCQualType(QualType T,
2052 Qualifiers::GC GCAttr) const {
2053 QualType CanT = getCanonicalType(T);
2054 if (CanT.getObjCGCAttr() == GCAttr)
2057 if (const PointerType *ptr = T->getAs<PointerType>()) {
2058 QualType Pointee = ptr->getPointeeType();
2059 if (Pointee->isAnyPointerType()) {
2060 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2061 return getPointerType(ResultType);
2065 // If we are composing extended qualifiers together, merge together
2066 // into one ExtQuals node.
2067 QualifierCollector Quals;
2068 const Type *TypeNode = Quals.strip(T);
2070 // If this type already has an ObjCGC specified, it cannot get
2072 assert(!Quals.hasObjCGCAttr() &&
2073 "Type cannot have multiple ObjCGCs!");
2074 Quals.addObjCGCAttr(GCAttr);
2076 return getExtQualType(TypeNode, Quals);
2079 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2080 FunctionType::ExtInfo Info) {
2081 if (T->getExtInfo() == Info)
2085 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2086 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2088 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2091 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2094 return cast<FunctionType>(Result.getTypePtr());
2097 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2098 QualType ResultType) {
2099 FD = FD->getMostRecentDecl();
2101 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2103 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2104 if (FunctionDecl *Next = FD->getPreviousDecl())
2109 if (ASTMutationListener *L = getASTMutationListener())
2110 L->DeducedReturnType(FD, ResultType);
2113 /// getComplexType - Return the uniqued reference to the type for a complex
2114 /// number with the specified element type.
2115 QualType ASTContext::getComplexType(QualType T) const {
2116 // Unique pointers, to guarantee there is only one pointer of a particular
2118 llvm::FoldingSetNodeID ID;
2119 ComplexType::Profile(ID, T);
2121 void *InsertPos = nullptr;
2122 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(CT, 0);
2125 // If the pointee type isn't canonical, this won't be a canonical type either,
2126 // so fill in the canonical type field.
2128 if (!T.isCanonical()) {
2129 Canonical = getComplexType(getCanonicalType(T));
2131 // Get the new insert position for the node we care about.
2132 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2133 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2135 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2136 Types.push_back(New);
2137 ComplexTypes.InsertNode(New, InsertPos);
2138 return QualType(New, 0);
2141 /// getPointerType - Return the uniqued reference to the type for a pointer to
2142 /// the specified type.
2143 QualType ASTContext::getPointerType(QualType T) const {
2144 // Unique pointers, to guarantee there is only one pointer of a particular
2146 llvm::FoldingSetNodeID ID;
2147 PointerType::Profile(ID, T);
2149 void *InsertPos = nullptr;
2150 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2151 return QualType(PT, 0);
2153 // If the pointee type isn't canonical, this won't be a canonical type either,
2154 // so fill in the canonical type field.
2156 if (!T.isCanonical()) {
2157 Canonical = getPointerType(getCanonicalType(T));
2159 // Get the new insert position for the node we care about.
2160 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2163 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2164 Types.push_back(New);
2165 PointerTypes.InsertNode(New, InsertPos);
2166 return QualType(New, 0);
2169 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2170 llvm::FoldingSetNodeID ID;
2171 AdjustedType::Profile(ID, Orig, New);
2172 void *InsertPos = nullptr;
2173 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 return QualType(AT, 0);
2177 QualType Canonical = getCanonicalType(New);
2179 // Get the new insert position for the node we care about.
2180 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 assert(!AT && "Shouldn't be in the map!");
2183 AT = new (*this, TypeAlignment)
2184 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2185 Types.push_back(AT);
2186 AdjustedTypes.InsertNode(AT, InsertPos);
2187 return QualType(AT, 0);
2190 QualType ASTContext::getDecayedType(QualType T) const {
2191 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2196 // A declaration of a parameter as "array of type" shall be
2197 // adjusted to "qualified pointer to type", where the type
2198 // qualifiers (if any) are those specified within the [ and ] of
2199 // the array type derivation.
2200 if (T->isArrayType())
2201 Decayed = getArrayDecayedType(T);
2204 // A declaration of a parameter as "function returning type"
2205 // shall be adjusted to "pointer to function returning type", as
2207 if (T->isFunctionType())
2208 Decayed = getPointerType(T);
2210 llvm::FoldingSetNodeID ID;
2211 AdjustedType::Profile(ID, T, Decayed);
2212 void *InsertPos = nullptr;
2213 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2215 return QualType(AT, 0);
2217 QualType Canonical = getCanonicalType(Decayed);
2219 // Get the new insert position for the node we care about.
2220 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2221 assert(!AT && "Shouldn't be in the map!");
2223 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2224 Types.push_back(AT);
2225 AdjustedTypes.InsertNode(AT, InsertPos);
2226 return QualType(AT, 0);
2229 /// getBlockPointerType - Return the uniqued reference to the type for
2230 /// a pointer to the specified block.
2231 QualType ASTContext::getBlockPointerType(QualType T) const {
2232 assert(T->isFunctionType() && "block of function types only");
2233 // Unique pointers, to guarantee there is only one block of a particular
2235 llvm::FoldingSetNodeID ID;
2236 BlockPointerType::Profile(ID, T);
2238 void *InsertPos = nullptr;
2239 if (BlockPointerType *PT =
2240 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2241 return QualType(PT, 0);
2243 // If the block pointee type isn't canonical, this won't be a canonical
2244 // type either so fill in the canonical type field.
2246 if (!T.isCanonical()) {
2247 Canonical = getBlockPointerType(getCanonicalType(T));
2249 // Get the new insert position for the node we care about.
2250 BlockPointerType *NewIP =
2251 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2252 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2254 BlockPointerType *New
2255 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2256 Types.push_back(New);
2257 BlockPointerTypes.InsertNode(New, InsertPos);
2258 return QualType(New, 0);
2261 /// getLValueReferenceType - Return the uniqued reference to the type for an
2262 /// lvalue reference to the specified type.
2264 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2265 assert(getCanonicalType(T) != OverloadTy &&
2266 "Unresolved overloaded function type");
2268 // Unique pointers, to guarantee there is only one pointer of a particular
2270 llvm::FoldingSetNodeID ID;
2271 ReferenceType::Profile(ID, T, SpelledAsLValue);
2273 void *InsertPos = nullptr;
2274 if (LValueReferenceType *RT =
2275 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2276 return QualType(RT, 0);
2278 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2280 // If the referencee type isn't canonical, this won't be a canonical type
2281 // either, so fill in the canonical type field.
2283 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2284 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2285 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2287 // Get the new insert position for the node we care about.
2288 LValueReferenceType *NewIP =
2289 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2290 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2293 LValueReferenceType *New
2294 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2296 Types.push_back(New);
2297 LValueReferenceTypes.InsertNode(New, InsertPos);
2299 return QualType(New, 0);
2302 /// getRValueReferenceType - Return the uniqued reference to the type for an
2303 /// rvalue reference to the specified type.
2304 QualType ASTContext::getRValueReferenceType(QualType T) const {
2305 // Unique pointers, to guarantee there is only one pointer of a particular
2307 llvm::FoldingSetNodeID ID;
2308 ReferenceType::Profile(ID, T, false);
2310 void *InsertPos = nullptr;
2311 if (RValueReferenceType *RT =
2312 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2313 return QualType(RT, 0);
2315 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2317 // If the referencee type isn't canonical, this won't be a canonical type
2318 // either, so fill in the canonical type field.
2320 if (InnerRef || !T.isCanonical()) {
2321 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2322 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2324 // Get the new insert position for the node we care about.
2325 RValueReferenceType *NewIP =
2326 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2327 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2330 RValueReferenceType *New
2331 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2332 Types.push_back(New);
2333 RValueReferenceTypes.InsertNode(New, InsertPos);
2334 return QualType(New, 0);
2337 /// getMemberPointerType - Return the uniqued reference to the type for a
2338 /// member pointer to the specified type, in the specified class.
2339 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2340 // Unique pointers, to guarantee there is only one pointer of a particular
2342 llvm::FoldingSetNodeID ID;
2343 MemberPointerType::Profile(ID, T, Cls);
2345 void *InsertPos = nullptr;
2346 if (MemberPointerType *PT =
2347 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2348 return QualType(PT, 0);
2350 // If the pointee or class type isn't canonical, this won't be a canonical
2351 // type either, so fill in the canonical type field.
2353 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2354 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2356 // Get the new insert position for the node we care about.
2357 MemberPointerType *NewIP =
2358 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2359 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2361 MemberPointerType *New
2362 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2363 Types.push_back(New);
2364 MemberPointerTypes.InsertNode(New, InsertPos);
2365 return QualType(New, 0);
2368 /// getConstantArrayType - Return the unique reference to the type for an
2369 /// array of the specified element type.
2370 QualType ASTContext::getConstantArrayType(QualType EltTy,
2371 const llvm::APInt &ArySizeIn,
2372 ArrayType::ArraySizeModifier ASM,
2373 unsigned IndexTypeQuals) const {
2374 assert((EltTy->isDependentType() ||
2375 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2376 "Constant array of VLAs is illegal!");
2378 // Convert the array size into a canonical width matching the pointer size for
2380 llvm::APInt ArySize(ArySizeIn);
2382 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2384 llvm::FoldingSetNodeID ID;
2385 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2387 void *InsertPos = nullptr;
2388 if (ConstantArrayType *ATP =
2389 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2390 return QualType(ATP, 0);
2392 // If the element type isn't canonical or has qualifiers, this won't
2393 // be a canonical type either, so fill in the canonical type field.
2395 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2396 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2397 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2398 ASM, IndexTypeQuals);
2399 Canon = getQualifiedType(Canon, canonSplit.Quals);
2401 // Get the new insert position for the node we care about.
2402 ConstantArrayType *NewIP =
2403 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2404 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2407 ConstantArrayType *New = new(*this,TypeAlignment)
2408 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2409 ConstantArrayTypes.InsertNode(New, InsertPos);
2410 Types.push_back(New);
2411 return QualType(New, 0);
2414 /// getVariableArrayDecayedType - Turns the given type, which may be
2415 /// variably-modified, into the corresponding type with all the known
2416 /// sizes replaced with [*].
2417 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2418 // Vastly most common case.
2419 if (!type->isVariablyModifiedType()) return type;
2423 SplitQualType split = type.getSplitDesugaredType();
2424 const Type *ty = split.Ty;
2425 switch (ty->getTypeClass()) {
2426 #define TYPE(Class, Base)
2427 #define ABSTRACT_TYPE(Class, Base)
2428 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2429 #include "clang/AST/TypeNodes.def"
2430 llvm_unreachable("didn't desugar past all non-canonical types?");
2432 // These types should never be variably-modified.
2436 case Type::ExtVector:
2437 case Type::DependentSizedExtVector:
2438 case Type::ObjCObject:
2439 case Type::ObjCInterface:
2440 case Type::ObjCObjectPointer:
2443 case Type::UnresolvedUsing:
2444 case Type::TypeOfExpr:
2446 case Type::Decltype:
2447 case Type::UnaryTransform:
2448 case Type::DependentName:
2449 case Type::InjectedClassName:
2450 case Type::TemplateSpecialization:
2451 case Type::DependentTemplateSpecialization:
2452 case Type::TemplateTypeParm:
2453 case Type::SubstTemplateTypeParmPack:
2455 case Type::PackExpansion:
2456 llvm_unreachable("type should never be variably-modified");
2458 // These types can be variably-modified but should never need to
2460 case Type::FunctionNoProto:
2461 case Type::FunctionProto:
2462 case Type::BlockPointer:
2463 case Type::MemberPointer:
2466 // These types can be variably-modified. All these modifications
2467 // preserve structure except as noted by comments.
2468 // TODO: if we ever care about optimizing VLAs, there are no-op
2469 // optimizations available here.
2471 result = getPointerType(getVariableArrayDecayedType(
2472 cast<PointerType>(ty)->getPointeeType()));
2475 case Type::LValueReference: {
2476 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2477 result = getLValueReferenceType(
2478 getVariableArrayDecayedType(lv->getPointeeType()),
2479 lv->isSpelledAsLValue());
2483 case Type::RValueReference: {
2484 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2485 result = getRValueReferenceType(
2486 getVariableArrayDecayedType(lv->getPointeeType()));
2490 case Type::Atomic: {
2491 const AtomicType *at = cast<AtomicType>(ty);
2492 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2496 case Type::ConstantArray: {
2497 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2498 result = getConstantArrayType(
2499 getVariableArrayDecayedType(cat->getElementType()),
2501 cat->getSizeModifier(),
2502 cat->getIndexTypeCVRQualifiers());
2506 case Type::DependentSizedArray: {
2507 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2508 result = getDependentSizedArrayType(
2509 getVariableArrayDecayedType(dat->getElementType()),
2511 dat->getSizeModifier(),
2512 dat->getIndexTypeCVRQualifiers(),
2513 dat->getBracketsRange());
2517 // Turn incomplete types into [*] types.
2518 case Type::IncompleteArray: {
2519 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2520 result = getVariableArrayType(
2521 getVariableArrayDecayedType(iat->getElementType()),
2524 iat->getIndexTypeCVRQualifiers(),
2529 // Turn VLA types into [*] types.
2530 case Type::VariableArray: {
2531 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2532 result = getVariableArrayType(
2533 getVariableArrayDecayedType(vat->getElementType()),
2536 vat->getIndexTypeCVRQualifiers(),
2537 vat->getBracketsRange());
2542 // Apply the top-level qualifiers from the original.
2543 return getQualifiedType(result, split.Quals);
2546 /// getVariableArrayType - Returns a non-unique reference to the type for a
2547 /// variable array of the specified element type.
2548 QualType ASTContext::getVariableArrayType(QualType EltTy,
2550 ArrayType::ArraySizeModifier ASM,
2551 unsigned IndexTypeQuals,
2552 SourceRange Brackets) const {
2553 // Since we don't unique expressions, it isn't possible to unique VLA's
2554 // that have an expression provided for their size.
2557 // Be sure to pull qualifiers off the element type.
2558 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2559 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2560 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2561 IndexTypeQuals, Brackets);
2562 Canon = getQualifiedType(Canon, canonSplit.Quals);
2565 VariableArrayType *New = new(*this, TypeAlignment)
2566 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2568 VariableArrayTypes.push_back(New);
2569 Types.push_back(New);
2570 return QualType(New, 0);
2573 /// getDependentSizedArrayType - Returns a non-unique reference to
2574 /// the type for a dependently-sized array of the specified element
2576 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2578 ArrayType::ArraySizeModifier ASM,
2579 unsigned elementTypeQuals,
2580 SourceRange brackets) const {
2581 assert((!numElements || numElements->isTypeDependent() ||
2582 numElements->isValueDependent()) &&
2583 "Size must be type- or value-dependent!");
2585 // Dependently-sized array types that do not have a specified number
2586 // of elements will have their sizes deduced from a dependent
2587 // initializer. We do no canonicalization here at all, which is okay
2588 // because they can't be used in most locations.
2590 DependentSizedArrayType *newType
2591 = new (*this, TypeAlignment)
2592 DependentSizedArrayType(*this, elementType, QualType(),
2593 numElements, ASM, elementTypeQuals,
2595 Types.push_back(newType);
2596 return QualType(newType, 0);
2599 // Otherwise, we actually build a new type every time, but we
2600 // also build a canonical type.
2602 SplitQualType canonElementType = getCanonicalType(elementType).split();
2604 void *insertPos = nullptr;
2605 llvm::FoldingSetNodeID ID;
2606 DependentSizedArrayType::Profile(ID, *this,
2607 QualType(canonElementType.Ty, 0),
2608 ASM, elementTypeQuals, numElements);
2610 // Look for an existing type with these properties.
2611 DependentSizedArrayType *canonTy =
2612 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2614 // If we don't have one, build one.
2616 canonTy = new (*this, TypeAlignment)
2617 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2618 QualType(), numElements, ASM, elementTypeQuals,
2620 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2621 Types.push_back(canonTy);
2624 // Apply qualifiers from the element type to the array.
2625 QualType canon = getQualifiedType(QualType(canonTy,0),
2626 canonElementType.Quals);
2628 // If we didn't need extra canonicalization for the element type,
2629 // then just use that as our result.
2630 if (QualType(canonElementType.Ty, 0) == elementType)
2633 // Otherwise, we need to build a type which follows the spelling
2634 // of the element type.
2635 DependentSizedArrayType *sugaredType
2636 = new (*this, TypeAlignment)
2637 DependentSizedArrayType(*this, elementType, canon, numElements,
2638 ASM, elementTypeQuals, brackets);
2639 Types.push_back(sugaredType);
2640 return QualType(sugaredType, 0);
2643 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2644 ArrayType::ArraySizeModifier ASM,
2645 unsigned elementTypeQuals) const {
2646 llvm::FoldingSetNodeID ID;
2647 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2649 void *insertPos = nullptr;
2650 if (IncompleteArrayType *iat =
2651 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2652 return QualType(iat, 0);
2654 // If the element type isn't canonical, this won't be a canonical type
2655 // either, so fill in the canonical type field. We also have to pull
2656 // qualifiers off the element type.
2659 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2660 SplitQualType canonSplit = getCanonicalType(elementType).split();
2661 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2662 ASM, elementTypeQuals);
2663 canon = getQualifiedType(canon, canonSplit.Quals);
2665 // Get the new insert position for the node we care about.
2666 IncompleteArrayType *existing =
2667 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2668 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2671 IncompleteArrayType *newType = new (*this, TypeAlignment)
2672 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2674 IncompleteArrayTypes.InsertNode(newType, insertPos);
2675 Types.push_back(newType);
2676 return QualType(newType, 0);
2679 /// getVectorType - Return the unique reference to a vector type of
2680 /// the specified element type and size. VectorType must be a built-in type.
2681 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2682 VectorType::VectorKind VecKind) const {
2683 assert(vecType->isBuiltinType());
2685 // Check if we've already instantiated a vector of this type.
2686 llvm::FoldingSetNodeID ID;
2687 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2689 void *InsertPos = nullptr;
2690 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2691 return QualType(VTP, 0);
2693 // If the element type isn't canonical, this won't be a canonical type either,
2694 // so fill in the canonical type field.
2696 if (!vecType.isCanonical()) {
2697 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2699 // Get the new insert position for the node we care about.
2700 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2701 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2703 VectorType *New = new (*this, TypeAlignment)
2704 VectorType(vecType, NumElts, Canonical, VecKind);
2705 VectorTypes.InsertNode(New, InsertPos);
2706 Types.push_back(New);
2707 return QualType(New, 0);
2710 /// getExtVectorType - Return the unique reference to an extended vector type of
2711 /// the specified element type and size. VectorType must be a built-in type.
2713 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2714 assert(vecType->isBuiltinType() || vecType->isDependentType());
2716 // Check if we've already instantiated a vector of this type.
2717 llvm::FoldingSetNodeID ID;
2718 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2719 VectorType::GenericVector);
2720 void *InsertPos = nullptr;
2721 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2722 return QualType(VTP, 0);
2724 // If the element type isn't canonical, this won't be a canonical type either,
2725 // so fill in the canonical type field.
2727 if (!vecType.isCanonical()) {
2728 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2730 // Get the new insert position for the node we care about.
2731 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2732 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2734 ExtVectorType *New = new (*this, TypeAlignment)
2735 ExtVectorType(vecType, NumElts, Canonical);
2736 VectorTypes.InsertNode(New, InsertPos);
2737 Types.push_back(New);
2738 return QualType(New, 0);
2742 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2744 SourceLocation AttrLoc) const {
2745 llvm::FoldingSetNodeID ID;
2746 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2749 void *InsertPos = nullptr;
2750 DependentSizedExtVectorType *Canon
2751 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2752 DependentSizedExtVectorType *New;
2754 // We already have a canonical version of this array type; use it as
2755 // the canonical type for a newly-built type.
2756 New = new (*this, TypeAlignment)
2757 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2760 QualType CanonVecTy = getCanonicalType(vecType);
2761 if (CanonVecTy == vecType) {
2762 New = new (*this, TypeAlignment)
2763 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2766 DependentSizedExtVectorType *CanonCheck
2767 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2768 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2770 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2772 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2774 New = new (*this, TypeAlignment)
2775 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2779 Types.push_back(New);
2780 return QualType(New, 0);
2783 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2786 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2787 const FunctionType::ExtInfo &Info) const {
2788 const CallingConv CallConv = Info.getCC();
2790 // Unique functions, to guarantee there is only one function of a particular
2792 llvm::FoldingSetNodeID ID;
2793 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2795 void *InsertPos = nullptr;
2796 if (FunctionNoProtoType *FT =
2797 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2798 return QualType(FT, 0);
2801 if (!ResultTy.isCanonical()) {
2802 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2804 // Get the new insert position for the node we care about.
2805 FunctionNoProtoType *NewIP =
2806 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2807 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2810 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2811 FunctionNoProtoType *New = new (*this, TypeAlignment)
2812 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2813 Types.push_back(New);
2814 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2815 return QualType(New, 0);
2818 /// \brief Determine whether \p T is canonical as the result type of a function.
2819 static bool isCanonicalResultType(QualType T) {
2820 return T.isCanonical() &&
2821 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2822 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2826 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2827 const FunctionProtoType::ExtProtoInfo &EPI) const {
2828 size_t NumArgs = ArgArray.size();
2830 // Unique functions, to guarantee there is only one function of a particular
2832 llvm::FoldingSetNodeID ID;
2833 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2836 void *InsertPos = nullptr;
2837 if (FunctionProtoType *FTP =
2838 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(FTP, 0);
2841 // Determine whether the type being created is already canonical or not.
2843 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2844 !EPI.HasTrailingReturn;
2845 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2846 if (!ArgArray[i].isCanonicalAsParam())
2847 isCanonical = false;
2849 // If this type isn't canonical, get the canonical version of it.
2850 // The exception spec is not part of the canonical type.
2853 SmallVector<QualType, 16> CanonicalArgs;
2854 CanonicalArgs.reserve(NumArgs);
2855 for (unsigned i = 0; i != NumArgs; ++i)
2856 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2858 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2859 CanonicalEPI.HasTrailingReturn = false;
2860 CanonicalEPI.ExceptionSpecType = EST_None;
2861 CanonicalEPI.NumExceptions = 0;
2863 // Result types do not have ARC lifetime qualifiers.
2864 QualType CanResultTy = getCanonicalType(ResultTy);
2865 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2866 Qualifiers Qs = CanResultTy.getQualifiers();
2867 Qs.removeObjCLifetime();
2868 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2871 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2873 // Get the new insert position for the node we care about.
2874 FunctionProtoType *NewIP =
2875 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2876 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2879 // FunctionProtoType objects are allocated with extra bytes after
2880 // them for three variable size arrays at the end:
2881 // - parameter types
2882 // - exception types
2883 // - consumed-arguments flags
2884 // Instead of the exception types, there could be a noexcept
2885 // expression, or information used to resolve the exception
2887 size_t Size = sizeof(FunctionProtoType) +
2888 NumArgs * sizeof(QualType);
2889 if (EPI.ExceptionSpecType == EST_Dynamic) {
2890 Size += EPI.NumExceptions * sizeof(QualType);
2891 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2892 Size += sizeof(Expr*);
2893 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2894 Size += 2 * sizeof(FunctionDecl*);
2895 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2896 Size += sizeof(FunctionDecl*);
2898 if (EPI.ConsumedParameters)
2899 Size += NumArgs * sizeof(bool);
2901 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2902 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2903 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2904 Types.push_back(FTP);
2905 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2906 return QualType(FTP, 0);
2910 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2911 if (!isa<CXXRecordDecl>(D)) return false;
2912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2913 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2915 if (RD->getDescribedClassTemplate() &&
2916 !isa<ClassTemplateSpecializationDecl>(RD))
2922 /// getInjectedClassNameType - Return the unique reference to the
2923 /// injected class name type for the specified templated declaration.
2924 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2925 QualType TST) const {
2926 assert(NeedsInjectedClassNameType(Decl));
2927 if (Decl->TypeForDecl) {
2928 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2929 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2930 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2931 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2932 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2935 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2936 Decl->TypeForDecl = newType;
2937 Types.push_back(newType);
2939 return QualType(Decl->TypeForDecl, 0);
2942 /// getTypeDeclType - Return the unique reference to the type for the
2943 /// specified type declaration.
2944 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2945 assert(Decl && "Passed null for Decl param");
2946 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2948 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2949 return getTypedefType(Typedef);
2951 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2952 "Template type parameter types are always available.");
2954 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2955 assert(Record->isFirstDecl() && "struct/union has previous declaration");
2956 assert(!NeedsInjectedClassNameType(Record));
2957 return getRecordType(Record);
2958 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2959 assert(Enum->isFirstDecl() && "enum has previous declaration");
2960 return getEnumType(Enum);
2961 } else if (const UnresolvedUsingTypenameDecl *Using =
2962 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2963 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2964 Decl->TypeForDecl = newType;
2965 Types.push_back(newType);
2967 llvm_unreachable("TypeDecl without a type?");
2969 return QualType(Decl->TypeForDecl, 0);
2972 /// getTypedefType - Return the unique reference to the type for the
2973 /// specified typedef name decl.
2975 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2976 QualType Canonical) const {
2977 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2979 if (Canonical.isNull())
2980 Canonical = getCanonicalType(Decl->getUnderlyingType());
2981 TypedefType *newType = new(*this, TypeAlignment)
2982 TypedefType(Type::Typedef, Decl, Canonical);
2983 Decl->TypeForDecl = newType;
2984 Types.push_back(newType);
2985 return QualType(newType, 0);
2988 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2989 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2991 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2992 if (PrevDecl->TypeForDecl)
2993 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2995 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2996 Decl->TypeForDecl = newType;
2997 Types.push_back(newType);
2998 return QualType(newType, 0);
3001 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3002 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3004 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3005 if (PrevDecl->TypeForDecl)
3006 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3008 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3009 Decl->TypeForDecl = newType;
3010 Types.push_back(newType);
3011 return QualType(newType, 0);
3014 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3015 QualType modifiedType,
3016 QualType equivalentType) {
3017 llvm::FoldingSetNodeID id;
3018 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3020 void *insertPos = nullptr;
3021 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3022 if (type) return QualType(type, 0);
3024 QualType canon = getCanonicalType(equivalentType);
3025 type = new (*this, TypeAlignment)
3026 AttributedType(canon, attrKind, modifiedType, equivalentType);
3028 Types.push_back(type);
3029 AttributedTypes.InsertNode(type, insertPos);
3031 return QualType(type, 0);
3035 /// \brief Retrieve a substitution-result type.
3037 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3038 QualType Replacement) const {
3039 assert(Replacement.isCanonical()
3040 && "replacement types must always be canonical");
3042 llvm::FoldingSetNodeID ID;
3043 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3044 void *InsertPos = nullptr;
3045 SubstTemplateTypeParmType *SubstParm
3046 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3049 SubstParm = new (*this, TypeAlignment)
3050 SubstTemplateTypeParmType(Parm, Replacement);
3051 Types.push_back(SubstParm);
3052 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3055 return QualType(SubstParm, 0);
3058 /// \brief Retrieve a
3059 QualType ASTContext::getSubstTemplateTypeParmPackType(
3060 const TemplateTypeParmType *Parm,
3061 const TemplateArgument &ArgPack) {
3063 for (const auto &P : ArgPack.pack_elements()) {
3064 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3065 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3069 llvm::FoldingSetNodeID ID;
3070 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3071 void *InsertPos = nullptr;
3072 if (SubstTemplateTypeParmPackType *SubstParm
3073 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3074 return QualType(SubstParm, 0);
3077 if (!Parm->isCanonicalUnqualified()) {
3078 Canon = getCanonicalType(QualType(Parm, 0));
3079 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3081 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3084 SubstTemplateTypeParmPackType *SubstParm
3085 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3087 Types.push_back(SubstParm);
3088 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3089 return QualType(SubstParm, 0);
3092 /// \brief Retrieve the template type parameter type for a template
3093 /// parameter or parameter pack with the given depth, index, and (optionally)
3095 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3097 TemplateTypeParmDecl *TTPDecl) const {
3098 llvm::FoldingSetNodeID ID;
3099 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3100 void *InsertPos = nullptr;
3101 TemplateTypeParmType *TypeParm
3102 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3105 return QualType(TypeParm, 0);
3108 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3109 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3111 TemplateTypeParmType *TypeCheck
3112 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3113 assert(!TypeCheck && "Template type parameter canonical type broken");
3116 TypeParm = new (*this, TypeAlignment)
3117 TemplateTypeParmType(Depth, Index, ParameterPack);
3119 Types.push_back(TypeParm);
3120 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3122 return QualType(TypeParm, 0);
3126 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3127 SourceLocation NameLoc,
3128 const TemplateArgumentListInfo &Args,
3129 QualType Underlying) const {
3130 assert(!Name.getAsDependentTemplateName() &&
3131 "No dependent template names here!");
3132 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3134 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3135 TemplateSpecializationTypeLoc TL =
3136 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3137 TL.setTemplateKeywordLoc(SourceLocation());
3138 TL.setTemplateNameLoc(NameLoc);
3139 TL.setLAngleLoc(Args.getLAngleLoc());
3140 TL.setRAngleLoc(Args.getRAngleLoc());
3141 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3142 TL.setArgLocInfo(i, Args[i].getLocInfo());
3147 ASTContext::getTemplateSpecializationType(TemplateName Template,
3148 const TemplateArgumentListInfo &Args,
3149 QualType Underlying) const {
3150 assert(!Template.getAsDependentTemplateName() &&
3151 "No dependent template names here!");
3153 unsigned NumArgs = Args.size();
3155 SmallVector<TemplateArgument, 4> ArgVec;
3156 ArgVec.reserve(NumArgs);
3157 for (unsigned i = 0; i != NumArgs; ++i)
3158 ArgVec.push_back(Args[i].getArgument());
3160 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3165 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3167 for (unsigned I = 0; I != NumArgs; ++I)
3168 if (Args[I].isPackExpansion())
3176 ASTContext::getTemplateSpecializationType(TemplateName Template,
3177 const TemplateArgument *Args,
3179 QualType Underlying) const {
3180 assert(!Template.getAsDependentTemplateName() &&
3181 "No dependent template names here!");
3182 // Look through qualified template names.
3183 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3184 Template = TemplateName(QTN->getTemplateDecl());
3187 Template.getAsTemplateDecl() &&
3188 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3190 if (!Underlying.isNull())
3191 CanonType = getCanonicalType(Underlying);
3193 // We can get here with an alias template when the specialization contains
3194 // a pack expansion that does not match up with a parameter pack.
3195 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3196 "Caller must compute aliased type");
3197 IsTypeAlias = false;
3198 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3202 // Allocate the (non-canonical) template specialization type, but don't
3203 // try to unique it: these types typically have location information that
3204 // we don't unique and don't want to lose.
3205 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3206 sizeof(TemplateArgument) * NumArgs +
3207 (IsTypeAlias? sizeof(QualType) : 0),
3209 TemplateSpecializationType *Spec
3210 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3211 IsTypeAlias ? Underlying : QualType());
3213 Types.push_back(Spec);
3214 return QualType(Spec, 0);
3218 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3219 const TemplateArgument *Args,
3220 unsigned NumArgs) const {
3221 assert(!Template.getAsDependentTemplateName() &&
3222 "No dependent template names here!");
3224 // Look through qualified template names.
3225 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3226 Template = TemplateName(QTN->getTemplateDecl());
3228 // Build the canonical template specialization type.
3229 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3230 SmallVector<TemplateArgument, 4> CanonArgs;
3231 CanonArgs.reserve(NumArgs);
3232 for (unsigned I = 0; I != NumArgs; ++I)
3233 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3235 // Determine whether this canonical template specialization type already
3237 llvm::FoldingSetNodeID ID;
3238 TemplateSpecializationType::Profile(ID, CanonTemplate,
3239 CanonArgs.data(), NumArgs, *this);
3241 void *InsertPos = nullptr;
3242 TemplateSpecializationType *Spec
3243 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3246 // Allocate a new canonical template specialization type.
3247 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3248 sizeof(TemplateArgument) * NumArgs),
3250 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3251 CanonArgs.data(), NumArgs,
3252 QualType(), QualType());
3253 Types.push_back(Spec);
3254 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3257 assert(Spec->isDependentType() &&
3258 "Non-dependent template-id type must have a canonical type");
3259 return QualType(Spec, 0);
3263 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3264 NestedNameSpecifier *NNS,
3265 QualType NamedType) const {
3266 llvm::FoldingSetNodeID ID;
3267 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3269 void *InsertPos = nullptr;
3270 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3272 return QualType(T, 0);
3274 QualType Canon = NamedType;
3275 if (!Canon.isCanonical()) {
3276 Canon = getCanonicalType(NamedType);
3277 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3278 assert(!CheckT && "Elaborated canonical type broken");
3282 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3284 ElaboratedTypes.InsertNode(T, InsertPos);
3285 return QualType(T, 0);
3289 ASTContext::getParenType(QualType InnerType) const {
3290 llvm::FoldingSetNodeID ID;
3291 ParenType::Profile(ID, InnerType);
3293 void *InsertPos = nullptr;
3294 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3296 return QualType(T, 0);
3298 QualType Canon = InnerType;
3299 if (!Canon.isCanonical()) {
3300 Canon = getCanonicalType(InnerType);
3301 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3302 assert(!CheckT && "Paren canonical type broken");
3306 T = new (*this) ParenType(InnerType, Canon);
3308 ParenTypes.InsertNode(T, InsertPos);
3309 return QualType(T, 0);
3312 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3313 NestedNameSpecifier *NNS,
3314 const IdentifierInfo *Name,
3315 QualType Canon) const {
3316 if (Canon.isNull()) {
3317 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3318 ElaboratedTypeKeyword CanonKeyword = Keyword;
3319 if (Keyword == ETK_None)
3320 CanonKeyword = ETK_Typename;
3322 if (CanonNNS != NNS || CanonKeyword != Keyword)
3323 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3326 llvm::FoldingSetNodeID ID;
3327 DependentNameType::Profile(ID, Keyword, NNS, Name);
3329 void *InsertPos = nullptr;
3330 DependentNameType *T
3331 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3333 return QualType(T, 0);
3335 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3337 DependentNameTypes.InsertNode(T, InsertPos);
3338 return QualType(T, 0);
3342 ASTContext::getDependentTemplateSpecializationType(
3343 ElaboratedTypeKeyword Keyword,
3344 NestedNameSpecifier *NNS,
3345 const IdentifierInfo *Name,
3346 const TemplateArgumentListInfo &Args) const {
3347 // TODO: avoid this copy
3348 SmallVector<TemplateArgument, 16> ArgCopy;
3349 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3350 ArgCopy.push_back(Args[I].getArgument());
3351 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3357 ASTContext::getDependentTemplateSpecializationType(
3358 ElaboratedTypeKeyword Keyword,
3359 NestedNameSpecifier *NNS,
3360 const IdentifierInfo *Name,
3362 const TemplateArgument *Args) const {
3363 assert((!NNS || NNS->isDependent()) &&
3364 "nested-name-specifier must be dependent");
3366 llvm::FoldingSetNodeID ID;
3367 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3368 Name, NumArgs, Args);
3370 void *InsertPos = nullptr;
3371 DependentTemplateSpecializationType *T
3372 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 return QualType(T, 0);
3376 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3378 ElaboratedTypeKeyword CanonKeyword = Keyword;
3379 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3381 bool AnyNonCanonArgs = false;
3382 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3383 for (unsigned I = 0; I != NumArgs; ++I) {
3384 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3385 if (!CanonArgs[I].structurallyEquals(Args[I]))
3386 AnyNonCanonArgs = true;
3390 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3391 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3395 // Find the insert position again.
3396 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3399 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3400 sizeof(TemplateArgument) * NumArgs),
3402 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3403 Name, NumArgs, Args, Canon);
3405 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3406 return QualType(T, 0);
3409 QualType ASTContext::getPackExpansionType(QualType Pattern,
3410 Optional<unsigned> NumExpansions) {
3411 llvm::FoldingSetNodeID ID;
3412 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3414 assert(Pattern->containsUnexpandedParameterPack() &&
3415 "Pack expansions must expand one or more parameter packs");
3416 void *InsertPos = nullptr;
3417 PackExpansionType *T
3418 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3420 return QualType(T, 0);
3423 if (!Pattern.isCanonical()) {
3424 Canon = getCanonicalType(Pattern);
3425 // The canonical type might not contain an unexpanded parameter pack, if it
3426 // contains an alias template specialization which ignores one of its
3428 if (Canon->containsUnexpandedParameterPack()) {
3429 Canon = getPackExpansionType(Canon, NumExpansions);
3431 // Find the insert position again, in case we inserted an element into
3432 // PackExpansionTypes and invalidated our insert position.
3433 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3437 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3439 PackExpansionTypes.InsertNode(T, InsertPos);
3440 return QualType(T, 0);
3443 /// CmpProtocolNames - Comparison predicate for sorting protocols
3445 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3446 const ObjCProtocolDecl *RHS) {
3447 return LHS->getDeclName() < RHS->getDeclName();
3450 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3451 unsigned NumProtocols) {
3452 if (NumProtocols == 0) return true;
3454 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3457 for (unsigned i = 1; i != NumProtocols; ++i)
3458 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3459 Protocols[i]->getCanonicalDecl() != Protocols[i])
3464 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3465 unsigned &NumProtocols) {
3466 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3468 // Sort protocols, keyed by name.
3469 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3472 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3473 Protocols[I] = Protocols[I]->getCanonicalDecl();
3475 // Remove duplicates.
3476 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3477 NumProtocols = ProtocolsEnd-Protocols;
3480 QualType ASTContext::getObjCObjectType(QualType BaseType,
3481 ObjCProtocolDecl * const *Protocols,
3482 unsigned NumProtocols) const {
3483 // If the base type is an interface and there aren't any protocols
3484 // to add, then the interface type will do just fine.
3485 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3488 // Look in the folding set for an existing type.
3489 llvm::FoldingSetNodeID ID;
3490 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3491 void *InsertPos = nullptr;
3492 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3493 return QualType(QT, 0);
3495 // Build the canonical type, which has the canonical base type and
3496 // a sorted-and-uniqued list of protocols.
3498 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3499 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3500 if (!ProtocolsSorted) {
3501 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3502 Protocols + NumProtocols);
3503 unsigned UniqueCount = NumProtocols;
3505 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3506 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3507 &Sorted[0], UniqueCount);
3509 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3510 Protocols, NumProtocols);
3513 // Regenerate InsertPos.
3514 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3517 unsigned Size = sizeof(ObjCObjectTypeImpl);
3518 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3519 void *Mem = Allocate(Size, TypeAlignment);
3520 ObjCObjectTypeImpl *T =
3521 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3524 ObjCObjectTypes.InsertNode(T, InsertPos);
3525 return QualType(T, 0);
3528 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3529 /// protocol list adopt all protocols in QT's qualified-id protocol
3531 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3532 ObjCInterfaceDecl *IC) {
3533 if (!QT->isObjCQualifiedIdType())
3536 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3537 // If both the right and left sides have qualifiers.
3538 for (auto *Proto : OPT->quals()) {
3539 if (!IC->ClassImplementsProtocol(Proto, false))
3547 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3548 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3550 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3551 ObjCInterfaceDecl *IDecl) {
3552 if (!QT->isObjCQualifiedIdType())
3554 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3557 if (!IDecl->hasDefinition())
3559 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3560 CollectInheritedProtocols(IDecl, InheritedProtocols);
3561 if (InheritedProtocols.empty())
3563 // Check that if every protocol in list of id<plist> conforms to a protcol
3564 // of IDecl's, then bridge casting is ok.
3565 bool Conforms = false;
3566 for (auto *Proto : OPT->quals()) {
3568 for (auto *PI : InheritedProtocols) {
3569 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3580 for (auto *PI : InheritedProtocols) {
3581 // If both the right and left sides have qualifiers.
3582 bool Adopts = false;
3583 for (auto *Proto : OPT->quals()) {
3584 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3585 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3594 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3595 /// the given object type.
3596 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3597 llvm::FoldingSetNodeID ID;
3598 ObjCObjectPointerType::Profile(ID, ObjectT);
3600 void *InsertPos = nullptr;
3601 if (ObjCObjectPointerType *QT =
3602 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3603 return QualType(QT, 0);
3605 // Find the canonical object type.
3607 if (!ObjectT.isCanonical()) {
3608 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3610 // Regenerate InsertPos.
3611 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3615 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3616 ObjCObjectPointerType *QType =
3617 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3619 Types.push_back(QType);
3620 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3621 return QualType(QType, 0);
3624 /// getObjCInterfaceType - Return the unique reference to the type for the
3625 /// specified ObjC interface decl. The list of protocols is optional.
3626 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3627 ObjCInterfaceDecl *PrevDecl) const {
3628 if (Decl->TypeForDecl)
3629 return QualType(Decl->TypeForDecl, 0);
3632 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3633 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3634 return QualType(PrevDecl->TypeForDecl, 0);
3637 // Prefer the definition, if there is one.
3638 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3641 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3642 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3643 Decl->TypeForDecl = T;
3645 return QualType(T, 0);
3648 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3649 /// TypeOfExprType AST's (since expression's are never shared). For example,
3650 /// multiple declarations that refer to "typeof(x)" all contain different
3651 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3652 /// on canonical type's (which are always unique).
3653 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3654 TypeOfExprType *toe;
3655 if (tofExpr->isTypeDependent()) {
3656 llvm::FoldingSetNodeID ID;
3657 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3659 void *InsertPos = nullptr;
3660 DependentTypeOfExprType *Canon
3661 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3663 // We already have a "canonical" version of an identical, dependent
3664 // typeof(expr) type. Use that as our canonical type.
3665 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3666 QualType((TypeOfExprType*)Canon, 0));
3668 // Build a new, canonical typeof(expr) type.
3670 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3671 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3675 QualType Canonical = getCanonicalType(tofExpr->getType());
3676 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3678 Types.push_back(toe);
3679 return QualType(toe, 0);
3682 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3683 /// TypeOfType nodes. The only motivation to unique these nodes would be
3684 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3685 /// an issue. This doesn't affect the type checker, since it operates
3686 /// on canonical types (which are always unique).
3687 QualType ASTContext::getTypeOfType(QualType tofType) const {
3688 QualType Canonical = getCanonicalType(tofType);
3689 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3690 Types.push_back(tot);
3691 return QualType(tot, 0);
3695 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3696 /// nodes. This would never be helpful, since each such type has its own
3697 /// expression, and would not give a significant memory saving, since there
3698 /// is an Expr tree under each such type.
3699 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3702 // C++11 [temp.type]p2:
3703 // If an expression e involves a template parameter, decltype(e) denotes a
3704 // unique dependent type. Two such decltype-specifiers refer to the same
3705 // type only if their expressions are equivalent (14.5.6.1).
3706 if (e->isInstantiationDependent()) {
3707 llvm::FoldingSetNodeID ID;
3708 DependentDecltypeType::Profile(ID, *this, e);
3710 void *InsertPos = nullptr;
3711 DependentDecltypeType *Canon
3712 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3714 // Build a new, canonical typeof(expr) type.
3715 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3716 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3718 dt = new (*this, TypeAlignment)
3719 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3721 dt = new (*this, TypeAlignment)
3722 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3724 Types.push_back(dt);
3725 return QualType(dt, 0);
3728 /// getUnaryTransformationType - We don't unique these, since the memory
3729 /// savings are minimal and these are rare.
3730 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3731 QualType UnderlyingType,
3732 UnaryTransformType::UTTKind Kind)
3734 UnaryTransformType *Ty =
3735 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3737 UnderlyingType->isDependentType() ?
3738 QualType() : getCanonicalType(UnderlyingType));
3739 Types.push_back(Ty);
3740 return QualType(Ty, 0);
3743 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3744 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3745 /// canonical deduced-but-dependent 'auto' type.
3746 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3747 bool IsDependent) const {
3748 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3749 return getAutoDeductType();
3751 // Look in the folding set for an existing type.
3752 void *InsertPos = nullptr;
3753 llvm::FoldingSetNodeID ID;
3754 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3755 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3756 return QualType(AT, 0);
3758 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3761 Types.push_back(AT);
3763 AutoTypes.InsertNode(AT, InsertPos);
3764 return QualType(AT, 0);
3767 /// getAtomicType - Return the uniqued reference to the atomic type for
3768 /// the given value type.
3769 QualType ASTContext::getAtomicType(QualType T) const {
3770 // Unique pointers, to guarantee there is only one pointer of a particular
3772 llvm::FoldingSetNodeID ID;
3773 AtomicType::Profile(ID, T);
3775 void *InsertPos = nullptr;
3776 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3777 return QualType(AT, 0);
3779 // If the atomic value type isn't canonical, this won't be a canonical type
3780 // either, so fill in the canonical type field.
3782 if (!T.isCanonical()) {
3783 Canonical = getAtomicType(getCanonicalType(T));
3785 // Get the new insert position for the node we care about.
3786 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3789 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3790 Types.push_back(New);
3791 AtomicTypes.InsertNode(New, InsertPos);
3792 return QualType(New, 0);
3795 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3796 QualType ASTContext::getAutoDeductType() const {
3797 if (AutoDeductTy.isNull())
3798 AutoDeductTy = QualType(
3799 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3800 /*dependent*/false),
3802 return AutoDeductTy;
3805 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3806 QualType ASTContext::getAutoRRefDeductType() const {
3807 if (AutoRRefDeductTy.isNull())
3808 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3809 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3810 return AutoRRefDeductTy;
3813 /// getTagDeclType - Return the unique reference to the type for the
3814 /// specified TagDecl (struct/union/class/enum) decl.
3815 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3817 // FIXME: What is the design on getTagDeclType when it requires casting
3818 // away const? mutable?
3819 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3822 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3823 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3824 /// needs to agree with the definition in <stddef.h>.
3825 CanQualType ASTContext::getSizeType() const {
3826 return getFromTargetType(Target->getSizeType());
3829 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3830 CanQualType ASTContext::getIntMaxType() const {
3831 return getFromTargetType(Target->getIntMaxType());
3834 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3835 CanQualType ASTContext::getUIntMaxType() const {
3836 return getFromTargetType(Target->getUIntMaxType());
3839 /// getSignedWCharType - Return the type of "signed wchar_t".
3840 /// Used when in C++, as a GCC extension.
3841 QualType ASTContext::getSignedWCharType() const {
3842 // FIXME: derive from "Target" ?
3846 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3847 /// Used when in C++, as a GCC extension.
3848 QualType ASTContext::getUnsignedWCharType() const {
3849 // FIXME: derive from "Target" ?
3850 return UnsignedIntTy;
3853 QualType ASTContext::getIntPtrType() const {
3854 return getFromTargetType(Target->getIntPtrType());
3857 QualType ASTContext::getUIntPtrType() const {
3858 return getCorrespondingUnsignedType(getIntPtrType());
3861 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3862 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3863 QualType ASTContext::getPointerDiffType() const {
3864 return getFromTargetType(Target->getPtrDiffType(0));
3867 /// \brief Return the unique type for "pid_t" defined in
3868 /// <sys/types.h>. We need this to compute the correct type for vfork().
3869 QualType ASTContext::getProcessIDType() const {
3870 return getFromTargetType(Target->getProcessIDType());
3873 //===----------------------------------------------------------------------===//
3875 //===----------------------------------------------------------------------===//
3877 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3878 // Push qualifiers into arrays, and then discard any remaining
3880 T = getCanonicalType(T);
3881 T = getVariableArrayDecayedType(T);
3882 const Type *Ty = T.getTypePtr();
3884 if (isa<ArrayType>(Ty)) {
3885 Result = getArrayDecayedType(QualType(Ty,0));
3886 } else if (isa<FunctionType>(Ty)) {
3887 Result = getPointerType(QualType(Ty, 0));
3889 Result = QualType(Ty, 0);
3892 return CanQualType::CreateUnsafe(Result);
3895 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3896 Qualifiers &quals) {
3897 SplitQualType splitType = type.getSplitUnqualifiedType();
3899 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3900 // the unqualified desugared type and then drops it on the floor.
3901 // We then have to strip that sugar back off with
3902 // getUnqualifiedDesugaredType(), which is silly.
3903 const ArrayType *AT =
3904 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3906 // If we don't have an array, just use the results in splitType.
3908 quals = splitType.Quals;
3909 return QualType(splitType.Ty, 0);
3912 // Otherwise, recurse on the array's element type.
3913 QualType elementType = AT->getElementType();
3914 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3916 // If that didn't change the element type, AT has no qualifiers, so we
3917 // can just use the results in splitType.
3918 if (elementType == unqualElementType) {
3919 assert(quals.empty()); // from the recursive call
3920 quals = splitType.Quals;
3921 return QualType(splitType.Ty, 0);
3924 // Otherwise, add in the qualifiers from the outermost type, then
3925 // build the type back up.
3926 quals.addConsistentQualifiers(splitType.Quals);
3928 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3929 return getConstantArrayType(unqualElementType, CAT->getSize(),
3930 CAT->getSizeModifier(), 0);
3933 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3934 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3937 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3938 return getVariableArrayType(unqualElementType,
3940 VAT->getSizeModifier(),
3941 VAT->getIndexTypeCVRQualifiers(),
3942 VAT->getBracketsRange());
3945 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3946 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3947 DSAT->getSizeModifier(), 0,
3951 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3952 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3953 /// they point to and return true. If T1 and T2 aren't pointer types
3954 /// or pointer-to-member types, or if they are not similar at this
3955 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3956 /// qualifiers on T1 and T2 are ignored. This function will typically
3957 /// be called in a loop that successively "unwraps" pointer and
3958 /// pointer-to-member types to compare them at each level.
3959 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3960 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3961 *T2PtrType = T2->getAs<PointerType>();
3962 if (T1PtrType && T2PtrType) {
3963 T1 = T1PtrType->getPointeeType();
3964 T2 = T2PtrType->getPointeeType();
3968 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3969 *T2MPType = T2->getAs<MemberPointerType>();
3970 if (T1MPType && T2MPType &&
3971 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3972 QualType(T2MPType->getClass(), 0))) {
3973 T1 = T1MPType->getPointeeType();
3974 T2 = T2MPType->getPointeeType();
3978 if (getLangOpts().ObjC1) {
3979 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3980 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3981 if (T1OPType && T2OPType) {
3982 T1 = T1OPType->getPointeeType();
3983 T2 = T2OPType->getPointeeType();
3988 // FIXME: Block pointers, too?
3994 ASTContext::getNameForTemplate(TemplateName Name,
3995 SourceLocation NameLoc) const {
3996 switch (Name.getKind()) {
3997 case TemplateName::QualifiedTemplate:
3998 case TemplateName::Template:
3999 // DNInfo work in progress: CHECKME: what about DNLoc?
4000 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4003 case TemplateName::OverloadedTemplate: {
4004 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4005 // DNInfo work in progress: CHECKME: what about DNLoc?
4006 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4009 case TemplateName::DependentTemplate: {
4010 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4011 DeclarationName DName;
4012 if (DTN->isIdentifier()) {
4013 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4014 return DeclarationNameInfo(DName, NameLoc);
4016 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4017 // DNInfo work in progress: FIXME: source locations?
4018 DeclarationNameLoc DNLoc;
4019 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4020 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4021 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4025 case TemplateName::SubstTemplateTemplateParm: {
4026 SubstTemplateTemplateParmStorage *subst
4027 = Name.getAsSubstTemplateTemplateParm();
4028 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4032 case TemplateName::SubstTemplateTemplateParmPack: {
4033 SubstTemplateTemplateParmPackStorage *subst
4034 = Name.getAsSubstTemplateTemplateParmPack();
4035 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4040 llvm_unreachable("bad template name kind!");
4043 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4044 switch (Name.getKind()) {
4045 case TemplateName::QualifiedTemplate:
4046 case TemplateName::Template: {
4047 TemplateDecl *Template = Name.getAsTemplateDecl();
4048 if (TemplateTemplateParmDecl *TTP
4049 = dyn_cast<TemplateTemplateParmDecl>(Template))
4050 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4052 // The canonical template name is the canonical template declaration.
4053 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4056 case TemplateName::OverloadedTemplate:
4057 llvm_unreachable("cannot canonicalize overloaded template");
4059 case TemplateName::DependentTemplate: {
4060 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4061 assert(DTN && "Non-dependent template names must refer to template decls.");
4062 return DTN->CanonicalTemplateName;
4065 case TemplateName::SubstTemplateTemplateParm: {
4066 SubstTemplateTemplateParmStorage *subst
4067 = Name.getAsSubstTemplateTemplateParm();
4068 return getCanonicalTemplateName(subst->getReplacement());
4071 case TemplateName::SubstTemplateTemplateParmPack: {
4072 SubstTemplateTemplateParmPackStorage *subst
4073 = Name.getAsSubstTemplateTemplateParmPack();
4074 TemplateTemplateParmDecl *canonParameter
4075 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4076 TemplateArgument canonArgPack
4077 = getCanonicalTemplateArgument(subst->getArgumentPack());
4078 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4082 llvm_unreachable("bad template name!");
4085 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4086 X = getCanonicalTemplateName(X);
4087 Y = getCanonicalTemplateName(Y);
4088 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4092 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4093 switch (Arg.getKind()) {
4094 case TemplateArgument::Null:
4097 case TemplateArgument::Expression:
4100 case TemplateArgument::Declaration: {
4101 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4102 return TemplateArgument(D, Arg.isDeclForReferenceParam());
4105 case TemplateArgument::NullPtr:
4106 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4109 case TemplateArgument::Template:
4110 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4112 case TemplateArgument::TemplateExpansion:
4113 return TemplateArgument(getCanonicalTemplateName(
4114 Arg.getAsTemplateOrTemplatePattern()),
4115 Arg.getNumTemplateExpansions());
4117 case TemplateArgument::Integral:
4118 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4120 case TemplateArgument::Type:
4121 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4123 case TemplateArgument::Pack: {
4124 if (Arg.pack_size() == 0)
4127 TemplateArgument *CanonArgs
4128 = new (*this) TemplateArgument[Arg.pack_size()];
4130 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4131 AEnd = Arg.pack_end();
4132 A != AEnd; (void)++A, ++Idx)
4133 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4135 return TemplateArgument(CanonArgs, Arg.pack_size());
4139 // Silence GCC warning
4140 llvm_unreachable("Unhandled template argument kind");
4143 NestedNameSpecifier *
4144 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4148 switch (NNS->getKind()) {
4149 case NestedNameSpecifier::Identifier:
4150 // Canonicalize the prefix but keep the identifier the same.
4151 return NestedNameSpecifier::Create(*this,
4152 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4153 NNS->getAsIdentifier());
4155 case NestedNameSpecifier::Namespace:
4156 // A namespace is canonical; build a nested-name-specifier with
4157 // this namespace and no prefix.
4158 return NestedNameSpecifier::Create(*this, nullptr,
4159 NNS->getAsNamespace()->getOriginalNamespace());
4161 case NestedNameSpecifier::NamespaceAlias:
4162 // A namespace is canonical; build a nested-name-specifier with
4163 // this namespace and no prefix.
4164 return NestedNameSpecifier::Create(*this, nullptr,
4165 NNS->getAsNamespaceAlias()->getNamespace()
4166 ->getOriginalNamespace());
4168 case NestedNameSpecifier::TypeSpec:
4169 case NestedNameSpecifier::TypeSpecWithTemplate: {
4170 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4172 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4173 // break it apart into its prefix and identifier, then reconsititute those
4174 // as the canonical nested-name-specifier. This is required to canonicalize
4175 // a dependent nested-name-specifier involving typedefs of dependent-name
4177 // typedef typename T::type T1;
4178 // typedef typename T1::type T2;
4179 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4180 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4181 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4183 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4184 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4186 return NestedNameSpecifier::Create(*this, nullptr, false,
4187 const_cast<Type *>(T.getTypePtr()));
4190 case NestedNameSpecifier::Global:
4191 // The global specifier is canonical and unique.
4195 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4199 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4200 // Handle the non-qualified case efficiently.
4201 if (!T.hasLocalQualifiers()) {
4202 // Handle the common positive case fast.
4203 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4207 // Handle the common negative case fast.
4208 if (!isa<ArrayType>(T.getCanonicalType()))
4211 // Apply any qualifiers from the array type to the element type. This
4212 // implements C99 6.7.3p8: "If the specification of an array type includes
4213 // any type qualifiers, the element type is so qualified, not the array type."
4215 // If we get here, we either have type qualifiers on the type, or we have
4216 // sugar such as a typedef in the way. If we have type qualifiers on the type
4217 // we must propagate them down into the element type.
4219 SplitQualType split = T.getSplitDesugaredType();
4220 Qualifiers qs = split.Quals;
4222 // If we have a simple case, just return now.
4223 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4224 if (!ATy || qs.empty())
4227 // Otherwise, we have an array and we have qualifiers on it. Push the
4228 // qualifiers into the array element type and return a new array type.
4229 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4231 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4232 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4233 CAT->getSizeModifier(),
4234 CAT->getIndexTypeCVRQualifiers()));
4235 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4236 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4237 IAT->getSizeModifier(),
4238 IAT->getIndexTypeCVRQualifiers()));
4240 if (const DependentSizedArrayType *DSAT
4241 = dyn_cast<DependentSizedArrayType>(ATy))
4242 return cast<ArrayType>(
4243 getDependentSizedArrayType(NewEltTy,
4244 DSAT->getSizeExpr(),
4245 DSAT->getSizeModifier(),
4246 DSAT->getIndexTypeCVRQualifiers(),
4247 DSAT->getBracketsRange()));
4249 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4250 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4252 VAT->getSizeModifier(),
4253 VAT->getIndexTypeCVRQualifiers(),
4254 VAT->getBracketsRange()));
4257 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4258 if (T->isArrayType() || T->isFunctionType())
4259 return getDecayedType(T);
4263 QualType ASTContext::getSignatureParameterType(QualType T) const {
4264 T = getVariableArrayDecayedType(T);
4265 T = getAdjustedParameterType(T);
4266 return T.getUnqualifiedType();
4269 /// getArrayDecayedType - Return the properly qualified result of decaying the
4270 /// specified array type to a pointer. This operation is non-trivial when
4271 /// handling typedefs etc. The canonical type of "T" must be an array type,
4272 /// this returns a pointer to a properly qualified element of the array.
4274 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4275 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4276 // Get the element type with 'getAsArrayType' so that we don't lose any
4277 // typedefs in the element type of the array. This also handles propagation
4278 // of type qualifiers from the array type into the element type if present
4280 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4281 assert(PrettyArrayType && "Not an array type!");
4283 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4285 // int x[restrict 4] -> int *restrict
4286 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4289 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4290 return getBaseElementType(array->getElementType());
4293 QualType ASTContext::getBaseElementType(QualType type) const {
4296 SplitQualType split = type.getSplitDesugaredType();
4297 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4300 type = array->getElementType();
4301 qs.addConsistentQualifiers(split.Quals);
4304 return getQualifiedType(type, qs);
4307 /// getConstantArrayElementCount - Returns number of constant array elements.
4309 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4310 uint64_t ElementCount = 1;
4312 ElementCount *= CA->getSize().getZExtValue();
4313 CA = dyn_cast_or_null<ConstantArrayType>(
4314 CA->getElementType()->getAsArrayTypeUnsafe());
4316 return ElementCount;
4319 /// getFloatingRank - Return a relative rank for floating point types.
4320 /// This routine will assert if passed a built-in type that isn't a float.
4321 static FloatingRank getFloatingRank(QualType T) {
4322 if (const ComplexType *CT = T->getAs<ComplexType>())
4323 return getFloatingRank(CT->getElementType());
4325 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4326 switch (T->getAs<BuiltinType>()->getKind()) {
4327 default: llvm_unreachable("getFloatingRank(): not a floating type");
4328 case BuiltinType::Half: return HalfRank;
4329 case BuiltinType::Float: return FloatRank;
4330 case BuiltinType::Double: return DoubleRank;
4331 case BuiltinType::LongDouble: return LongDoubleRank;
4335 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4336 /// point or a complex type (based on typeDomain/typeSize).
4337 /// 'typeDomain' is a real floating point or complex type.
4338 /// 'typeSize' is a real floating point or complex type.
4339 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4340 QualType Domain) const {
4341 FloatingRank EltRank = getFloatingRank(Size);
4342 if (Domain->isComplexType()) {
4344 case HalfRank: llvm_unreachable("Complex half is not supported");
4345 case FloatRank: return FloatComplexTy;
4346 case DoubleRank: return DoubleComplexTy;
4347 case LongDoubleRank: return LongDoubleComplexTy;
4351 assert(Domain->isRealFloatingType() && "Unknown domain!");
4353 case HalfRank: return HalfTy;
4354 case FloatRank: return FloatTy;
4355 case DoubleRank: return DoubleTy;
4356 case LongDoubleRank: return LongDoubleTy;
4358 llvm_unreachable("getFloatingRank(): illegal value for rank");
4361 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4362 /// point types, ignoring the domain of the type (i.e. 'double' ==
4363 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4364 /// LHS < RHS, return -1.
4365 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4366 FloatingRank LHSR = getFloatingRank(LHS);
4367 FloatingRank RHSR = getFloatingRank(RHS);
4376 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4377 /// routine will assert if passed a built-in type that isn't an integer or enum,
4378 /// or if it is not canonicalized.
4379 unsigned ASTContext::getIntegerRank(const Type *T) const {
4380 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4382 switch (cast<BuiltinType>(T)->getKind()) {
4383 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4384 case BuiltinType::Bool:
4385 return 1 + (getIntWidth(BoolTy) << 3);
4386 case BuiltinType::Char_S:
4387 case BuiltinType::Char_U:
4388 case BuiltinType::SChar:
4389 case BuiltinType::UChar:
4390 return 2 + (getIntWidth(CharTy) << 3);
4391 case BuiltinType::Short:
4392 case BuiltinType::UShort:
4393 return 3 + (getIntWidth(ShortTy) << 3);
4394 case BuiltinType::Int:
4395 case BuiltinType::UInt:
4396 return 4 + (getIntWidth(IntTy) << 3);
4397 case BuiltinType::Long:
4398 case BuiltinType::ULong:
4399 return 5 + (getIntWidth(LongTy) << 3);
4400 case BuiltinType::LongLong:
4401 case BuiltinType::ULongLong:
4402 return 6 + (getIntWidth(LongLongTy) << 3);
4403 case BuiltinType::Int128:
4404 case BuiltinType::UInt128:
4405 return 7 + (getIntWidth(Int128Ty) << 3);
4409 /// \brief Whether this is a promotable bitfield reference according
4410 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4412 /// \returns the type this bit-field will promote to, or NULL if no
4413 /// promotion occurs.
4414 QualType ASTContext::isPromotableBitField(Expr *E) const {
4415 if (E->isTypeDependent() || E->isValueDependent())
4418 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4422 QualType FT = Field->getType();
4424 uint64_t BitWidth = Field->getBitWidthValue(*this);
4425 uint64_t IntSize = getTypeSize(IntTy);
4426 // GCC extension compatibility: if the bit-field size is less than or equal
4427 // to the size of int, it gets promoted no matter what its type is.
4428 // For instance, unsigned long bf : 4 gets promoted to signed int.
4429 if (BitWidth < IntSize)
4432 if (BitWidth == IntSize)
4433 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4435 // Types bigger than int are not subject to promotions, and therefore act
4436 // like the base type.
4437 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4442 /// getPromotedIntegerType - Returns the type that Promotable will
4443 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4445 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4446 assert(!Promotable.isNull());
4447 assert(Promotable->isPromotableIntegerType());
4448 if (const EnumType *ET = Promotable->getAs<EnumType>())
4449 return ET->getDecl()->getPromotionType();
4451 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4452 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4453 // (3.9.1) can be converted to a prvalue of the first of the following
4454 // types that can represent all the values of its underlying type:
4455 // int, unsigned int, long int, unsigned long int, long long int, or
4456 // unsigned long long int [...]
4457 // FIXME: Is there some better way to compute this?
4458 if (BT->getKind() == BuiltinType::WChar_S ||
4459 BT->getKind() == BuiltinType::WChar_U ||
4460 BT->getKind() == BuiltinType::Char16 ||
4461 BT->getKind() == BuiltinType::Char32) {
4462 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4463 uint64_t FromSize = getTypeSize(BT);
4464 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4465 LongLongTy, UnsignedLongLongTy };
4466 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4467 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4468 if (FromSize < ToSize ||
4469 (FromSize == ToSize &&
4470 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4471 return PromoteTypes[Idx];
4473 llvm_unreachable("char type should fit into long long");
4477 // At this point, we should have a signed or unsigned integer type.
4478 if (Promotable->isSignedIntegerType())
4480 uint64_t PromotableSize = getIntWidth(Promotable);
4481 uint64_t IntSize = getIntWidth(IntTy);
4482 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4483 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4486 /// \brief Recurses in pointer/array types until it finds an objc retainable
4487 /// type and returns its ownership.
4488 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4489 while (!T.isNull()) {
4490 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4491 return T.getObjCLifetime();
4492 if (T->isArrayType())
4493 T = getBaseElementType(T);
4494 else if (const PointerType *PT = T->getAs<PointerType>())
4495 T = PT->getPointeeType();
4496 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4497 T = RT->getPointeeType();
4502 return Qualifiers::OCL_None;
4505 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4506 // Incomplete enum types are not treated as integer types.
4507 // FIXME: In C++, enum types are never integer types.
4508 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4509 return ET->getDecl()->getIntegerType().getTypePtr();
4513 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4514 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4515 /// LHS < RHS, return -1.
4516 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4517 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4518 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4520 // Unwrap enums to their underlying type.
4521 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4522 LHSC = getIntegerTypeForEnum(ET);
4523 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4524 RHSC = getIntegerTypeForEnum(ET);
4526 if (LHSC == RHSC) return 0;
4528 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4529 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4531 unsigned LHSRank = getIntegerRank(LHSC);
4532 unsigned RHSRank = getIntegerRank(RHSC);
4534 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4535 if (LHSRank == RHSRank) return 0;
4536 return LHSRank > RHSRank ? 1 : -1;
4539 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4541 // If the unsigned [LHS] type is larger, return it.
4542 if (LHSRank >= RHSRank)
4545 // If the signed type can represent all values of the unsigned type, it
4546 // wins. Because we are dealing with 2's complement and types that are
4547 // powers of two larger than each other, this is always safe.
4551 // If the unsigned [RHS] type is larger, return it.
4552 if (RHSRank >= LHSRank)
4555 // If the signed type can represent all values of the unsigned type, it
4556 // wins. Because we are dealing with 2's complement and types that are
4557 // powers of two larger than each other, this is always safe.
4561 // getCFConstantStringType - Return the type used for constant CFStrings.
4562 QualType ASTContext::getCFConstantStringType() const {
4563 if (!CFConstantStringTypeDecl) {
4564 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4565 CFConstantStringTypeDecl->startDefinition();
4567 QualType FieldTypes[4];
4570 FieldTypes[0] = getPointerType(IntTy.withConst());
4572 FieldTypes[1] = IntTy;
4574 FieldTypes[2] = getPointerType(CharTy.withConst());
4576 FieldTypes[3] = LongTy;
4579 for (unsigned i = 0; i < 4; ++i) {
4580 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4582 SourceLocation(), nullptr,
4583 FieldTypes[i], /*TInfo=*/nullptr,
4584 /*BitWidth=*/nullptr,
4587 Field->setAccess(AS_public);
4588 CFConstantStringTypeDecl->addDecl(Field);
4591 CFConstantStringTypeDecl->completeDefinition();
4594 return getTagDeclType(CFConstantStringTypeDecl);
4597 QualType ASTContext::getObjCSuperType() const {
4598 if (ObjCSuperType.isNull()) {
4599 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4600 TUDecl->addDecl(ObjCSuperTypeDecl);
4601 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4603 return ObjCSuperType;
4606 void ASTContext::setCFConstantStringType(QualType T) {
4607 const RecordType *Rec = T->getAs<RecordType>();
4608 assert(Rec && "Invalid CFConstantStringType");
4609 CFConstantStringTypeDecl = Rec->getDecl();
4612 QualType ASTContext::getBlockDescriptorType() const {
4613 if (BlockDescriptorType)
4614 return getTagDeclType(BlockDescriptorType);
4617 // FIXME: Needs the FlagAppleBlock bit.
4618 RD = buildImplicitRecord("__block_descriptor");
4619 RD->startDefinition();
4621 QualType FieldTypes[] = {
4626 static const char *const FieldNames[] = {
4631 for (size_t i = 0; i < 2; ++i) {
4632 FieldDecl *Field = FieldDecl::Create(
4633 *this, RD, SourceLocation(), SourceLocation(),
4634 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4635 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4636 Field->setAccess(AS_public);
4640 RD->completeDefinition();
4642 BlockDescriptorType = RD;
4644 return getTagDeclType(BlockDescriptorType);
4647 QualType ASTContext::getBlockDescriptorExtendedType() const {
4648 if (BlockDescriptorExtendedType)
4649 return getTagDeclType(BlockDescriptorExtendedType);
4652 // FIXME: Needs the FlagAppleBlock bit.
4653 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4654 RD->startDefinition();
4656 QualType FieldTypes[] = {
4659 getPointerType(VoidPtrTy),
4660 getPointerType(VoidPtrTy)
4663 static const char *const FieldNames[] = {
4670 for (size_t i = 0; i < 4; ++i) {
4671 FieldDecl *Field = FieldDecl::Create(
4672 *this, RD, SourceLocation(), SourceLocation(),
4673 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4674 /*BitWidth=*/nullptr,
4675 /*Mutable=*/false, ICIS_NoInit);
4676 Field->setAccess(AS_public);
4680 RD->completeDefinition();
4682 BlockDescriptorExtendedType = RD;
4683 return getTagDeclType(BlockDescriptorExtendedType);
4686 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4687 /// requires copy/dispose. Note that this must match the logic
4688 /// in buildByrefHelpers.
4689 bool ASTContext::BlockRequiresCopying(QualType Ty,
4691 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4692 const Expr *copyExpr = getBlockVarCopyInits(D);
4693 if (!copyExpr && record->hasTrivialDestructor()) return false;
4698 if (!Ty->isObjCRetainableType()) return false;
4700 Qualifiers qs = Ty.getQualifiers();
4702 // If we have lifetime, that dominates.
4703 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4704 assert(getLangOpts().ObjCAutoRefCount);
4707 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4709 // These are just bits as far as the runtime is concerned.
4710 case Qualifiers::OCL_ExplicitNone:
4711 case Qualifiers::OCL_Autoreleasing:
4714 // Tell the runtime that this is ARC __weak, called by the
4716 case Qualifiers::OCL_Weak:
4717 // ARC __strong __block variables need to be retained.
4718 case Qualifiers::OCL_Strong:
4721 llvm_unreachable("fell out of lifetime switch!");
4723 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4724 Ty->isObjCObjectPointerType());
4727 bool ASTContext::getByrefLifetime(QualType Ty,
4728 Qualifiers::ObjCLifetime &LifeTime,
4729 bool &HasByrefExtendedLayout) const {
4731 if (!getLangOpts().ObjC1 ||
4732 getLangOpts().getGC() != LangOptions::NonGC)
4735 HasByrefExtendedLayout = false;
4736 if (Ty->isRecordType()) {
4737 HasByrefExtendedLayout = true;
4738 LifeTime = Qualifiers::OCL_None;
4740 else if (getLangOpts().ObjCAutoRefCount)
4741 LifeTime = Ty.getObjCLifetime();
4743 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4744 LifeTime = Qualifiers::OCL_ExplicitNone;
4746 LifeTime = Qualifiers::OCL_None;
4750 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4751 if (!ObjCInstanceTypeDecl)
4752 ObjCInstanceTypeDecl =
4753 buildImplicitTypedef(getObjCIdType(), "instancetype");
4754 return ObjCInstanceTypeDecl;
4757 // This returns true if a type has been typedefed to BOOL:
4758 // typedef <type> BOOL;
4759 static bool isTypeTypedefedAsBOOL(QualType T) {
4760 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4761 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4762 return II->isStr("BOOL");
4767 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4769 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4770 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4771 return CharUnits::Zero();
4773 CharUnits sz = getTypeSizeInChars(type);
4775 // Make all integer and enum types at least as large as an int
4776 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4777 sz = std::max(sz, getTypeSizeInChars(IntTy));
4778 // Treat arrays as pointers, since that's how they're passed in.
4779 else if (type->isArrayType())
4780 sz = getTypeSizeInChars(VoidPtrTy);
4784 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4785 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4786 VD->getType()->isIntegralOrEnumerationType() &&
4787 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4791 std::string charUnitsToString(const CharUnits &CU) {
4792 return llvm::itostr(CU.getQuantity());
4795 /// getObjCEncodingForBlock - Return the encoded type for this block
4797 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4800 const BlockDecl *Decl = Expr->getBlockDecl();
4802 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4803 // Encode result type.
4804 if (getLangOpts().EncodeExtendedBlockSig)
4805 getObjCEncodingForMethodParameter(
4806 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4809 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
4810 // Compute size of all parameters.
4811 // Start with computing size of a pointer in number of bytes.
4812 // FIXME: There might(should) be a better way of doing this computation!
4814 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4815 CharUnits ParmOffset = PtrSize;
4816 for (auto PI : Decl->params()) {
4817 QualType PType = PI->getType();
4818 CharUnits sz = getObjCEncodingTypeSize(PType);
4821 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4824 // Size of the argument frame
4825 S += charUnitsToString(ParmOffset);
4826 // Block pointer and offset.
4830 ParmOffset = PtrSize;
4831 for (auto PVDecl : Decl->params()) {
4832 QualType PType = PVDecl->getOriginalType();
4833 if (const ArrayType *AT =
4834 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4835 // Use array's original type only if it has known number of
4837 if (!isa<ConstantArrayType>(AT))
4838 PType = PVDecl->getType();
4839 } else if (PType->isFunctionType())
4840 PType = PVDecl->getType();
4841 if (getLangOpts().EncodeExtendedBlockSig)
4842 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4843 S, true /*Extended*/);
4845 getObjCEncodingForType(PType, S);
4846 S += charUnitsToString(ParmOffset);
4847 ParmOffset += getObjCEncodingTypeSize(PType);
4853 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4855 // Encode result type.
4856 getObjCEncodingForType(Decl->getReturnType(), S);
4857 CharUnits ParmOffset;
4858 // Compute size of all parameters.
4859 for (auto PI : Decl->params()) {
4860 QualType PType = PI->getType();
4861 CharUnits sz = getObjCEncodingTypeSize(PType);
4865 assert (sz.isPositive() &&
4866 "getObjCEncodingForFunctionDecl - Incomplete param type");
4869 S += charUnitsToString(ParmOffset);
4870 ParmOffset = CharUnits::Zero();
4873 for (auto PVDecl : Decl->params()) {
4874 QualType PType = PVDecl->getOriginalType();
4875 if (const ArrayType *AT =
4876 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4877 // Use array's original type only if it has known number of
4879 if (!isa<ConstantArrayType>(AT))
4880 PType = PVDecl->getType();
4881 } else if (PType->isFunctionType())
4882 PType = PVDecl->getType();
4883 getObjCEncodingForType(PType, S);
4884 S += charUnitsToString(ParmOffset);
4885 ParmOffset += getObjCEncodingTypeSize(PType);
4891 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4892 /// method parameter or return type. If Extended, include class names and
4893 /// block object types.
4894 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4895 QualType T, std::string& S,
4896 bool Extended) const {
4897 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4898 getObjCEncodingForTypeQualifier(QT, S);
4899 // Encode parameter type.
4900 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
4901 true /*OutermostType*/,
4902 false /*EncodingProperty*/,
4903 false /*StructField*/,
4904 Extended /*EncodeBlockParameters*/,
4905 Extended /*EncodeClassNames*/);
4908 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4910 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4912 bool Extended) const {
4913 // FIXME: This is not very efficient.
4914 // Encode return type.
4915 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4916 Decl->getReturnType(), S, Extended);
4917 // Compute size of all parameters.
4918 // Start with computing size of a pointer in number of bytes.
4919 // FIXME: There might(should) be a better way of doing this computation!
4921 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4922 // The first two arguments (self and _cmd) are pointers; account for
4924 CharUnits ParmOffset = 2 * PtrSize;
4925 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4926 E = Decl->sel_param_end(); PI != E; ++PI) {
4927 QualType PType = (*PI)->getType();
4928 CharUnits sz = getObjCEncodingTypeSize(PType);
4932 assert (sz.isPositive() &&
4933 "getObjCEncodingForMethodDecl - Incomplete param type");
4936 S += charUnitsToString(ParmOffset);
4938 S += charUnitsToString(PtrSize);
4941 ParmOffset = 2 * PtrSize;
4942 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4943 E = Decl->sel_param_end(); PI != E; ++PI) {
4944 const ParmVarDecl *PVDecl = *PI;
4945 QualType PType = PVDecl->getOriginalType();
4946 if (const ArrayType *AT =
4947 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4948 // Use array's original type only if it has known number of
4950 if (!isa<ConstantArrayType>(AT))
4951 PType = PVDecl->getType();
4952 } else if (PType->isFunctionType())
4953 PType = PVDecl->getType();
4954 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4955 PType, S, Extended);
4956 S += charUnitsToString(ParmOffset);
4957 ParmOffset += getObjCEncodingTypeSize(PType);
4963 ObjCPropertyImplDecl *
4964 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4965 const ObjCPropertyDecl *PD,
4966 const Decl *Container) const {
4969 if (const ObjCCategoryImplDecl *CID =
4970 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4971 for (auto *PID : CID->property_impls())
4972 if (PID->getPropertyDecl() == PD)
4975 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4976 for (auto *PID : OID->property_impls())
4977 if (PID->getPropertyDecl() == PD)
4983 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4984 /// property declaration. If non-NULL, Container must be either an
4985 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4986 /// NULL when getting encodings for protocol properties.
4987 /// Property attributes are stored as a comma-delimited C string. The simple
4988 /// attributes readonly and bycopy are encoded as single characters. The
4989 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4990 /// encoded as single characters, followed by an identifier. Property types
4991 /// are also encoded as a parametrized attribute. The characters used to encode
4992 /// these attributes are defined by the following enumeration:
4994 /// enum PropertyAttributes {
4995 /// kPropertyReadOnly = 'R', // property is read-only.
4996 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4997 /// kPropertyByref = '&', // property is a reference to the value last assigned
4998 /// kPropertyDynamic = 'D', // property is dynamic
4999 /// kPropertyGetter = 'G', // followed by getter selector name
5000 /// kPropertySetter = 'S', // followed by setter selector name
5001 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5002 /// kPropertyType = 'T' // followed by old-style type encoding.
5003 /// kPropertyWeak = 'W' // 'weak' property
5004 /// kPropertyStrong = 'P' // property GC'able
5005 /// kPropertyNonAtomic = 'N' // property non-atomic
5008 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5009 const Decl *Container,
5010 std::string& S) const {
5011 // Collect information from the property implementation decl(s).
5012 bool Dynamic = false;
5013 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5015 if (ObjCPropertyImplDecl *PropertyImpDecl =
5016 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5017 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5020 SynthesizePID = PropertyImpDecl;
5023 // FIXME: This is not very efficient.
5026 // Encode result type.
5027 // GCC has some special rules regarding encoding of properties which
5028 // closely resembles encoding of ivars.
5029 getObjCEncodingForPropertyType(PD->getType(), S);
5031 if (PD->isReadOnly()) {
5033 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5035 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5037 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5040 switch (PD->getSetterKind()) {
5041 case ObjCPropertyDecl::Assign: break;
5042 case ObjCPropertyDecl::Copy: S += ",C"; break;
5043 case ObjCPropertyDecl::Retain: S += ",&"; break;
5044 case ObjCPropertyDecl::Weak: S += ",W"; break;
5048 // It really isn't clear at all what this means, since properties
5049 // are "dynamic by default".
5053 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5056 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5058 S += PD->getGetterName().getAsString();
5061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5063 S += PD->getSetterName().getAsString();
5066 if (SynthesizePID) {
5067 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5069 S += OID->getNameAsString();
5072 // FIXME: OBJCGC: weak & strong
5075 /// getLegacyIntegralTypeEncoding -
5076 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5077 /// 'l' or 'L' , but not always. For typedefs, we need to use
5078 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5080 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5081 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5082 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5083 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5084 PointeeTy = UnsignedIntTy;
5086 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5092 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5093 const FieldDecl *Field) const {
5094 // We follow the behavior of gcc, expanding structures which are
5095 // directly pointed to, and expanding embedded structures. Note that
5096 // these rules are sufficient to prevent recursive encoding of the
5098 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5099 true /* outermost type */);
5102 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5103 std::string& S) const {
5104 // Encode result type.
5105 // GCC has some special rules regarding encoding of properties which
5106 // closely resembles encoding of ivars.
5107 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5108 true /* outermost type */,
5109 true /* encoding property */);
5112 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5113 BuiltinType::Kind kind) {
5115 case BuiltinType::Void: return 'v';
5116 case BuiltinType::Bool: return 'B';
5117 case BuiltinType::Char_U:
5118 case BuiltinType::UChar: return 'C';
5119 case BuiltinType::Char16:
5120 case BuiltinType::UShort: return 'S';
5121 case BuiltinType::Char32:
5122 case BuiltinType::UInt: return 'I';
5123 case BuiltinType::ULong:
5124 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5125 case BuiltinType::UInt128: return 'T';
5126 case BuiltinType::ULongLong: return 'Q';
5127 case BuiltinType::Char_S:
5128 case BuiltinType::SChar: return 'c';
5129 case BuiltinType::Short: return 's';
5130 case BuiltinType::WChar_S:
5131 case BuiltinType::WChar_U:
5132 case BuiltinType::Int: return 'i';
5133 case BuiltinType::Long:
5134 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5135 case BuiltinType::LongLong: return 'q';
5136 case BuiltinType::Int128: return 't';
5137 case BuiltinType::Float: return 'f';
5138 case BuiltinType::Double: return 'd';
5139 case BuiltinType::LongDouble: return 'D';
5140 case BuiltinType::NullPtr: return '*'; // like char*
5142 case BuiltinType::Half:
5143 // FIXME: potentially need @encodes for these!
5146 case BuiltinType::ObjCId:
5147 case BuiltinType::ObjCClass:
5148 case BuiltinType::ObjCSel:
5149 llvm_unreachable("@encoding ObjC primitive type");
5151 // OpenCL and placeholder types don't need @encodings.
5152 case BuiltinType::OCLImage1d:
5153 case BuiltinType::OCLImage1dArray:
5154 case BuiltinType::OCLImage1dBuffer:
5155 case BuiltinType::OCLImage2d:
5156 case BuiltinType::OCLImage2dArray:
5157 case BuiltinType::OCLImage3d:
5158 case BuiltinType::OCLEvent:
5159 case BuiltinType::OCLSampler:
5160 case BuiltinType::Dependent:
5161 #define BUILTIN_TYPE(KIND, ID)
5162 #define PLACEHOLDER_TYPE(KIND, ID) \
5163 case BuiltinType::KIND:
5164 #include "clang/AST/BuiltinTypes.def"
5165 llvm_unreachable("invalid builtin type for @encode");
5167 llvm_unreachable("invalid BuiltinType::Kind value");
5170 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5171 EnumDecl *Enum = ET->getDecl();
5173 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5174 if (!Enum->isFixed())
5177 // The encoding of a fixed enum type matches its fixed underlying type.
5178 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5179 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5182 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5183 QualType T, const FieldDecl *FD) {
5184 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5186 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5187 // The GNU runtime requires more information; bitfields are encoded as b,
5188 // then the offset (in bits) of the first element, then the type of the
5189 // bitfield, then the size in bits. For example, in this structure:
5196 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5197 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5198 // information is not especially sensible, but we're stuck with it for
5199 // compatibility with GCC, although providing it breaks anything that
5200 // actually uses runtime introspection and wants to work on both runtimes...
5201 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5202 const RecordDecl *RD = FD->getParent();
5203 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5204 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5205 if (const EnumType *ET = T->getAs<EnumType>())
5206 S += ObjCEncodingForEnumType(Ctx, ET);
5208 const BuiltinType *BT = T->castAs<BuiltinType>();
5209 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5212 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5215 // FIXME: Use SmallString for accumulating string.
5216 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5217 bool ExpandPointedToStructures,
5218 bool ExpandStructures,
5219 const FieldDecl *FD,
5221 bool EncodingProperty,
5223 bool EncodeBlockParameters,
5224 bool EncodeClassNames,
5225 bool EncodePointerToObjCTypedef) const {
5226 CanQualType CT = getCanonicalType(T);
5227 switch (CT->getTypeClass()) {
5230 if (FD && FD->isBitField())
5231 return EncodeBitField(this, S, T, FD);
5232 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5233 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5235 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5238 case Type::Complex: {
5239 const ComplexType *CT = T->castAs<ComplexType>();
5241 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr,
5246 case Type::Atomic: {
5247 const AtomicType *AT = T->castAs<AtomicType>();
5249 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr,
5254 // encoding for pointer or reference types.
5256 case Type::LValueReference:
5257 case Type::RValueReference: {
5259 if (isa<PointerType>(CT)) {
5260 const PointerType *PT = T->castAs<PointerType>();
5261 if (PT->isObjCSelType()) {
5265 PointeeTy = PT->getPointeeType();
5267 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5270 bool isReadOnly = false;
5271 // For historical/compatibility reasons, the read-only qualifier of the
5272 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5273 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5274 // Also, do not emit the 'r' for anything but the outermost type!
5275 if (isa<TypedefType>(T.getTypePtr())) {
5276 if (OutermostType && T.isConstQualified()) {
5280 } else if (OutermostType) {
5281 QualType P = PointeeTy;
5282 while (P->getAs<PointerType>())
5283 P = P->getAs<PointerType>()->getPointeeType();
5284 if (P.isConstQualified()) {
5290 // Another legacy compatibility encoding. Some ObjC qualifier and type
5291 // combinations need to be rearranged.
5292 // Rewrite "in const" from "nr" to "rn"
5293 if (StringRef(S).endswith("nr"))
5294 S.replace(S.end()-2, S.end(), "rn");
5297 if (PointeeTy->isCharType()) {
5298 // char pointer types should be encoded as '*' unless it is a
5299 // type that has been typedef'd to 'BOOL'.
5300 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5304 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5305 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5306 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5310 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5311 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5318 getLegacyIntegralTypeEncoding(PointeeTy);
5320 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5325 case Type::ConstantArray:
5326 case Type::IncompleteArray:
5327 case Type::VariableArray: {
5328 const ArrayType *AT = cast<ArrayType>(CT);
5330 if (isa<IncompleteArrayType>(AT) && !StructField) {
5331 // Incomplete arrays are encoded as a pointer to the array element.
5334 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5335 false, ExpandStructures, FD);
5339 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5340 S += llvm::utostr(CAT->getSize().getZExtValue());
5342 //Variable length arrays are encoded as a regular array with 0 elements.
5343 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5344 "Unknown array type!");
5348 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5349 false, ExpandStructures, FD);
5355 case Type::FunctionNoProto:
5356 case Type::FunctionProto:
5360 case Type::Record: {
5361 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5362 S += RDecl->isUnion() ? '(' : '{';
5363 // Anonymous structures print as '?'
5364 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5366 if (ClassTemplateSpecializationDecl *Spec
5367 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5368 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5369 llvm::raw_string_ostream OS(S);
5370 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5371 TemplateArgs.data(),
5372 TemplateArgs.size(),
5373 (*this).getPrintingPolicy());
5378 if (ExpandStructures) {
5380 if (!RDecl->isUnion()) {
5381 getObjCEncodingForStructureImpl(RDecl, S, FD);
5383 for (const auto *Field : RDecl->fields()) {
5386 S += Field->getNameAsString();
5390 // Special case bit-fields.
5391 if (Field->isBitField()) {
5392 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5395 QualType qt = Field->getType();
5396 getLegacyIntegralTypeEncoding(qt);
5397 getObjCEncodingForTypeImpl(qt, S, false, true,
5398 FD, /*OutermostType*/false,
5399 /*EncodingProperty*/false,
5400 /*StructField*/true);
5405 S += RDecl->isUnion() ? ')' : '}';
5409 case Type::BlockPointer: {
5410 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5411 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5412 if (EncodeBlockParameters) {
5413 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5416 // Block return type
5417 getObjCEncodingForTypeImpl(
5418 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5419 FD, false /* OutermostType */, EncodingProperty,
5420 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
5424 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5425 for (const auto &I : FPT->param_types())
5426 getObjCEncodingForTypeImpl(
5427 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5428 false /* OutermostType */, EncodingProperty,
5429 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
5436 case Type::ObjCObject: {
5437 // hack to match legacy encoding of *id and *Class
5438 QualType Ty = getObjCObjectPointerType(CT);
5439 if (Ty->isObjCIdType()) {
5440 S += "{objc_object=}";
5443 else if (Ty->isObjCClassType()) {
5444 S += "{objc_class=}";
5449 case Type::ObjCInterface: {
5450 // Ignore protocol qualifiers when mangling at this level.
5451 T = T->castAs<ObjCObjectType>()->getBaseType();
5453 // The assumption seems to be that this assert will succeed
5454 // because nested levels will have filtered out 'id' and 'Class'.
5455 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5456 // @encode(class_name)
5457 ObjCInterfaceDecl *OI = OIT->getDecl();
5459 const IdentifierInfo *II = OI->getIdentifier();
5462 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5463 DeepCollectObjCIvars(OI, true, Ivars);
5464 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5465 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5466 if (Field->isBitField())
5467 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5469 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5470 false, false, false, false, false,
5471 EncodePointerToObjCTypedef);
5477 case Type::ObjCObjectPointer: {
5478 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5479 if (OPT->isObjCIdType()) {
5484 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5485 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5486 // Since this is a binary compatibility issue, need to consult with runtime
5487 // folks. Fortunately, this is a *very* obsure construct.
5492 if (OPT->isObjCQualifiedIdType()) {
5493 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5494 ExpandPointedToStructures,
5495 ExpandStructures, FD);
5496 if (FD || EncodingProperty || EncodeClassNames) {
5497 // Note that we do extended encoding of protocol qualifer list
5498 // Only when doing ivar or property encoding.
5500 for (const auto *I : OPT->quals()) {
5502 S += I->getNameAsString();
5510 QualType PointeeTy = OPT->getPointeeType();
5511 if (!EncodingProperty &&
5512 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5513 !EncodePointerToObjCTypedef) {
5514 // Another historical/compatibility reason.
5515 // We encode the underlying type which comes out as
5518 if (FD && OPT->getInterfaceDecl()) {
5519 // Prevent recursive encoding of fields in some rare cases.
5520 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5521 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5522 DeepCollectObjCIvars(OI, true, Ivars);
5523 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5524 if (cast<FieldDecl>(Ivars[i]) == FD) {
5526 S += OI->getIdentifier()->getName();
5532 getObjCEncodingForTypeImpl(PointeeTy, S,
5533 false, ExpandPointedToStructures,
5535 false, false, false, false, false,
5536 /*EncodePointerToObjCTypedef*/true);
5541 if (OPT->getInterfaceDecl() &&
5542 (FD || EncodingProperty || EncodeClassNames)) {
5544 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5545 for (const auto *I : OPT->quals()) {
5547 S += I->getNameAsString();
5555 // gcc just blithely ignores member pointers.
5556 // FIXME: we shoul do better than that. 'M' is available.
5557 case Type::MemberPointer:
5561 case Type::ExtVector:
5562 // This matches gcc's encoding, even though technically it is
5564 // FIXME. We should do a better job than gcc.
5568 // We could see an undeduced auto type here during error recovery.
5572 #define ABSTRACT_TYPE(KIND, BASE)
5573 #define TYPE(KIND, BASE)
5574 #define DEPENDENT_TYPE(KIND, BASE) \
5576 #define NON_CANONICAL_TYPE(KIND, BASE) \
5578 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5580 #include "clang/AST/TypeNodes.def"
5581 llvm_unreachable("@encode for dependent type!");
5583 llvm_unreachable("bad type kind!");
5586 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5588 const FieldDecl *FD,
5589 bool includeVBases) const {
5590 assert(RDecl && "Expected non-null RecordDecl");
5591 assert(!RDecl->isUnion() && "Should not be called for unions");
5592 if (!RDecl->getDefinition())
5595 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5596 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5597 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5600 for (const auto &BI : CXXRec->bases()) {
5601 if (!BI.isVirtual()) {
5602 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5603 if (base->isEmpty())
5605 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5606 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5607 std::make_pair(offs, base));
5613 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5614 FieldEnd = RDecl->field_end();
5615 Field != FieldEnd; ++Field, ++i) {
5616 uint64_t offs = layout.getFieldOffset(i);
5617 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5618 std::make_pair(offs, *Field));
5621 if (CXXRec && includeVBases) {
5622 for (const auto &BI : CXXRec->vbases()) {
5623 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5624 if (base->isEmpty())
5626 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5627 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5628 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5629 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5630 std::make_pair(offs, base));
5636 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5638 size = layout.getSize();
5642 uint64_t CurOffs = 0;
5644 std::multimap<uint64_t, NamedDecl *>::iterator
5645 CurLayObj = FieldOrBaseOffsets.begin();
5647 if (CXXRec && CXXRec->isDynamicClass() &&
5648 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5651 std::string recname = CXXRec->getNameAsString();
5652 if (recname.empty()) recname = "?";
5658 CurOffs += getTypeSize(VoidPtrTy);
5662 if (!RDecl->hasFlexibleArrayMember()) {
5663 // Mark the end of the structure.
5664 uint64_t offs = toBits(size);
5665 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5666 std::make_pair(offs, nullptr));
5669 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5671 assert(CurOffs <= CurLayObj->first);
5672 if (CurOffs < CurLayObj->first) {
5673 uint64_t padding = CurLayObj->first - CurOffs;
5674 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5675 // packing/alignment of members is different that normal, in which case
5676 // the encoding will be out-of-sync with the real layout.
5677 // If the runtime switches to just consider the size of types without
5678 // taking into account alignment, we could make padding explicit in the
5679 // encoding (e.g. using arrays of chars). The encoding strings would be
5680 // longer then though.
5685 NamedDecl *dcl = CurLayObj->second;
5687 break; // reached end of structure.
5689 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5690 // We expand the bases without their virtual bases since those are going
5691 // in the initial structure. Note that this differs from gcc which
5692 // expands virtual bases each time one is encountered in the hierarchy,
5693 // making the encoding type bigger than it really is.
5694 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5695 assert(!base->isEmpty());
5697 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5700 FieldDecl *field = cast<FieldDecl>(dcl);
5703 S += field->getNameAsString();
5707 if (field->isBitField()) {
5708 EncodeBitField(this, S, field->getType(), field);
5710 CurOffs += field->getBitWidthValue(*this);
5713 QualType qt = field->getType();
5714 getLegacyIntegralTypeEncoding(qt);
5715 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5716 /*OutermostType*/false,
5717 /*EncodingProperty*/false,
5718 /*StructField*/true);
5720 CurOffs += getTypeSize(field->getType());
5727 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5728 std::string& S) const {
5729 if (QT & Decl::OBJC_TQ_In)
5731 if (QT & Decl::OBJC_TQ_Inout)
5733 if (QT & Decl::OBJC_TQ_Out)
5735 if (QT & Decl::OBJC_TQ_Bycopy)
5737 if (QT & Decl::OBJC_TQ_Byref)
5739 if (QT & Decl::OBJC_TQ_Oneway)
5743 TypedefDecl *ASTContext::getObjCIdDecl() const {
5745 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
5746 T = getObjCObjectPointerType(T);
5747 ObjCIdDecl = buildImplicitTypedef(T, "id");
5752 TypedefDecl *ASTContext::getObjCSelDecl() const {
5754 QualType T = getPointerType(ObjCBuiltinSelTy);
5755 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5760 TypedefDecl *ASTContext::getObjCClassDecl() const {
5761 if (!ObjCClassDecl) {
5762 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
5763 T = getObjCObjectPointerType(T);
5764 ObjCClassDecl = buildImplicitTypedef(T, "Class");
5766 return ObjCClassDecl;
5769 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5770 if (!ObjCProtocolClassDecl) {
5771 ObjCProtocolClassDecl
5772 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5774 &Idents.get("Protocol"),
5775 /*PrevDecl=*/nullptr,
5776 SourceLocation(), true);
5779 return ObjCProtocolClassDecl;
5782 //===----------------------------------------------------------------------===//
5783 // __builtin_va_list Construction Functions
5784 //===----------------------------------------------------------------------===//
5786 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5787 // typedef char* __builtin_va_list;
5788 QualType T = Context->getPointerType(Context->CharTy);
5789 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5792 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5793 // typedef void* __builtin_va_list;
5794 QualType T = Context->getPointerType(Context->VoidTy);
5795 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5798 static TypedefDecl *
5799 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5801 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
5802 if (Context->getLangOpts().CPlusPlus) {
5803 // namespace std { struct __va_list {
5805 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5806 Context->getTranslationUnitDecl(),
5807 /*Inline*/ false, SourceLocation(),
5808 SourceLocation(), &Context->Idents.get("std"),
5809 /*PrevDecl*/ nullptr);
5811 VaListTagDecl->setDeclContext(NS);
5814 VaListTagDecl->startDefinition();
5816 const size_t NumFields = 5;
5817 QualType FieldTypes[NumFields];
5818 const char *FieldNames[NumFields];
5821 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5822 FieldNames[0] = "__stack";
5825 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5826 FieldNames[1] = "__gr_top";
5829 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5830 FieldNames[2] = "__vr_top";
5833 FieldTypes[3] = Context->IntTy;
5834 FieldNames[3] = "__gr_offs";
5837 FieldTypes[4] = Context->IntTy;
5838 FieldNames[4] = "__vr_offs";
5841 for (unsigned i = 0; i < NumFields; ++i) {
5842 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5846 &Context->Idents.get(FieldNames[i]),
5847 FieldTypes[i], /*TInfo=*/nullptr,
5848 /*BitWidth=*/nullptr,
5851 Field->setAccess(AS_public);
5852 VaListTagDecl->addDecl(Field);
5854 VaListTagDecl->completeDefinition();
5855 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5856 Context->VaListTagTy = VaListTagType;
5858 // } __builtin_va_list;
5859 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
5862 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5863 // typedef struct __va_list_tag {
5864 RecordDecl *VaListTagDecl;
5866 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5867 VaListTagDecl->startDefinition();
5869 const size_t NumFields = 5;
5870 QualType FieldTypes[NumFields];
5871 const char *FieldNames[NumFields];
5873 // unsigned char gpr;
5874 FieldTypes[0] = Context->UnsignedCharTy;
5875 FieldNames[0] = "gpr";
5877 // unsigned char fpr;
5878 FieldTypes[1] = Context->UnsignedCharTy;
5879 FieldNames[1] = "fpr";
5881 // unsigned short reserved;
5882 FieldTypes[2] = Context->UnsignedShortTy;
5883 FieldNames[2] = "reserved";
5885 // void* overflow_arg_area;
5886 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5887 FieldNames[3] = "overflow_arg_area";
5889 // void* reg_save_area;
5890 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5891 FieldNames[4] = "reg_save_area";
5894 for (unsigned i = 0; i < NumFields; ++i) {
5895 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5898 &Context->Idents.get(FieldNames[i]),
5899 FieldTypes[i], /*TInfo=*/nullptr,
5900 /*BitWidth=*/nullptr,
5903 Field->setAccess(AS_public);
5904 VaListTagDecl->addDecl(Field);
5906 VaListTagDecl->completeDefinition();
5907 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5908 Context->VaListTagTy = VaListTagType;
5911 TypedefDecl *VaListTagTypedefDecl =
5912 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5914 QualType VaListTagTypedefType =
5915 Context->getTypedefType(VaListTagTypedefDecl);
5917 // typedef __va_list_tag __builtin_va_list[1];
5918 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5919 QualType VaListTagArrayType
5920 = Context->getConstantArrayType(VaListTagTypedefType,
5921 Size, ArrayType::Normal, 0);
5922 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
5925 static TypedefDecl *
5926 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5927 // typedef struct __va_list_tag {
5928 RecordDecl *VaListTagDecl;
5929 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5930 VaListTagDecl->startDefinition();
5932 const size_t NumFields = 4;
5933 QualType FieldTypes[NumFields];
5934 const char *FieldNames[NumFields];
5936 // unsigned gp_offset;
5937 FieldTypes[0] = Context->UnsignedIntTy;
5938 FieldNames[0] = "gp_offset";
5940 // unsigned fp_offset;
5941 FieldTypes[1] = Context->UnsignedIntTy;
5942 FieldNames[1] = "fp_offset";
5944 // void* overflow_arg_area;
5945 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5946 FieldNames[2] = "overflow_arg_area";
5948 // void* reg_save_area;
5949 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5950 FieldNames[3] = "reg_save_area";
5953 for (unsigned i = 0; i < NumFields; ++i) {
5954 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5958 &Context->Idents.get(FieldNames[i]),
5959 FieldTypes[i], /*TInfo=*/nullptr,
5960 /*BitWidth=*/nullptr,
5963 Field->setAccess(AS_public);
5964 VaListTagDecl->addDecl(Field);
5966 VaListTagDecl->completeDefinition();
5967 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5968 Context->VaListTagTy = VaListTagType;
5971 TypedefDecl *VaListTagTypedefDecl =
5972 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5974 QualType VaListTagTypedefType =
5975 Context->getTypedefType(VaListTagTypedefDecl);
5977 // typedef __va_list_tag __builtin_va_list[1];
5978 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5979 QualType VaListTagArrayType
5980 = Context->getConstantArrayType(VaListTagTypedefType,
5981 Size, ArrayType::Normal,0);
5982 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
5985 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5986 // typedef int __builtin_va_list[4];
5987 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5988 QualType IntArrayType
5989 = Context->getConstantArrayType(Context->IntTy,
5990 Size, ArrayType::Normal, 0);
5991 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
5994 static TypedefDecl *
5995 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5997 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
5998 if (Context->getLangOpts().CPlusPlus) {
5999 // namespace std { struct __va_list {
6001 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6002 Context->getTranslationUnitDecl(),
6003 /*Inline*/false, SourceLocation(),
6004 SourceLocation(), &Context->Idents.get("std"),
6005 /*PrevDecl*/ nullptr);
6007 VaListDecl->setDeclContext(NS);
6010 VaListDecl->startDefinition();
6013 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6017 &Context->Idents.get("__ap"),
6018 Context->getPointerType(Context->VoidTy),
6020 /*BitWidth=*/nullptr,
6023 Field->setAccess(AS_public);
6024 VaListDecl->addDecl(Field);
6027 VaListDecl->completeDefinition();
6029 // typedef struct __va_list __builtin_va_list;
6030 QualType T = Context->getRecordType(VaListDecl);
6031 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6034 static TypedefDecl *
6035 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6036 // typedef struct __va_list_tag {
6037 RecordDecl *VaListTagDecl;
6038 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6039 VaListTagDecl->startDefinition();
6041 const size_t NumFields = 4;
6042 QualType FieldTypes[NumFields];
6043 const char *FieldNames[NumFields];
6046 FieldTypes[0] = Context->LongTy;
6047 FieldNames[0] = "__gpr";
6050 FieldTypes[1] = Context->LongTy;
6051 FieldNames[1] = "__fpr";
6053 // void *__overflow_arg_area;
6054 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6055 FieldNames[2] = "__overflow_arg_area";
6057 // void *__reg_save_area;
6058 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6059 FieldNames[3] = "__reg_save_area";
6062 for (unsigned i = 0; i < NumFields; ++i) {
6063 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6067 &Context->Idents.get(FieldNames[i]),
6068 FieldTypes[i], /*TInfo=*/nullptr,
6069 /*BitWidth=*/nullptr,
6072 Field->setAccess(AS_public);
6073 VaListTagDecl->addDecl(Field);
6075 VaListTagDecl->completeDefinition();
6076 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6077 Context->VaListTagTy = VaListTagType;
6080 TypedefDecl *VaListTagTypedefDecl =
6081 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6082 QualType VaListTagTypedefType =
6083 Context->getTypedefType(VaListTagTypedefDecl);
6085 // typedef __va_list_tag __builtin_va_list[1];
6086 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6087 QualType VaListTagArrayType
6088 = Context->getConstantArrayType(VaListTagTypedefType,
6089 Size, ArrayType::Normal,0);
6091 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6094 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6095 TargetInfo::BuiltinVaListKind Kind) {
6097 case TargetInfo::CharPtrBuiltinVaList:
6098 return CreateCharPtrBuiltinVaListDecl(Context);
6099 case TargetInfo::VoidPtrBuiltinVaList:
6100 return CreateVoidPtrBuiltinVaListDecl(Context);
6101 case TargetInfo::AArch64ABIBuiltinVaList:
6102 return CreateAArch64ABIBuiltinVaListDecl(Context);
6103 case TargetInfo::PowerABIBuiltinVaList:
6104 return CreatePowerABIBuiltinVaListDecl(Context);
6105 case TargetInfo::X86_64ABIBuiltinVaList:
6106 return CreateX86_64ABIBuiltinVaListDecl(Context);
6107 case TargetInfo::PNaClABIBuiltinVaList:
6108 return CreatePNaClABIBuiltinVaListDecl(Context);
6109 case TargetInfo::AAPCSABIBuiltinVaList:
6110 return CreateAAPCSABIBuiltinVaListDecl(Context);
6111 case TargetInfo::SystemZBuiltinVaList:
6112 return CreateSystemZBuiltinVaListDecl(Context);
6115 llvm_unreachable("Unhandled __builtin_va_list type kind");
6118 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6119 if (!BuiltinVaListDecl) {
6120 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6121 assert(BuiltinVaListDecl->isImplicit());
6124 return BuiltinVaListDecl;
6127 QualType ASTContext::getVaListTagType() const {
6128 // Force the creation of VaListTagTy by building the __builtin_va_list
6130 if (VaListTagTy.isNull())
6131 (void) getBuiltinVaListDecl();
6136 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6137 assert(ObjCConstantStringType.isNull() &&
6138 "'NSConstantString' type already set!");
6140 ObjCConstantStringType = getObjCInterfaceType(Decl);
6143 /// \brief Retrieve the template name that corresponds to a non-empty
6146 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6147 UnresolvedSetIterator End) const {
6148 unsigned size = End - Begin;
6149 assert(size > 1 && "set is not overloaded!");
6151 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6152 size * sizeof(FunctionTemplateDecl*));
6153 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6155 NamedDecl **Storage = OT->getStorage();
6156 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6158 assert(isa<FunctionTemplateDecl>(D) ||
6159 (isa<UsingShadowDecl>(D) &&
6160 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6164 return TemplateName(OT);
6167 /// \brief Retrieve the template name that represents a qualified
6168 /// template name such as \c std::vector.
6170 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6171 bool TemplateKeyword,
6172 TemplateDecl *Template) const {
6173 assert(NNS && "Missing nested-name-specifier in qualified template name");
6175 // FIXME: Canonicalization?
6176 llvm::FoldingSetNodeID ID;
6177 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6179 void *InsertPos = nullptr;
6180 QualifiedTemplateName *QTN =
6181 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6183 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6184 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6185 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6188 return TemplateName(QTN);
6191 /// \brief Retrieve the template name that represents a dependent
6192 /// template name such as \c MetaFun::template apply.
6194 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6195 const IdentifierInfo *Name) const {
6196 assert((!NNS || NNS->isDependent()) &&
6197 "Nested name specifier must be dependent");
6199 llvm::FoldingSetNodeID ID;
6200 DependentTemplateName::Profile(ID, NNS, Name);
6202 void *InsertPos = nullptr;
6203 DependentTemplateName *QTN =
6204 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6207 return TemplateName(QTN);
6209 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6210 if (CanonNNS == NNS) {
6211 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6212 DependentTemplateName(NNS, Name);
6214 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6215 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6216 DependentTemplateName(NNS, Name, Canon);
6217 DependentTemplateName *CheckQTN =
6218 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6219 assert(!CheckQTN && "Dependent type name canonicalization broken");
6223 DependentTemplateNames.InsertNode(QTN, InsertPos);
6224 return TemplateName(QTN);
6227 /// \brief Retrieve the template name that represents a dependent
6228 /// template name such as \c MetaFun::template operator+.
6230 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6231 OverloadedOperatorKind Operator) const {
6232 assert((!NNS || NNS->isDependent()) &&
6233 "Nested name specifier must be dependent");
6235 llvm::FoldingSetNodeID ID;
6236 DependentTemplateName::Profile(ID, NNS, Operator);
6238 void *InsertPos = nullptr;
6239 DependentTemplateName *QTN
6240 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6243 return TemplateName(QTN);
6245 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6246 if (CanonNNS == NNS) {
6247 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6248 DependentTemplateName(NNS, Operator);
6250 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6251 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6252 DependentTemplateName(NNS, Operator, Canon);
6254 DependentTemplateName *CheckQTN
6255 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6256 assert(!CheckQTN && "Dependent template name canonicalization broken");
6260 DependentTemplateNames.InsertNode(QTN, InsertPos);
6261 return TemplateName(QTN);
6265 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6266 TemplateName replacement) const {
6267 llvm::FoldingSetNodeID ID;
6268 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6270 void *insertPos = nullptr;
6271 SubstTemplateTemplateParmStorage *subst
6272 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6275 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6276 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6279 return TemplateName(subst);
6283 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6284 const TemplateArgument &ArgPack) const {
6285 ASTContext &Self = const_cast<ASTContext &>(*this);
6286 llvm::FoldingSetNodeID ID;
6287 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6289 void *InsertPos = nullptr;
6290 SubstTemplateTemplateParmPackStorage *Subst
6291 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6294 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6295 ArgPack.pack_size(),
6296 ArgPack.pack_begin());
6297 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6300 return TemplateName(Subst);
6303 /// getFromTargetType - Given one of the integer types provided by
6304 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6305 /// is actually a value of type @c TargetInfo::IntType.
6306 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6308 case TargetInfo::NoInt: return CanQualType();
6309 case TargetInfo::SignedChar: return SignedCharTy;
6310 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6311 case TargetInfo::SignedShort: return ShortTy;
6312 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6313 case TargetInfo::SignedInt: return IntTy;
6314 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6315 case TargetInfo::SignedLong: return LongTy;
6316 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6317 case TargetInfo::SignedLongLong: return LongLongTy;
6318 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6321 llvm_unreachable("Unhandled TargetInfo::IntType value");
6324 //===----------------------------------------------------------------------===//
6326 //===----------------------------------------------------------------------===//
6328 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6329 /// garbage collection attribute.
6331 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6332 if (getLangOpts().getGC() == LangOptions::NonGC)
6333 return Qualifiers::GCNone;
6335 assert(getLangOpts().ObjC1);
6336 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6338 // Default behaviour under objective-C's gc is for ObjC pointers
6339 // (or pointers to them) be treated as though they were declared
6341 if (GCAttrs == Qualifiers::GCNone) {
6342 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6343 return Qualifiers::Strong;
6344 else if (Ty->isPointerType())
6345 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6347 // It's not valid to set GC attributes on anything that isn't a
6350 QualType CT = Ty->getCanonicalTypeInternal();
6351 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6352 CT = AT->getElementType();
6353 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6359 //===----------------------------------------------------------------------===//
6360 // Type Compatibility Testing
6361 //===----------------------------------------------------------------------===//
6363 /// areCompatVectorTypes - Return true if the two specified vector types are
6365 static bool areCompatVectorTypes(const VectorType *LHS,
6366 const VectorType *RHS) {
6367 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6368 return LHS->getElementType() == RHS->getElementType() &&
6369 LHS->getNumElements() == RHS->getNumElements();
6372 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6373 QualType SecondVec) {
6374 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6375 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6377 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6380 // Treat Neon vector types and most AltiVec vector types as if they are the
6381 // equivalent GCC vector types.
6382 const VectorType *First = FirstVec->getAs<VectorType>();
6383 const VectorType *Second = SecondVec->getAs<VectorType>();
6384 if (First->getNumElements() == Second->getNumElements() &&
6385 hasSameType(First->getElementType(), Second->getElementType()) &&
6386 First->getVectorKind() != VectorType::AltiVecPixel &&
6387 First->getVectorKind() != VectorType::AltiVecBool &&
6388 Second->getVectorKind() != VectorType::AltiVecPixel &&
6389 Second->getVectorKind() != VectorType::AltiVecBool)
6395 //===----------------------------------------------------------------------===//
6396 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6397 //===----------------------------------------------------------------------===//
6399 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6400 /// inheritance hierarchy of 'rProto'.
6402 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6403 ObjCProtocolDecl *rProto) const {
6404 if (declaresSameEntity(lProto, rProto))
6406 for (auto *PI : rProto->protocols())
6407 if (ProtocolCompatibleWithProtocol(lProto, PI))
6412 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6413 /// Class<pr1, ...>.
6414 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6416 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6417 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6418 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6420 for (auto *lhsProto : lhsQID->quals()) {
6422 for (auto *rhsProto : rhsOPT->quals()) {
6423 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6434 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6435 /// ObjCQualifiedIDType.
6436 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6438 // Allow id<P..> and an 'id' or void* type in all cases.
6439 if (lhs->isVoidPointerType() ||
6440 lhs->isObjCIdType() || lhs->isObjCClassType())
6442 else if (rhs->isVoidPointerType() ||
6443 rhs->isObjCIdType() || rhs->isObjCClassType())
6446 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6447 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6449 if (!rhsOPT) return false;
6451 if (rhsOPT->qual_empty()) {
6452 // If the RHS is a unqualified interface pointer "NSString*",
6453 // make sure we check the class hierarchy.
6454 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6455 for (auto *I : lhsQID->quals()) {
6456 // when comparing an id<P> on lhs with a static type on rhs,
6457 // see if static class implements all of id's protocols, directly or
6458 // through its super class and categories.
6459 if (!rhsID->ClassImplementsProtocol(I, true))
6463 // If there are no qualifiers and no interface, we have an 'id'.
6466 // Both the right and left sides have qualifiers.
6467 for (auto *lhsProto : lhsQID->quals()) {
6470 // when comparing an id<P> on lhs with a static type on rhs,
6471 // see if static class implements all of id's protocols, directly or
6472 // through its super class and categories.
6473 for (auto *rhsProto : rhsOPT->quals()) {
6474 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6475 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6480 // If the RHS is a qualified interface pointer "NSString<P>*",
6481 // make sure we check the class hierarchy.
6482 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6483 for (auto *I : lhsQID->quals()) {
6484 // when comparing an id<P> on lhs with a static type on rhs,
6485 // see if static class implements all of id's protocols, directly or
6486 // through its super class and categories.
6487 if (rhsID->ClassImplementsProtocol(I, true)) {
6500 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6501 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6503 if (const ObjCObjectPointerType *lhsOPT =
6504 lhs->getAsObjCInterfacePointerType()) {
6505 // If both the right and left sides have qualifiers.
6506 for (auto *lhsProto : lhsOPT->quals()) {
6509 // when comparing an id<P> on rhs with a static type on lhs,
6510 // see if static class implements all of id's protocols, directly or
6511 // through its super class and categories.
6512 // First, lhs protocols in the qualifier list must be found, direct
6513 // or indirect in rhs's qualifier list or it is a mismatch.
6514 for (auto *rhsProto : rhsQID->quals()) {
6515 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6516 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6525 // Static class's protocols, or its super class or category protocols
6526 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6527 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6528 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6529 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6530 // This is rather dubious but matches gcc's behavior. If lhs has
6531 // no type qualifier and its class has no static protocol(s)
6532 // assume that it is mismatch.
6533 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6535 for (auto *lhsProto : LHSInheritedProtocols) {
6537 for (auto *rhsProto : rhsQID->quals()) {
6538 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6539 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6553 /// canAssignObjCInterfaces - Return true if the two interface types are
6554 /// compatible for assignment from RHS to LHS. This handles validation of any
6555 /// protocol qualifiers on the LHS or RHS.
6557 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6558 const ObjCObjectPointerType *RHSOPT) {
6559 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6560 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6562 // If either type represents the built-in 'id' or 'Class' types, return true.
6563 if (LHS->isObjCUnqualifiedIdOrClass() ||
6564 RHS->isObjCUnqualifiedIdOrClass())
6567 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6568 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6572 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6573 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6574 QualType(RHSOPT,0));
6576 // If we have 2 user-defined types, fall into that path.
6577 if (LHS->getInterface() && RHS->getInterface())
6578 return canAssignObjCInterfaces(LHS, RHS);
6583 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6584 /// for providing type-safety for objective-c pointers used to pass/return
6585 /// arguments in block literals. When passed as arguments, passing 'A*' where
6586 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6587 /// not OK. For the return type, the opposite is not OK.
6588 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6589 const ObjCObjectPointerType *LHSOPT,
6590 const ObjCObjectPointerType *RHSOPT,
6591 bool BlockReturnType) {
6592 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6595 if (LHSOPT->isObjCBuiltinType()) {
6596 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6599 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6600 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6604 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6605 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6606 if (LHS && RHS) { // We have 2 user-defined types.
6608 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6609 return BlockReturnType;
6610 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6611 return !BlockReturnType;
6619 /// getIntersectionOfProtocols - This routine finds the intersection of set
6620 /// of protocols inherited from two distinct objective-c pointer objects.
6621 /// It is used to build composite qualifier list of the composite type of
6622 /// the conditional expression involving two objective-c pointer objects.
6624 void getIntersectionOfProtocols(ASTContext &Context,
6625 const ObjCObjectPointerType *LHSOPT,
6626 const ObjCObjectPointerType *RHSOPT,
6627 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6629 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6630 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6631 assert(LHS->getInterface() && "LHS must have an interface base");
6632 assert(RHS->getInterface() && "RHS must have an interface base");
6634 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6635 unsigned LHSNumProtocols = LHS->getNumProtocols();
6636 if (LHSNumProtocols > 0)
6637 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6639 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6640 Context.CollectInheritedProtocols(LHS->getInterface(),
6641 LHSInheritedProtocols);
6642 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6643 LHSInheritedProtocols.end());
6646 unsigned RHSNumProtocols = RHS->getNumProtocols();
6647 if (RHSNumProtocols > 0) {
6648 ObjCProtocolDecl **RHSProtocols =
6649 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6650 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6651 if (InheritedProtocolSet.count(RHSProtocols[i]))
6652 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6654 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6655 Context.CollectInheritedProtocols(RHS->getInterface(),
6656 RHSInheritedProtocols);
6657 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6658 RHSInheritedProtocols.begin(),
6659 E = RHSInheritedProtocols.end(); I != E; ++I)
6660 if (InheritedProtocolSet.count((*I)))
6661 IntersectionOfProtocols.push_back((*I));
6665 /// areCommonBaseCompatible - Returns common base class of the two classes if
6666 /// one found. Note that this is O'2 algorithm. But it will be called as the
6667 /// last type comparison in a ?-exp of ObjC pointer types before a
6668 /// warning is issued. So, its invokation is extremely rare.
6669 QualType ASTContext::areCommonBaseCompatible(
6670 const ObjCObjectPointerType *Lptr,
6671 const ObjCObjectPointerType *Rptr) {
6672 const ObjCObjectType *LHS = Lptr->getObjectType();
6673 const ObjCObjectType *RHS = Rptr->getObjectType();
6674 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6675 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6676 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6680 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6681 if (canAssignObjCInterfaces(LHS, RHS)) {
6682 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6683 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6685 QualType Result = QualType(LHS, 0);
6686 if (!Protocols.empty())
6687 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6688 Result = getObjCObjectPointerType(Result);
6691 } while ((LDecl = LDecl->getSuperClass()));
6696 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6697 const ObjCObjectType *RHS) {
6698 assert(LHS->getInterface() && "LHS is not an interface type");
6699 assert(RHS->getInterface() && "RHS is not an interface type");
6701 // Verify that the base decls are compatible: the RHS must be a subclass of
6703 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6706 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6707 // protocol qualified at all, then we are good.
6708 if (LHS->getNumProtocols() == 0)
6711 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6712 // more detailed analysis is required.
6713 if (RHS->getNumProtocols() == 0) {
6714 // OK, if LHS is a superclass of RHS *and*
6715 // this superclass is assignment compatible with LHS.
6718 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6720 // OK if conversion of LHS to SuperClass results in narrowing of types
6721 // ; i.e., SuperClass may implement at least one of the protocols
6722 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6723 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6724 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6725 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6726 // If super class has no protocols, it is not a match.
6727 if (SuperClassInheritedProtocols.empty())
6730 for (const auto *LHSProto : LHS->quals()) {
6731 bool SuperImplementsProtocol = false;
6732 for (auto *SuperClassProto : SuperClassInheritedProtocols) {
6733 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6734 SuperImplementsProtocol = true;
6738 if (!SuperImplementsProtocol)
6746 for (const auto *LHSPI : LHS->quals()) {
6747 bool RHSImplementsProtocol = false;
6749 // If the RHS doesn't implement the protocol on the left, the types
6750 // are incompatible.
6751 for (auto *RHSPI : RHS->quals()) {
6752 if (RHSPI->lookupProtocolNamed(LHSPI->getIdentifier())) {
6753 RHSImplementsProtocol = true;
6757 // FIXME: For better diagnostics, consider passing back the protocol name.
6758 if (!RHSImplementsProtocol)
6761 // The RHS implements all protocols listed on the LHS.
6765 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6766 // get the "pointed to" types
6767 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6768 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6770 if (!LHSOPT || !RHSOPT)
6773 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6774 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6777 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6778 return canAssignObjCInterfaces(
6779 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6780 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6783 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6784 /// both shall have the identically qualified version of a compatible type.
6785 /// C99 6.2.7p1: Two types have compatible types if their types are the
6786 /// same. See 6.7.[2,3,5] for additional rules.
6787 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6788 bool CompareUnqualified) {
6789 if (getLangOpts().CPlusPlus)
6790 return hasSameType(LHS, RHS);
6792 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6795 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6796 return typesAreCompatible(LHS, RHS);
6799 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6800 return !mergeTypes(LHS, RHS, true).isNull();
6803 /// mergeTransparentUnionType - if T is a transparent union type and a member
6804 /// of T is compatible with SubType, return the merged type, else return
6806 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6807 bool OfBlockPointer,
6809 if (const RecordType *UT = T->getAsUnionType()) {
6810 RecordDecl *UD = UT->getDecl();
6811 if (UD->hasAttr<TransparentUnionAttr>()) {
6812 for (const auto *I : UD->fields()) {
6813 QualType ET = I->getType().getUnqualifiedType();
6814 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6824 /// mergeFunctionParameterTypes - merge two types which appear as function
6826 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6827 bool OfBlockPointer,
6829 // GNU extension: two types are compatible if they appear as a function
6830 // argument, one of the types is a transparent union type and the other
6831 // type is compatible with a union member
6832 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6834 if (!lmerge.isNull())
6837 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6839 if (!rmerge.isNull())
6842 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6845 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6846 bool OfBlockPointer,
6848 const FunctionType *lbase = lhs->getAs<FunctionType>();
6849 const FunctionType *rbase = rhs->getAs<FunctionType>();
6850 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6851 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6852 bool allLTypes = true;
6853 bool allRTypes = true;
6855 // Check return type
6857 if (OfBlockPointer) {
6858 QualType RHS = rbase->getReturnType();
6859 QualType LHS = lbase->getReturnType();
6860 bool UnqualifiedResult = Unqualified;
6861 if (!UnqualifiedResult)
6862 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6863 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6866 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
6868 if (retType.isNull()) return QualType();
6871 retType = retType.getUnqualifiedType();
6873 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6874 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
6876 LRetType = LRetType.getUnqualifiedType();
6877 RRetType = RRetType.getUnqualifiedType();
6880 if (getCanonicalType(retType) != LRetType)
6882 if (getCanonicalType(retType) != RRetType)
6885 // FIXME: double check this
6886 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6887 // rbase->getRegParmAttr() != 0 &&
6888 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6889 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6890 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6892 // Compatible functions must have compatible calling conventions
6893 if (lbaseInfo.getCC() != rbaseInfo.getCC())
6896 // Regparm is part of the calling convention.
6897 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6899 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6902 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6905 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6906 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6908 if (lbaseInfo.getNoReturn() != NoReturn)
6910 if (rbaseInfo.getNoReturn() != NoReturn)
6913 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6915 if (lproto && rproto) { // two C99 style function prototypes
6916 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6917 "C++ shouldn't be here");
6918 // Compatible functions must have the same number of parameters
6919 if (lproto->getNumParams() != rproto->getNumParams())
6922 // Variadic and non-variadic functions aren't compatible
6923 if (lproto->isVariadic() != rproto->isVariadic())
6926 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6929 if (LangOpts.ObjCAutoRefCount &&
6930 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6933 // Check parameter type compatibility
6934 SmallVector<QualType, 10> types;
6935 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6936 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6937 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6938 QualType paramType = mergeFunctionParameterTypes(
6939 lParamType, rParamType, OfBlockPointer, Unqualified);
6940 if (paramType.isNull())
6944 paramType = paramType.getUnqualifiedType();
6946 types.push_back(paramType);
6948 lParamType = lParamType.getUnqualifiedType();
6949 rParamType = rParamType.getUnqualifiedType();
6952 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
6954 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
6958 if (allLTypes) return lhs;
6959 if (allRTypes) return rhs;
6961 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6962 EPI.ExtInfo = einfo;
6963 return getFunctionType(retType, types, EPI);
6966 if (lproto) allRTypes = false;
6967 if (rproto) allLTypes = false;
6969 const FunctionProtoType *proto = lproto ? lproto : rproto;
6971 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
6972 if (proto->isVariadic()) return QualType();
6973 // Check that the types are compatible with the types that
6974 // would result from default argument promotions (C99 6.7.5.3p15).
6975 // The only types actually affected are promotable integer
6976 // types and floats, which would be passed as a different
6977 // type depending on whether the prototype is visible.
6978 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6979 QualType paramTy = proto->getParamType(i);
6981 // Look at the converted type of enum types, since that is the type used
6982 // to pass enum values.
6983 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6984 paramTy = Enum->getDecl()->getIntegerType();
6985 if (paramTy.isNull())
6989 if (paramTy->isPromotableIntegerType() ||
6990 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
6994 if (allLTypes) return lhs;
6995 if (allRTypes) return rhs;
6997 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6998 EPI.ExtInfo = einfo;
6999 return getFunctionType(retType, proto->getParamTypes(), EPI);
7002 if (allLTypes) return lhs;
7003 if (allRTypes) return rhs;
7004 return getFunctionNoProtoType(retType, einfo);
7007 /// Given that we have an enum type and a non-enum type, try to merge them.
7008 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7009 QualType other, bool isBlockReturnType) {
7010 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7011 // a signed integer type, or an unsigned integer type.
7012 // Compatibility is based on the underlying type, not the promotion
7014 QualType underlyingType = ET->getDecl()->getIntegerType();
7015 if (underlyingType.isNull()) return QualType();
7016 if (Context.hasSameType(underlyingType, other))
7019 // In block return types, we're more permissive and accept any
7020 // integral type of the same size.
7021 if (isBlockReturnType && other->isIntegerType() &&
7022 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7028 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7029 bool OfBlockPointer,
7030 bool Unqualified, bool BlockReturnType) {
7031 // C++ [expr]: If an expression initially has the type "reference to T", the
7032 // type is adjusted to "T" prior to any further analysis, the expression
7033 // designates the object or function denoted by the reference, and the
7034 // expression is an lvalue unless the reference is an rvalue reference and
7035 // the expression is a function call (possibly inside parentheses).
7036 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7037 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7040 LHS = LHS.getUnqualifiedType();
7041 RHS = RHS.getUnqualifiedType();
7044 QualType LHSCan = getCanonicalType(LHS),
7045 RHSCan = getCanonicalType(RHS);
7047 // If two types are identical, they are compatible.
7048 if (LHSCan == RHSCan)
7051 // If the qualifiers are different, the types aren't compatible... mostly.
7052 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7053 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7054 if (LQuals != RQuals) {
7055 // If any of these qualifiers are different, we have a type
7057 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7058 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7059 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7062 // Exactly one GC qualifier difference is allowed: __strong is
7063 // okay if the other type has no GC qualifier but is an Objective
7064 // C object pointer (i.e. implicitly strong by default). We fix
7065 // this by pretending that the unqualified type was actually
7066 // qualified __strong.
7067 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7068 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7069 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7071 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7074 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7075 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7077 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7078 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7083 // Okay, qualifiers are equal.
7085 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7086 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7088 // We want to consider the two function types to be the same for these
7089 // comparisons, just force one to the other.
7090 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7091 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7093 // Same as above for arrays
7094 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7095 LHSClass = Type::ConstantArray;
7096 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7097 RHSClass = Type::ConstantArray;
7099 // ObjCInterfaces are just specialized ObjCObjects.
7100 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7101 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7103 // Canonicalize ExtVector -> Vector.
7104 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7105 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7107 // If the canonical type classes don't match.
7108 if (LHSClass != RHSClass) {
7109 // Note that we only have special rules for turning block enum
7110 // returns into block int returns, not vice-versa.
7111 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7112 return mergeEnumWithInteger(*this, ETy, RHS, false);
7114 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7115 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7117 // allow block pointer type to match an 'id' type.
7118 if (OfBlockPointer && !BlockReturnType) {
7119 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7121 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7128 // The canonical type classes match.
7130 #define TYPE(Class, Base)
7131 #define ABSTRACT_TYPE(Class, Base)
7132 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7133 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7134 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7135 #include "clang/AST/TypeNodes.def"
7136 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7139 case Type::LValueReference:
7140 case Type::RValueReference:
7141 case Type::MemberPointer:
7142 llvm_unreachable("C++ should never be in mergeTypes");
7144 case Type::ObjCInterface:
7145 case Type::IncompleteArray:
7146 case Type::VariableArray:
7147 case Type::FunctionProto:
7148 case Type::ExtVector:
7149 llvm_unreachable("Types are eliminated above");
7153 // Merge two pointer types, while trying to preserve typedef info
7154 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7155 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7157 LHSPointee = LHSPointee.getUnqualifiedType();
7158 RHSPointee = RHSPointee.getUnqualifiedType();
7160 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7162 if (ResultType.isNull()) return QualType();
7163 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7165 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7167 return getPointerType(ResultType);
7169 case Type::BlockPointer:
7171 // Merge two block pointer types, while trying to preserve typedef info
7172 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7173 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7175 LHSPointee = LHSPointee.getUnqualifiedType();
7176 RHSPointee = RHSPointee.getUnqualifiedType();
7178 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7180 if (ResultType.isNull()) return QualType();
7181 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7183 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7185 return getBlockPointerType(ResultType);
7189 // Merge two pointer types, while trying to preserve typedef info
7190 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7191 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7193 LHSValue = LHSValue.getUnqualifiedType();
7194 RHSValue = RHSValue.getUnqualifiedType();
7196 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7198 if (ResultType.isNull()) return QualType();
7199 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7201 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7203 return getAtomicType(ResultType);
7205 case Type::ConstantArray:
7207 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7208 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7209 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7212 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7213 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7215 LHSElem = LHSElem.getUnqualifiedType();
7216 RHSElem = RHSElem.getUnqualifiedType();
7219 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7220 if (ResultType.isNull()) return QualType();
7221 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7223 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7225 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7226 ArrayType::ArraySizeModifier(), 0);
7227 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7228 ArrayType::ArraySizeModifier(), 0);
7229 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7230 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7231 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7233 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7236 // FIXME: This isn't correct! But tricky to implement because
7237 // the array's size has to be the size of LHS, but the type
7238 // has to be different.
7242 // FIXME: This isn't correct! But tricky to implement because
7243 // the array's size has to be the size of RHS, but the type
7244 // has to be different.
7247 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7248 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7249 return getIncompleteArrayType(ResultType,
7250 ArrayType::ArraySizeModifier(), 0);
7252 case Type::FunctionNoProto:
7253 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7258 // Only exactly equal builtin types are compatible, which is tested above.
7261 // Distinct complex types are incompatible.
7264 // FIXME: The merged type should be an ExtVector!
7265 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7266 RHSCan->getAs<VectorType>()))
7269 case Type::ObjCObject: {
7270 // Check if the types are assignment compatible.
7271 // FIXME: This should be type compatibility, e.g. whether
7272 // "LHS x; RHS x;" at global scope is legal.
7273 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7274 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7275 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7280 case Type::ObjCObjectPointer: {
7281 if (OfBlockPointer) {
7282 if (canAssignObjCInterfacesInBlockPointer(
7283 LHS->getAs<ObjCObjectPointerType>(),
7284 RHS->getAs<ObjCObjectPointerType>(),
7289 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7290 RHS->getAs<ObjCObjectPointerType>()))
7297 llvm_unreachable("Invalid Type::Class!");
7300 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7301 const FunctionProtoType *FromFunctionType,
7302 const FunctionProtoType *ToFunctionType) {
7303 if (FromFunctionType->hasAnyConsumedParams() !=
7304 ToFunctionType->hasAnyConsumedParams())
7306 FunctionProtoType::ExtProtoInfo FromEPI =
7307 FromFunctionType->getExtProtoInfo();
7308 FunctionProtoType::ExtProtoInfo ToEPI =
7309 ToFunctionType->getExtProtoInfo();
7310 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7311 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7312 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7318 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7319 /// 'RHS' attributes and returns the merged version; including for function
7321 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7322 QualType LHSCan = getCanonicalType(LHS),
7323 RHSCan = getCanonicalType(RHS);
7324 // If two types are identical, they are compatible.
7325 if (LHSCan == RHSCan)
7327 if (RHSCan->isFunctionType()) {
7328 if (!LHSCan->isFunctionType())
7330 QualType OldReturnType =
7331 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7332 QualType NewReturnType =
7333 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7334 QualType ResReturnType =
7335 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7336 if (ResReturnType.isNull())
7338 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7339 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7340 // In either case, use OldReturnType to build the new function type.
7341 const FunctionType *F = LHS->getAs<FunctionType>();
7342 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7343 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7344 EPI.ExtInfo = getFunctionExtInfo(LHS);
7345 QualType ResultType =
7346 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7353 // If the qualifiers are different, the types can still be merged.
7354 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7355 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7356 if (LQuals != RQuals) {
7357 // If any of these qualifiers are different, we have a type mismatch.
7358 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7359 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7362 // Exactly one GC qualifier difference is allowed: __strong is
7363 // okay if the other type has no GC qualifier but is an Objective
7364 // C object pointer (i.e. implicitly strong by default). We fix
7365 // this by pretending that the unqualified type was actually
7366 // qualified __strong.
7367 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7368 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7369 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7371 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7374 if (GC_L == Qualifiers::Strong)
7376 if (GC_R == Qualifiers::Strong)
7381 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7382 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7383 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7384 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7385 if (ResQT == LHSBaseQT)
7387 if (ResQT == RHSBaseQT)
7393 //===----------------------------------------------------------------------===//
7394 // Integer Predicates
7395 //===----------------------------------------------------------------------===//
7397 unsigned ASTContext::getIntWidth(QualType T) const {
7398 if (const EnumType *ET = T->getAs<EnumType>())
7399 T = ET->getDecl()->getIntegerType();
7400 if (T->isBooleanType())
7402 // For builtin types, just use the standard type sizing method
7403 return (unsigned)getTypeSize(T);
7406 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7407 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7409 // Turn <4 x signed int> -> <4 x unsigned int>
7410 if (const VectorType *VTy = T->getAs<VectorType>())
7411 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7412 VTy->getNumElements(), VTy->getVectorKind());
7414 // For enums, we return the unsigned version of the base type.
7415 if (const EnumType *ETy = T->getAs<EnumType>())
7416 T = ETy->getDecl()->getIntegerType();
7418 const BuiltinType *BTy = T->getAs<BuiltinType>();
7419 assert(BTy && "Unexpected signed integer type");
7420 switch (BTy->getKind()) {
7421 case BuiltinType::Char_S:
7422 case BuiltinType::SChar:
7423 return UnsignedCharTy;
7424 case BuiltinType::Short:
7425 return UnsignedShortTy;
7426 case BuiltinType::Int:
7427 return UnsignedIntTy;
7428 case BuiltinType::Long:
7429 return UnsignedLongTy;
7430 case BuiltinType::LongLong:
7431 return UnsignedLongLongTy;
7432 case BuiltinType::Int128:
7433 return UnsignedInt128Ty;
7435 llvm_unreachable("Unexpected signed integer type");
7439 ASTMutationListener::~ASTMutationListener() { }
7441 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7442 QualType ReturnType) {}
7444 //===----------------------------------------------------------------------===//
7445 // Builtin Type Computation
7446 //===----------------------------------------------------------------------===//
7448 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7449 /// pointer over the consumed characters. This returns the resultant type. If
7450 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7451 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7452 /// a vector of "i*".
7454 /// RequiresICE is filled in on return to indicate whether the value is required
7455 /// to be an Integer Constant Expression.
7456 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7457 ASTContext::GetBuiltinTypeError &Error,
7459 bool AllowTypeModifiers) {
7462 bool Signed = false, Unsigned = false;
7463 RequiresICE = false;
7465 // Read the prefixed modifiers first.
7469 default: Done = true; --Str; break;
7474 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7475 assert(!Signed && "Can't use 'S' modifier multiple times!");
7479 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7480 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7484 assert(HowLong <= 2 && "Can't have LLLL modifier");
7488 // This modifier represents int64 type.
7489 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7490 switch (Context.getTargetInfo().getInt64Type()) {
7492 llvm_unreachable("Unexpected integer type");
7493 case TargetInfo::SignedLong:
7496 case TargetInfo::SignedLongLong:
7505 // Read the base type.
7507 default: llvm_unreachable("Unknown builtin type letter!");
7509 assert(HowLong == 0 && !Signed && !Unsigned &&
7510 "Bad modifiers used with 'v'!");
7511 Type = Context.VoidTy;
7514 assert(HowLong == 0 && !Signed && !Unsigned &&
7515 "Bad modifiers used with 'f'!");
7516 Type = Context.HalfTy;
7519 assert(HowLong == 0 && !Signed && !Unsigned &&
7520 "Bad modifiers used with 'f'!");
7521 Type = Context.FloatTy;
7524 assert(HowLong < 2 && !Signed && !Unsigned &&
7525 "Bad modifiers used with 'd'!");
7527 Type = Context.LongDoubleTy;
7529 Type = Context.DoubleTy;
7532 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7534 Type = Context.UnsignedShortTy;
7536 Type = Context.ShortTy;
7540 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7541 else if (HowLong == 2)
7542 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7543 else if (HowLong == 1)
7544 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7546 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7549 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7551 Type = Context.SignedCharTy;
7553 Type = Context.UnsignedCharTy;
7555 Type = Context.CharTy;
7557 case 'b': // boolean
7558 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7559 Type = Context.BoolTy;
7561 case 'z': // size_t.
7562 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7563 Type = Context.getSizeType();
7566 Type = Context.getCFConstantStringType();
7569 Type = Context.getObjCIdType();
7572 Type = Context.getObjCSelType();
7575 Type = Context.getObjCSuperType();
7578 Type = Context.getBuiltinVaListType();
7579 assert(!Type.isNull() && "builtin va list type not initialized!");
7582 // This is a "reference" to a va_list; however, what exactly
7583 // this means depends on how va_list is defined. There are two
7584 // different kinds of va_list: ones passed by value, and ones
7585 // passed by reference. An example of a by-value va_list is
7586 // x86, where va_list is a char*. An example of by-ref va_list
7587 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7588 // we want this argument to be a char*&; for x86-64, we want
7589 // it to be a __va_list_tag*.
7590 Type = Context.getBuiltinVaListType();
7591 assert(!Type.isNull() && "builtin va list type not initialized!");
7592 if (Type->isArrayType())
7593 Type = Context.getArrayDecayedType(Type);
7595 Type = Context.getLValueReferenceType(Type);
7599 unsigned NumElements = strtoul(Str, &End, 10);
7600 assert(End != Str && "Missing vector size");
7603 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7604 RequiresICE, false);
7605 assert(!RequiresICE && "Can't require vector ICE");
7607 // TODO: No way to make AltiVec vectors in builtins yet.
7608 Type = Context.getVectorType(ElementType, NumElements,
7609 VectorType::GenericVector);
7615 unsigned NumElements = strtoul(Str, &End, 10);
7616 assert(End != Str && "Missing vector size");
7620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7622 Type = Context.getExtVectorType(ElementType, NumElements);
7626 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7628 assert(!RequiresICE && "Can't require complex ICE");
7629 Type = Context.getComplexType(ElementType);
7633 Type = Context.getPointerDiffType();
7637 Type = Context.getFILEType();
7638 if (Type.isNull()) {
7639 Error = ASTContext::GE_Missing_stdio;
7645 Type = Context.getsigjmp_bufType();
7647 Type = Context.getjmp_bufType();
7649 if (Type.isNull()) {
7650 Error = ASTContext::GE_Missing_setjmp;
7655 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7656 Type = Context.getucontext_tType();
7658 if (Type.isNull()) {
7659 Error = ASTContext::GE_Missing_ucontext;
7664 Type = Context.getProcessIDType();
7668 // If there are modifiers and if we're allowed to parse them, go for it.
7669 Done = !AllowTypeModifiers;
7671 switch (char c = *Str++) {
7672 default: Done = true; --Str; break;
7675 // Both pointers and references can have their pointee types
7676 // qualified with an address space.
7678 unsigned AddrSpace = strtoul(Str, &End, 10);
7679 if (End != Str && AddrSpace != 0) {
7680 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7684 Type = Context.getPointerType(Type);
7686 Type = Context.getLValueReferenceType(Type);
7689 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7691 Type = Type.withConst();
7694 Type = Context.getVolatileType(Type);
7697 Type = Type.withRestrict();
7702 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7703 "Integer constant 'I' type must be an integer");
7708 /// GetBuiltinType - Return the type for the specified builtin.
7709 QualType ASTContext::GetBuiltinType(unsigned Id,
7710 GetBuiltinTypeError &Error,
7711 unsigned *IntegerConstantArgs) const {
7712 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7714 SmallVector<QualType, 8> ArgTypes;
7716 bool RequiresICE = false;
7718 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7720 if (Error != GE_None)
7723 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7725 while (TypeStr[0] && TypeStr[0] != '.') {
7726 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7727 if (Error != GE_None)
7730 // If this argument is required to be an IntegerConstantExpression and the
7731 // caller cares, fill in the bitmask we return.
7732 if (RequiresICE && IntegerConstantArgs)
7733 *IntegerConstantArgs |= 1 << ArgTypes.size();
7735 // Do array -> pointer decay. The builtin should use the decayed type.
7736 if (Ty->isArrayType())
7737 Ty = getArrayDecayedType(Ty);
7739 ArgTypes.push_back(Ty);
7742 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7743 "'.' should only occur at end of builtin type list!");
7745 FunctionType::ExtInfo EI(CC_C);
7746 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7748 bool Variadic = (TypeStr[0] == '.');
7750 // We really shouldn't be making a no-proto type here, especially in C++.
7751 if (ArgTypes.empty() && Variadic)
7752 return getFunctionNoProtoType(ResType, EI);
7754 FunctionProtoType::ExtProtoInfo EPI;
7756 EPI.Variadic = Variadic;
7758 return getFunctionType(ResType, ArgTypes, EPI);
7761 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7762 const FunctionDecl *FD) {
7763 if (!FD->isExternallyVisible())
7764 return GVA_Internal;
7766 GVALinkage External = GVA_StrongExternal;
7767 switch (FD->getTemplateSpecializationKind()) {
7768 case TSK_Undeclared:
7769 case TSK_ExplicitSpecialization:
7770 External = GVA_StrongExternal;
7773 case TSK_ExplicitInstantiationDefinition:
7774 return GVA_StrongODR;
7776 // C++11 [temp.explicit]p10:
7777 // [ Note: The intent is that an inline function that is the subject of
7778 // an explicit instantiation declaration will still be implicitly
7779 // instantiated when used so that the body can be considered for
7780 // inlining, but that no out-of-line copy of the inline function would be
7781 // generated in the translation unit. -- end note ]
7782 case TSK_ExplicitInstantiationDeclaration:
7783 return GVA_AvailableExternally;
7785 case TSK_ImplicitInstantiation:
7786 External = GVA_DiscardableODR;
7790 if (!FD->isInlined())
7793 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7794 !FD->hasAttr<DLLExportAttr>()) ||
7795 FD->hasAttr<GNUInlineAttr>()) {
7796 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7798 // GNU or C99 inline semantics. Determine whether this symbol should be
7799 // externally visible.
7800 if (FD->isInlineDefinitionExternallyVisible())
7803 // C99 inline semantics, where the symbol is not externally visible.
7804 return GVA_AvailableExternally;
7807 // Functions specified with extern and inline in -fms-compatibility mode
7808 // forcibly get emitted. While the body of the function cannot be later
7809 // replaced, the function definition cannot be discarded.
7810 if (FD->getMostRecentDecl()->isMSExternInline())
7811 return GVA_StrongODR;
7813 return GVA_DiscardableODR;
7816 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7817 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7818 // dllexport/dllimport on inline functions.
7819 if (D->hasAttr<DLLImportAttr>()) {
7820 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7821 return GVA_AvailableExternally;
7822 } else if (D->hasAttr<DLLExportAttr>()) {
7823 if (L == GVA_DiscardableODR)
7824 return GVA_StrongODR;
7829 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7830 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7834 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7835 const VarDecl *VD) {
7836 if (!VD->isExternallyVisible())
7837 return GVA_Internal;
7839 if (VD->isStaticLocal()) {
7840 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7841 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7842 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7843 LexicalContext = LexicalContext->getLexicalParent();
7845 // Let the static local variable inherit it's linkage from the nearest
7846 // enclosing function.
7848 StaticLocalLinkage =
7849 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
7851 // GVA_StrongODR function linkage is stronger than what we need,
7852 // downgrade to GVA_DiscardableODR.
7853 // This allows us to discard the variable if we never end up needing it.
7854 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7855 : StaticLocalLinkage;
7858 // MSVC treats in-class initialized static data members as definitions.
7859 // By giving them non-strong linkage, out-of-line definitions won't
7860 // cause link errors.
7861 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7862 return GVA_DiscardableODR;
7864 switch (VD->getTemplateSpecializationKind()) {
7865 case TSK_Undeclared:
7866 case TSK_ExplicitSpecialization:
7867 return GVA_StrongExternal;
7869 case TSK_ExplicitInstantiationDefinition:
7870 return GVA_StrongODR;
7872 case TSK_ExplicitInstantiationDeclaration:
7873 return GVA_AvailableExternally;
7875 case TSK_ImplicitInstantiation:
7876 return GVA_DiscardableODR;
7879 llvm_unreachable("Invalid Linkage!");
7882 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7883 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7887 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7888 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7889 if (!VD->isFileVarDecl())
7891 // Global named register variables (GNU extension) are never emitted.
7892 if (VD->getStorageClass() == SC_Register)
7894 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7895 // We never need to emit an uninstantiated function template.
7896 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7901 // If this is a member of a class template, we do not need to emit it.
7902 if (D->getDeclContext()->isDependentContext())
7905 // Weak references don't produce any output by themselves.
7906 if (D->hasAttr<WeakRefAttr>())
7909 // Aliases and used decls are required.
7910 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7913 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7914 // Forward declarations aren't required.
7915 if (!FD->doesThisDeclarationHaveABody())
7916 return FD->doesDeclarationForceExternallyVisibleDefinition();
7918 // Constructors and destructors are required.
7919 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7922 // The key function for a class is required. This rule only comes
7923 // into play when inline functions can be key functions, though.
7924 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7925 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7926 const CXXRecordDecl *RD = MD->getParent();
7927 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7928 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7929 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7935 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7937 // static, static inline, always_inline, and extern inline functions can
7938 // always be deferred. Normal inline functions can be deferred in C99/C++.
7939 // Implicit template instantiations can also be deferred in C++.
7940 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
7941 Linkage == GVA_DiscardableODR)
7946 const VarDecl *VD = cast<VarDecl>(D);
7947 assert(VD->isFileVarDecl() && "Expected file scoped var");
7949 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
7950 !isMSStaticDataMemberInlineDefinition(VD))
7953 // Variables that can be needed in other TUs are required.
7954 GVALinkage L = GetGVALinkageForVariable(VD);
7955 if (L != GVA_Internal && L != GVA_AvailableExternally &&
7956 L != GVA_DiscardableODR)
7959 // Variables that have destruction with side-effects are required.
7960 if (VD->getType().isDestructedType())
7963 // Variables that have initialization with side-effects are required.
7964 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7970 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7971 bool IsCXXMethod) const {
7972 // Pass through to the C++ ABI object
7974 return ABI->getDefaultMethodCallConv(IsVariadic);
7976 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
7979 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7980 // Pass through to the C++ ABI object
7981 return ABI->isNearlyEmpty(RD);
7984 VTableContextBase *ASTContext::getVTableContext() {
7985 if (!VTContext.get()) {
7986 if (Target->getCXXABI().isMicrosoft())
7987 VTContext.reset(new MicrosoftVTableContext(*this));
7989 VTContext.reset(new ItaniumVTableContext(*this));
7991 return VTContext.get();
7994 MangleContext *ASTContext::createMangleContext() {
7995 switch (Target->getCXXABI().getKind()) {
7996 case TargetCXXABI::GenericAArch64:
7997 case TargetCXXABI::GenericItanium:
7998 case TargetCXXABI::GenericARM:
7999 case TargetCXXABI::iOS:
8000 case TargetCXXABI::iOS64:
8001 return ItaniumMangleContext::create(*this, getDiagnostics());
8002 case TargetCXXABI::Microsoft:
8003 return MicrosoftMangleContext::create(*this, getDiagnostics());
8005 llvm_unreachable("Unsupported ABI");
8008 CXXABI::~CXXABI() {}
8010 size_t ASTContext::getSideTableAllocatedMemory() const {
8011 return ASTRecordLayouts.getMemorySize() +
8012 llvm::capacity_in_bytes(ObjCLayouts) +
8013 llvm::capacity_in_bytes(KeyFunctions) +
8014 llvm::capacity_in_bytes(ObjCImpls) +
8015 llvm::capacity_in_bytes(BlockVarCopyInits) +
8016 llvm::capacity_in_bytes(DeclAttrs) +
8017 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8018 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8019 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8020 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8021 llvm::capacity_in_bytes(OverriddenMethods) +
8022 llvm::capacity_in_bytes(Types) +
8023 llvm::capacity_in_bytes(VariableArrayTypes) +
8024 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8027 /// getIntTypeForBitwidth -
8028 /// sets integer QualTy according to specified details:
8029 /// bitwidth, signed/unsigned.
8030 /// Returns empty type if there is no appropriate target types.
8031 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8032 unsigned Signed) const {
8033 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8034 CanQualType QualTy = getFromTargetType(Ty);
8035 if (!QualTy && DestWidth == 128)
8036 return Signed ? Int128Ty : UnsignedInt128Ty;
8040 /// getRealTypeForBitwidth -
8041 /// sets floating point QualTy according to specified bitwidth.
8042 /// Returns empty type if there is no appropriate target types.
8043 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8044 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8046 case TargetInfo::Float:
8048 case TargetInfo::Double:
8050 case TargetInfo::LongDouble:
8051 return LongDoubleTy;
8052 case TargetInfo::NoFloat:
8056 llvm_unreachable("Unhandled TargetInfo::RealType value");
8059 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8061 MangleNumbers[ND] = Number;
8064 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8065 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8066 MangleNumbers.find(ND);
8067 return I != MangleNumbers.end() ? I->second : 1;
8070 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8072 StaticLocalNumbers[VD] = Number;
8075 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8076 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8077 StaticLocalNumbers.find(VD);
8078 return I != StaticLocalNumbers.end() ? I->second : 1;
8081 MangleNumberingContext &
8082 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8083 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8084 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8086 MCtx = createMangleNumberingContext();
8090 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8091 return ABI->createMangleNumberingContext();
8094 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8095 ParamIndices[D] = index;
8098 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8099 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8100 assert(I != ParamIndices.end() &&
8101 "ParmIndices lacks entry set by ParmVarDecl");
8106 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8108 assert(E && E->getStorageDuration() == SD_Static &&
8109 "don't need to cache the computed value for this temporary");
8111 return &MaterializedTemporaryValues[E];
8113 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8114 MaterializedTemporaryValues.find(E);
8115 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
8118 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8119 const llvm::Triple &T = getTargetInfo().getTriple();
8120 if (!T.isOSDarwin())
8123 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8124 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8127 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8128 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8129 uint64_t Size = sizeChars.getQuantity();
8130 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8131 unsigned Align = alignChars.getQuantity();
8132 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8133 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8138 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8139 /// parents as defined by the \c RecursiveASTVisitor.
8141 /// Note that the relationship described here is purely in terms of AST
8142 /// traversal - there are other relationships (for example declaration context)
8143 /// in the AST that are better modeled by special matchers.
8145 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8146 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8149 /// \brief Builds and returns the translation unit's parent map.
8151 /// The caller takes ownership of the returned \c ParentMap.
8152 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8153 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8154 Visitor.TraverseDecl(&TU);
8155 return Visitor.Parents;
8159 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8161 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8164 bool shouldVisitTemplateInstantiations() const {
8167 bool shouldVisitImplicitCode() const {
8170 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8171 // are not triggered during data recursion.
8172 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8176 template <typename T>
8177 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8180 if (ParentStack.size() > 0) {
8181 // FIXME: Currently we add the same parent multiple times, but only
8182 // when no memoization data is available for the type.
8183 // For example when we visit all subexpressions of template
8184 // instantiations; this is suboptimal, but benign: the only way to
8185 // visit those is with hasAncestor / hasParent, and those do not create
8187 // The plan is to enable DynTypedNode to be storable in a map or hash
8188 // map. The main problem there is to implement hash functions /
8189 // comparison operators for all types that DynTypedNode supports that
8190 // do not have pointer identity.
8191 auto &NodeOrVector = (*Parents)[Node];
8192 if (NodeOrVector.isNull()) {
8193 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8195 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8197 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8198 auto *Vector = new ASTContext::ParentVector(1, *Node);
8199 NodeOrVector = Vector;
8202 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8205 NodeOrVector.template get<ASTContext::ParentVector *>();
8206 // Skip duplicates for types that have memoization data.
8207 // We must check that the type has memoization data before calling
8208 // std::find() because DynTypedNode::operator== can't compare all
8210 bool Found = ParentStack.back().getMemoizationData() &&
8211 std::find(Vector->begin(), Vector->end(),
8212 ParentStack.back()) != Vector->end();
8214 Vector->push_back(ParentStack.back());
8217 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8218 bool Result = (this ->* traverse) (Node);
8219 ParentStack.pop_back();
8223 bool TraverseDecl(Decl *DeclNode) {
8224 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8227 bool TraverseStmt(Stmt *StmtNode) {
8228 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8231 ASTContext::ParentMap *Parents;
8232 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8234 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8239 ASTContext::ParentVector
8240 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8241 assert(Node.getMemoizationData() &&
8242 "Invariant broken: only nodes that support memoization may be "
8243 "used in the parent map.");
8245 // We always need to run over the whole translation unit, as
8246 // hasAncestor can escape any subtree.
8248 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8250 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8251 if (I == AllParents->end()) {
8252 return ParentVector();
8254 if (I->second.is<ast_type_traits::DynTypedNode *>()) {
8255 return ParentVector(1, *I->second.get<ast_type_traits::DynTypedNode *>());
8257 const auto &Parents = *I->second.get<ParentVector *>();
8258 return ParentVector(Parents.begin(), Parents.end());
8262 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8263 const ObjCMethodDecl *MethodImpl) {
8264 // No point trying to match an unavailable/deprecated mothod.
8265 if (MethodDecl->hasAttr<UnavailableAttr>()
8266 || MethodDecl->hasAttr<DeprecatedAttr>())
8268 if (MethodDecl->getObjCDeclQualifier() !=
8269 MethodImpl->getObjCDeclQualifier())
8271 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8274 if (MethodDecl->param_size() != MethodImpl->param_size())
8277 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8278 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8279 EF = MethodDecl->param_end();
8280 IM != EM && IF != EF; ++IM, ++IF) {
8281 const ParmVarDecl *DeclVar = (*IF);
8282 const ParmVarDecl *ImplVar = (*IM);
8283 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8285 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8288 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8292 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8293 // doesn't include ASTContext.h
8295 clang::LazyGenerationalUpdatePtr<
8296 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8297 clang::LazyGenerationalUpdatePtr<
8298 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8299 const clang::ASTContext &Ctx, Decl *Value);