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/RecordLayout.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/Capacity.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
40 using namespace clang;
42 unsigned ASTContext::NumImplicitDefaultConstructors;
43 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
44 unsigned ASTContext::NumImplicitCopyConstructors;
45 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
46 unsigned ASTContext::NumImplicitMoveConstructors;
47 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
50 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
52 unsigned ASTContext::NumImplicitDestructors;
53 unsigned ASTContext::NumImplicitDestructorsDeclared;
56 HalfRank, FloatRank, DoubleRank, LongDoubleRank
59 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
60 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
67 // User can not attach documentation to implicit declarations.
71 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
96 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
101 // When tag declaration (but not definition!) is part of the
102 // decl-specifier-seq of some other declaration, it doesn't get comment
103 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
106 // TODO: handle comments for function parameters properly.
107 if (isa<ParmVarDecl>(D))
110 // TODO: we could look up template parameter documentation in the template
112 if (isa<TemplateTypeParmDecl>(D) ||
113 isa<NonTypeTemplateParmDecl>(D) ||
114 isa<TemplateTemplateParmDecl>(D))
117 ArrayRef<RawComment *> RawComments = Comments.getComments();
119 // If there are no comments anywhere, we won't find anything.
120 if (RawComments.empty())
123 // Find declaration location.
124 // For Objective-C declarations we generally don't expect to have multiple
125 // declarators, thus use declaration starting location as the "declaration
127 // For all other declarations multiple declarators are used quite frequently,
128 // so we use the location of the identifier as the "declaration location".
129 SourceLocation DeclLoc;
130 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
131 isa<ObjCPropertyDecl>(D) ||
132 isa<RedeclarableTemplateDecl>(D) ||
133 isa<ClassTemplateSpecializationDecl>(D))
134 DeclLoc = D->getLocStart();
136 DeclLoc = D->getLocation();
138 // If the declaration doesn't map directly to a location in a file, we
139 // can't find the comment.
140 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
143 // Find the comment that occurs just after this declaration.
144 ArrayRef<RawComment *>::iterator Comment;
146 // When searching for comments during parsing, the comment we are looking
147 // for is usually among the last two comments we parsed -- check them
149 RawComment CommentAtDeclLoc(
150 SourceMgr, SourceRange(DeclLoc), false,
151 LangOpts.CommentOpts.ParseAllComments);
152 BeforeThanCompare<RawComment> Compare(SourceMgr);
153 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
154 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
155 if (!Found && RawComments.size() >= 2) {
157 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
161 Comment = MaybeBeforeDecl + 1;
162 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
163 &CommentAtDeclLoc, Compare));
166 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
167 &CommentAtDeclLoc, Compare);
171 // Decompose the location for the declaration and find the beginning of the
173 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
175 // First check whether we have a trailing comment.
176 if (Comment != RawComments.end() &&
177 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
178 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
179 std::pair<FileID, unsigned> CommentBeginDecomp
180 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
181 // Check that Doxygen trailing comment comes after the declaration, starts
182 // on the same line and in the same file as the declaration.
183 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
184 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
185 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
186 CommentBeginDecomp.second)) {
191 // The comment just after the declaration was not a trailing comment.
192 // Let's look at the previous comment.
193 if (Comment == RawComments.begin())
197 // Check that we actually have a non-member Doxygen comment.
198 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
201 // Decompose the end of the comment.
202 std::pair<FileID, unsigned> CommentEndDecomp
203 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
205 // If the comment and the declaration aren't in the same file, then they
207 if (DeclLocDecomp.first != CommentEndDecomp.first)
210 // Get the corresponding buffer.
211 bool Invalid = false;
212 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
217 // Extract text between the comment and declaration.
218 StringRef Text(Buffer + CommentEndDecomp.second,
219 DeclLocDecomp.second - CommentEndDecomp.second);
221 // There should be no other declarations or preprocessor directives between
222 // comment and declaration.
223 if (Text.find_first_of(",;{}#@") != StringRef::npos)
230 /// If we have a 'templated' declaration for a template, adjust 'D' to
231 /// refer to the actual template.
232 /// If we have an implicit instantiation, adjust 'D' to refer to template.
233 const Decl *adjustDeclToTemplate(const Decl *D) {
234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
235 // Is this function declaration part of a function template?
236 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
239 // Nothing to do if function is not an implicit instantiation.
240 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
243 // Function is an implicit instantiation of a function template?
244 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
247 // Function is instantiated from a member definition of a class template?
248 if (const FunctionDecl *MemberDecl =
249 FD->getInstantiatedFromMemberFunction())
254 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
255 // Static data member is instantiated from a member definition of a class
257 if (VD->isStaticDataMember())
258 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
263 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
264 // Is this class declaration part of a class template?
265 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
268 // Class is an implicit instantiation of a class template or partial
270 if (const ClassTemplateSpecializationDecl *CTSD =
271 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
272 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
274 llvm::PointerUnion<ClassTemplateDecl *,
275 ClassTemplatePartialSpecializationDecl *>
276 PU = CTSD->getSpecializedTemplateOrPartial();
277 return PU.is<ClassTemplateDecl*>() ?
278 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
279 static_cast<const Decl*>(
280 PU.get<ClassTemplatePartialSpecializationDecl *>());
283 // Class is instantiated from a member definition of a class template?
284 if (const MemberSpecializationInfo *Info =
285 CRD->getMemberSpecializationInfo())
286 return Info->getInstantiatedFrom();
290 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
291 // Enum is instantiated from a member definition of a class template?
292 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
297 // FIXME: Adjust alias templates?
300 } // unnamed namespace
302 const RawComment *ASTContext::getRawCommentForAnyRedecl(
304 const Decl **OriginalDecl) const {
305 D = adjustDeclToTemplate(D);
307 // Check whether we have cached a comment for this declaration already.
309 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
310 RedeclComments.find(D);
311 if (Pos != RedeclComments.end()) {
312 const RawCommentAndCacheFlags &Raw = Pos->second;
313 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 *OriginalDecl = Raw.getOriginalDecl();
321 // Search for comments attached to declarations in the redeclaration chain.
322 const RawComment *RC = NULL;
323 const Decl *OriginalDeclForRC = NULL;
324 for (Decl::redecl_iterator I = D->redecls_begin(),
325 E = D->redecls_end();
327 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
328 RedeclComments.find(*I);
329 if (Pos != RedeclComments.end()) {
330 const RawCommentAndCacheFlags &Raw = Pos->second;
331 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
333 OriginalDeclForRC = Raw.getOriginalDecl();
337 RC = getRawCommentForDeclNoCache(*I);
338 OriginalDeclForRC = *I;
339 RawCommentAndCacheFlags Raw;
342 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
344 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
345 Raw.setOriginalDecl(*I);
346 RedeclComments[*I] = Raw;
352 // If we found a comment, it should be a documentation comment.
353 assert(!RC || RC->isDocumentation());
356 *OriginalDecl = OriginalDeclForRC;
358 // Update cache for every declaration in the redeclaration chain.
359 RawCommentAndCacheFlags Raw;
361 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
362 Raw.setOriginalDecl(OriginalDeclForRC);
364 for (Decl::redecl_iterator I = D->redecls_begin(),
365 E = D->redecls_end();
367 RawCommentAndCacheFlags &R = RedeclComments[*I];
368 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
375 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
376 SmallVectorImpl<const NamedDecl *> &Redeclared) {
377 const DeclContext *DC = ObjCMethod->getDeclContext();
378 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
379 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
382 // Add redeclared method here.
383 for (ObjCInterfaceDecl::known_extensions_iterator
384 Ext = ID->known_extensions_begin(),
385 ExtEnd = ID->known_extensions_end();
386 Ext != ExtEnd; ++Ext) {
387 if (ObjCMethodDecl *RedeclaredMethod =
388 Ext->getMethod(ObjCMethod->getSelector(),
389 ObjCMethod->isInstanceMethod()))
390 Redeclared.push_back(RedeclaredMethod);
395 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
396 const Decl *D) const {
397 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
398 ThisDeclInfo->CommentDecl = D;
399 ThisDeclInfo->IsFilled = false;
400 ThisDeclInfo->fill();
401 ThisDeclInfo->CommentDecl = FC->getDecl();
402 comments::FullComment *CFC =
403 new (*this) comments::FullComment(FC->getBlocks(),
409 comments::FullComment *ASTContext::getCommentForDecl(
411 const Preprocessor *PP) const {
412 D = adjustDeclToTemplate(D);
414 const Decl *Canonical = D->getCanonicalDecl();
415 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
416 ParsedComments.find(Canonical);
418 if (Pos != ParsedComments.end()) {
419 if (Canonical != D) {
420 comments::FullComment *FC = Pos->second;
421 comments::FullComment *CFC = cloneFullComment(FC, D);
427 const Decl *OriginalDecl;
429 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
431 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
432 SmallVector<const NamedDecl*, 8> Overridden;
433 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
434 if (OMD && OMD->isPropertyAccessor())
435 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
436 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
437 return cloneFullComment(FC, D);
439 addRedeclaredMethods(OMD, Overridden);
440 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
441 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
442 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
443 return cloneFullComment(FC, D);
445 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
446 // Attach any tag type's documentation to its typedef if latter
447 // does not have one of its own.
448 QualType QT = TD->getUnderlyingType();
449 if (const TagType *TT = QT->getAs<TagType>())
450 if (const Decl *TD = TT->getDecl())
451 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
452 return cloneFullComment(FC, D);
454 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
455 while (IC->getSuperClass()) {
456 IC = IC->getSuperClass();
457 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
458 return cloneFullComment(FC, D);
461 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
462 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
463 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
464 return cloneFullComment(FC, D);
466 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
467 if (!(RD = RD->getDefinition()))
469 // Check non-virtual bases.
470 for (CXXRecordDecl::base_class_const_iterator I =
471 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
472 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
474 QualType Ty = I->getType();
477 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
478 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
481 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
482 return cloneFullComment(FC, D);
485 // Check virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
488 if (I->getAccessSpecifier() != AS_public)
490 QualType Ty = I->getType();
493 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(VirtualBase= VirtualBase->getDefinition()))
496 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
497 return cloneFullComment(FC, D);
504 // If the RawComment was attached to other redeclaration of this Decl, we
505 // should parse the comment in context of that other Decl. This is important
506 // because comments can contain references to parameter names which can be
507 // different across redeclarations.
508 if (D != OriginalDecl)
509 return getCommentForDecl(OriginalDecl, PP);
511 comments::FullComment *FC = RC->parse(*this, PP, D);
512 ParsedComments[Canonical] = FC;
517 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
518 TemplateTemplateParmDecl *Parm) {
519 ID.AddInteger(Parm->getDepth());
520 ID.AddInteger(Parm->getPosition());
521 ID.AddBoolean(Parm->isParameterPack());
523 TemplateParameterList *Params = Parm->getTemplateParameters();
524 ID.AddInteger(Params->size());
525 for (TemplateParameterList::const_iterator P = Params->begin(),
526 PEnd = Params->end();
528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
530 ID.AddBoolean(TTP->isParameterPack());
534 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
536 ID.AddBoolean(NTTP->isParameterPack());
537 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
538 if (NTTP->isExpandedParameterPack()) {
540 ID.AddInteger(NTTP->getNumExpansionTypes());
541 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
542 QualType T = NTTP->getExpansionType(I);
543 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
546 ID.AddBoolean(false);
550 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
556 TemplateTemplateParmDecl *
557 ASTContext::getCanonicalTemplateTemplateParmDecl(
558 TemplateTemplateParmDecl *TTP) const {
559 // Check if we already have a canonical template template parameter.
560 llvm::FoldingSetNodeID ID;
561 CanonicalTemplateTemplateParm::Profile(ID, TTP);
563 CanonicalTemplateTemplateParm *Canonical
564 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
566 return Canonical->getParam();
568 // Build a canonical template parameter list.
569 TemplateParameterList *Params = TTP->getTemplateParameters();
570 SmallVector<NamedDecl *, 4> CanonParams;
571 CanonParams.reserve(Params->size());
572 for (TemplateParameterList::const_iterator P = Params->begin(),
573 PEnd = Params->end();
575 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
576 CanonParams.push_back(
577 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
581 TTP->getIndex(), 0, false,
582 TTP->isParameterPack()));
583 else if (NonTypeTemplateParmDecl *NTTP
584 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
585 QualType T = getCanonicalType(NTTP->getType());
586 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
587 NonTypeTemplateParmDecl *Param;
588 if (NTTP->isExpandedParameterPack()) {
589 SmallVector<QualType, 2> ExpandedTypes;
590 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
591 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
592 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
593 ExpandedTInfos.push_back(
594 getTrivialTypeSourceInfo(ExpandedTypes.back()));
597 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
601 NTTP->getPosition(), 0,
604 ExpandedTypes.data(),
605 ExpandedTypes.size(),
606 ExpandedTInfos.data());
608 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
612 NTTP->getPosition(), 0,
614 NTTP->isParameterPack(),
617 CanonParams.push_back(Param);
620 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
621 cast<TemplateTemplateParmDecl>(*P)));
624 TemplateTemplateParmDecl *CanonTTP
625 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
626 SourceLocation(), TTP->getDepth(),
628 TTP->isParameterPack(),
630 TemplateParameterList::Create(*this, SourceLocation(),
636 // Get the new insert position for the node we care about.
637 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
638 assert(Canonical == 0 && "Shouldn't be in the map!");
641 // Create the canonical template template parameter entry.
642 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
643 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
647 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
648 if (!LangOpts.CPlusPlus) return 0;
650 switch (T.getCXXABI().getKind()) {
651 case TargetCXXABI::GenericARM:
652 case TargetCXXABI::iOS:
653 return CreateARMCXXABI(*this);
654 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
655 case TargetCXXABI::GenericItanium:
656 return CreateItaniumCXXABI(*this);
657 case TargetCXXABI::Microsoft:
658 return CreateMicrosoftCXXABI(*this);
660 llvm_unreachable("Invalid CXXABI type!");
663 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
664 const LangOptions &LOpts) {
665 if (LOpts.FakeAddressSpaceMap) {
666 // The fake address space map must have a distinct entry for each
667 // language-specific address space.
668 static const unsigned FakeAddrSpaceMap[] = {
671 3, // opencl_constant
676 return &FakeAddrSpaceMap;
678 return &T.getAddressSpaceMap();
682 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
684 IdentifierTable &idents, SelectorTable &sels,
685 Builtin::Context &builtins,
686 unsigned size_reserve,
687 bool DelayInitialization)
688 : FunctionProtoTypes(this_()),
689 TemplateSpecializationTypes(this_()),
690 DependentTemplateSpecializationTypes(this_()),
691 SubstTemplateTemplateParmPacks(this_()),
692 GlobalNestedNameSpecifier(0),
693 Int128Decl(0), UInt128Decl(0),
694 BuiltinVaListDecl(0),
695 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
697 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
699 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
700 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
701 cudaConfigureCallDecl(0),
702 NullTypeSourceInfo(QualType()),
703 FirstLocalImport(), LastLocalImport(),
704 SourceMgr(SM), LangOpts(LOpts),
705 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
706 Idents(idents), Selectors(sels),
707 BuiltinInfo(builtins),
708 DeclarationNames(*this),
709 ExternalSource(0), Listener(0),
710 Comments(SM), CommentsLoaded(false),
711 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
713 UniqueBlockByRefTypeID(0)
715 if (size_reserve > 0) Types.reserve(size_reserve);
716 TUDecl = TranslationUnitDecl::Create(*this);
718 if (!DelayInitialization) {
719 assert(t && "No target supplied for ASTContext initialization");
720 InitBuiltinTypes(*t);
724 ASTContext::~ASTContext() {
725 // Release the DenseMaps associated with DeclContext objects.
726 // FIXME: Is this the ideal solution?
727 ReleaseDeclContextMaps();
729 // Call all of the deallocation functions.
730 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
731 Deallocations[I].first(Deallocations[I].second);
733 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
734 // because they can contain DenseMaps.
735 for (llvm::DenseMap<const ObjCContainerDecl*,
736 const ASTRecordLayout*>::iterator
737 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
738 // Increment in loop to prevent using deallocated memory.
739 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
742 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
743 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
744 // Increment in loop to prevent using deallocated memory.
745 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
749 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
750 AEnd = DeclAttrs.end();
752 A->second->~AttrVec();
755 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
756 Deallocations.push_back(std::make_pair(Callback, Data));
760 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
761 ExternalSource.reset(Source.take());
764 void ASTContext::PrintStats() const {
765 llvm::errs() << "\n*** AST Context Stats:\n";
766 llvm::errs() << " " << Types.size() << " types total.\n";
768 unsigned counts[] = {
769 #define TYPE(Name, Parent) 0,
770 #define ABSTRACT_TYPE(Name, Parent)
771 #include "clang/AST/TypeNodes.def"
775 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
777 counts[(unsigned)T->getTypeClass()]++;
781 unsigned TotalBytes = 0;
782 #define TYPE(Name, Parent) \
784 llvm::errs() << " " << counts[Idx] << " " << #Name \
786 TotalBytes += counts[Idx] * sizeof(Name##Type); \
788 #define ABSTRACT_TYPE(Name, Parent)
789 #include "clang/AST/TypeNodes.def"
791 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
793 // Implicit special member functions.
794 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
795 << NumImplicitDefaultConstructors
796 << " implicit default constructors created\n";
797 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
798 << NumImplicitCopyConstructors
799 << " implicit copy constructors created\n";
800 if (getLangOpts().CPlusPlus)
801 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
802 << NumImplicitMoveConstructors
803 << " implicit move constructors created\n";
804 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
805 << NumImplicitCopyAssignmentOperators
806 << " implicit copy assignment operators created\n";
807 if (getLangOpts().CPlusPlus)
808 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
809 << NumImplicitMoveAssignmentOperators
810 << " implicit move assignment operators created\n";
811 llvm::errs() << NumImplicitDestructorsDeclared << "/"
812 << NumImplicitDestructors
813 << " implicit destructors created\n";
815 if (ExternalSource.get()) {
816 llvm::errs() << "\n";
817 ExternalSource->PrintStats();
820 BumpAlloc.PrintStats();
823 TypedefDecl *ASTContext::getInt128Decl() const {
825 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
826 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
827 getTranslationUnitDecl(),
830 &Idents.get("__int128_t"),
837 TypedefDecl *ASTContext::getUInt128Decl() const {
839 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
840 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
841 getTranslationUnitDecl(),
844 &Idents.get("__uint128_t"),
851 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
852 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
853 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
857 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
858 assert((!this->Target || this->Target == &Target) &&
859 "Incorrect target reinitialization");
860 assert(VoidTy.isNull() && "Context reinitialized?");
862 this->Target = &Target;
864 ABI.reset(createCXXABI(Target));
865 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
868 InitBuiltinType(VoidTy, BuiltinType::Void);
871 InitBuiltinType(BoolTy, BuiltinType::Bool);
873 if (LangOpts.CharIsSigned)
874 InitBuiltinType(CharTy, BuiltinType::Char_S);
876 InitBuiltinType(CharTy, BuiltinType::Char_U);
878 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
879 InitBuiltinType(ShortTy, BuiltinType::Short);
880 InitBuiltinType(IntTy, BuiltinType::Int);
881 InitBuiltinType(LongTy, BuiltinType::Long);
882 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
885 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
886 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
887 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
888 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
889 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
892 InitBuiltinType(FloatTy, BuiltinType::Float);
893 InitBuiltinType(DoubleTy, BuiltinType::Double);
894 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
896 // GNU extension, 128-bit integers.
897 InitBuiltinType(Int128Ty, BuiltinType::Int128);
898 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
900 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
901 if (TargetInfo::isTypeSigned(Target.getWCharType()))
902 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
903 else // -fshort-wchar makes wchar_t be unsigned.
904 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
905 } else // C99 (or C++ using -fno-wchar)
906 WCharTy = getFromTargetType(Target.getWCharType());
908 WIntTy = getFromTargetType(Target.getWIntType());
910 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
911 InitBuiltinType(Char16Ty, BuiltinType::Char16);
913 Char16Ty = getFromTargetType(Target.getChar16Type());
915 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
916 InitBuiltinType(Char32Ty, BuiltinType::Char32);
918 Char32Ty = getFromTargetType(Target.getChar32Type());
920 // Placeholder type for type-dependent expressions whose type is
921 // completely unknown. No code should ever check a type against
922 // DependentTy and users should never see it; however, it is here to
923 // help diagnose failures to properly check for type-dependent
925 InitBuiltinType(DependentTy, BuiltinType::Dependent);
927 // Placeholder type for functions.
928 InitBuiltinType(OverloadTy, BuiltinType::Overload);
930 // Placeholder type for bound members.
931 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
933 // Placeholder type for pseudo-objects.
934 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
936 // "any" type; useful for debugger-like clients.
937 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
939 // Placeholder type for unbridged ARC casts.
940 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
942 // Placeholder type for builtin functions.
943 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
946 FloatComplexTy = getComplexType(FloatTy);
947 DoubleComplexTy = getComplexType(DoubleTy);
948 LongDoubleComplexTy = getComplexType(LongDoubleTy);
950 // Builtin types for 'id', 'Class', and 'SEL'.
951 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
952 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
953 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
955 if (LangOpts.OpenCL) {
956 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
957 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
958 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
959 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
960 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
961 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
963 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
964 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
967 // Builtin type for __objc_yes and __objc_no
968 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
969 SignedCharTy : BoolTy);
971 ObjCConstantStringType = QualType();
973 ObjCSuperType = QualType();
976 VoidPtrTy = getPointerType(VoidTy);
978 // nullptr type (C++0x 2.14.7)
979 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
981 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
982 InitBuiltinType(HalfTy, BuiltinType::Half);
984 // Builtin type used to help define __builtin_va_list.
985 VaListTagTy = QualType();
988 DiagnosticsEngine &ASTContext::getDiagnostics() const {
989 return SourceMgr.getDiagnostics();
992 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
993 AttrVec *&Result = DeclAttrs[D];
995 void *Mem = Allocate(sizeof(AttrVec));
996 Result = new (Mem) AttrVec;
1002 /// \brief Erase the attributes corresponding to the given declaration.
1003 void ASTContext::eraseDeclAttrs(const Decl *D) {
1004 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1005 if (Pos != DeclAttrs.end()) {
1006 Pos->second->~AttrVec();
1007 DeclAttrs.erase(Pos);
1011 MemberSpecializationInfo *
1012 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1013 assert(Var->isStaticDataMember() && "Not a static data member");
1014 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
1015 = InstantiatedFromStaticDataMember.find(Var);
1016 if (Pos == InstantiatedFromStaticDataMember.end())
1023 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1024 TemplateSpecializationKind TSK,
1025 SourceLocation PointOfInstantiation) {
1026 assert(Inst->isStaticDataMember() && "Not a static data member");
1027 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1028 assert(!InstantiatedFromStaticDataMember[Inst] &&
1029 "Already noted what static data member was instantiated from");
1030 InstantiatedFromStaticDataMember[Inst]
1031 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
1034 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1035 const FunctionDecl *FD){
1036 assert(FD && "Specialization is 0");
1037 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1038 = ClassScopeSpecializationPattern.find(FD);
1039 if (Pos == ClassScopeSpecializationPattern.end())
1045 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1046 FunctionDecl *Pattern) {
1047 assert(FD && "Specialization is 0");
1048 assert(Pattern && "Class scope specialization pattern is 0");
1049 ClassScopeSpecializationPattern[FD] = Pattern;
1053 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1054 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1055 = InstantiatedFromUsingDecl.find(UUD);
1056 if (Pos == InstantiatedFromUsingDecl.end())
1063 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1064 assert((isa<UsingDecl>(Pattern) ||
1065 isa<UnresolvedUsingValueDecl>(Pattern) ||
1066 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1067 "pattern decl is not a using decl");
1068 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1069 InstantiatedFromUsingDecl[Inst] = Pattern;
1073 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1074 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1075 = InstantiatedFromUsingShadowDecl.find(Inst);
1076 if (Pos == InstantiatedFromUsingShadowDecl.end())
1083 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1084 UsingShadowDecl *Pattern) {
1085 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1086 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1089 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1090 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1091 = InstantiatedFromUnnamedFieldDecl.find(Field);
1092 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1098 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1100 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1101 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1102 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1103 "Already noted what unnamed field was instantiated from");
1105 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1108 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1109 const FieldDecl *LastFD) const {
1110 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
1111 FD->getBitWidthValue(*this) == 0);
1114 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1115 const FieldDecl *LastFD) const {
1116 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
1117 FD->getBitWidthValue(*this) == 0 &&
1118 LastFD->getBitWidthValue(*this) != 0);
1121 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1122 const FieldDecl *LastFD) const {
1123 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
1124 FD->getBitWidthValue(*this) &&
1125 LastFD->getBitWidthValue(*this));
1128 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
1129 const FieldDecl *LastFD) const {
1130 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
1131 LastFD->getBitWidthValue(*this));
1134 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
1135 const FieldDecl *LastFD) const {
1136 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
1137 FD->getBitWidthValue(*this));
1140 ASTContext::overridden_cxx_method_iterator
1141 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1142 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1143 = OverriddenMethods.find(Method->getCanonicalDecl());
1144 if (Pos == OverriddenMethods.end())
1147 return Pos->second.begin();
1150 ASTContext::overridden_cxx_method_iterator
1151 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1152 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1153 = OverriddenMethods.find(Method->getCanonicalDecl());
1154 if (Pos == OverriddenMethods.end())
1157 return Pos->second.end();
1161 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1162 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1163 = OverriddenMethods.find(Method->getCanonicalDecl());
1164 if (Pos == OverriddenMethods.end())
1167 return Pos->second.size();
1170 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1171 const CXXMethodDecl *Overridden) {
1172 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1173 OverriddenMethods[Method].push_back(Overridden);
1176 void ASTContext::getOverriddenMethods(
1178 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1181 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1182 Overridden.append(overridden_methods_begin(CXXMethod),
1183 overridden_methods_end(CXXMethod));
1187 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1191 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1192 Method->getOverriddenMethods(OverDecls);
1193 Overridden.append(OverDecls.begin(), OverDecls.end());
1196 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1197 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1198 assert(!Import->isFromASTFile() && "Non-local import declaration");
1199 if (!FirstLocalImport) {
1200 FirstLocalImport = Import;
1201 LastLocalImport = Import;
1205 LastLocalImport->NextLocalImport = Import;
1206 LastLocalImport = Import;
1209 //===----------------------------------------------------------------------===//
1210 // Type Sizing and Analysis
1211 //===----------------------------------------------------------------------===//
1213 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1214 /// scalar floating point type.
1215 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1216 const BuiltinType *BT = T->getAs<BuiltinType>();
1217 assert(BT && "Not a floating point type!");
1218 switch (BT->getKind()) {
1219 default: llvm_unreachable("Not a floating point type!");
1220 case BuiltinType::Half: return Target->getHalfFormat();
1221 case BuiltinType::Float: return Target->getFloatFormat();
1222 case BuiltinType::Double: return Target->getDoubleFormat();
1223 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1227 /// getDeclAlign - Return a conservative estimate of the alignment of the
1228 /// specified decl. Note that bitfields do not have a valid alignment, so
1229 /// this method will assert on them.
1230 /// If @p RefAsPointee, references are treated like their underlying type
1231 /// (for alignof), else they're treated like pointers (for CodeGen).
1232 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
1233 unsigned Align = Target->getCharWidth();
1235 bool UseAlignAttrOnly = false;
1236 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1237 Align = AlignFromAttr;
1239 // __attribute__((aligned)) can increase or decrease alignment
1240 // *except* on a struct or struct member, where it only increases
1241 // alignment unless 'packed' is also specified.
1243 // It is an error for alignas to decrease alignment, so we can
1244 // ignore that possibility; Sema should diagnose it.
1245 if (isa<FieldDecl>(D)) {
1246 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1247 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1249 UseAlignAttrOnly = true;
1252 else if (isa<FieldDecl>(D))
1254 D->hasAttr<PackedAttr>() ||
1255 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1257 // If we're using the align attribute only, just ignore everything
1258 // else about the declaration and its type.
1259 if (UseAlignAttrOnly) {
1262 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1263 QualType T = VD->getType();
1264 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
1266 T = RT->getPointeeType();
1268 T = getPointerType(RT->getPointeeType());
1270 if (!T->isIncompleteType() && !T->isFunctionType()) {
1271 // Adjust alignments of declarations with array type by the
1272 // large-array alignment on the target.
1273 unsigned MinWidth = Target->getLargeArrayMinWidth();
1274 const ArrayType *arrayType;
1275 if (MinWidth && (arrayType = getAsArrayType(T))) {
1276 if (isa<VariableArrayType>(arrayType))
1277 Align = std::max(Align, Target->getLargeArrayAlign());
1278 else if (isa<ConstantArrayType>(arrayType) &&
1279 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1280 Align = std::max(Align, Target->getLargeArrayAlign());
1282 // Walk through any array types while we're at it.
1283 T = getBaseElementType(arrayType);
1285 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1286 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1287 if (VD->hasGlobalStorage())
1288 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1292 // Fields can be subject to extra alignment constraints, like if
1293 // the field is packed, the struct is packed, or the struct has a
1294 // a max-field-alignment constraint (#pragma pack). So calculate
1295 // the actual alignment of the field within the struct, and then
1296 // (as we're expected to) constrain that by the alignment of the type.
1297 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1298 // So calculate the alignment of the field.
1299 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1301 // Start with the record's overall alignment.
1302 unsigned fieldAlign = toBits(layout.getAlignment());
1304 // Use the GCD of that and the offset within the record.
1305 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1307 // Alignment is always a power of 2, so the GCD will be a power of 2,
1308 // which means we get to do this crazy thing instead of Euclid's.
1309 uint64_t lowBitOfOffset = offset & (~offset + 1);
1310 if (lowBitOfOffset < fieldAlign)
1311 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1314 Align = std::min(Align, fieldAlign);
1318 return toCharUnitsFromBits(Align);
1321 // getTypeInfoDataSizeInChars - Return the size of a type, in
1322 // chars. If the type is a record, its data size is returned. This is
1323 // the size of the memcpy that's performed when assigning this type
1324 // using a trivial copy/move assignment operator.
1325 std::pair<CharUnits, CharUnits>
1326 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1327 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1329 // In C++, objects can sometimes be allocated into the tail padding
1330 // of a base-class subobject. We decide whether that's possible
1331 // during class layout, so here we can just trust the layout results.
1332 if (getLangOpts().CPlusPlus) {
1333 if (const RecordType *RT = T->getAs<RecordType>()) {
1334 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1335 sizeAndAlign.first = layout.getDataSize();
1339 return sizeAndAlign;
1342 std::pair<CharUnits, CharUnits>
1343 ASTContext::getTypeInfoInChars(const Type *T) const {
1344 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1345 return std::make_pair(toCharUnitsFromBits(Info.first),
1346 toCharUnitsFromBits(Info.second));
1349 std::pair<CharUnits, CharUnits>
1350 ASTContext::getTypeInfoInChars(QualType T) const {
1351 return getTypeInfoInChars(T.getTypePtr());
1354 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1355 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1356 if (it != MemoizedTypeInfo.end())
1359 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1360 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1364 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1365 /// method does not work on incomplete types.
1367 /// FIXME: Pointers into different addr spaces could have different sizes and
1368 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1369 /// should take a QualType, &c.
1370 std::pair<uint64_t, unsigned>
1371 ASTContext::getTypeInfoImpl(const Type *T) const {
1374 switch (T->getTypeClass()) {
1375 #define TYPE(Class, Base)
1376 #define ABSTRACT_TYPE(Class, Base)
1377 #define NON_CANONICAL_TYPE(Class, Base)
1378 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1379 #include "clang/AST/TypeNodes.def"
1380 llvm_unreachable("Should not see dependent types");
1382 case Type::FunctionNoProto:
1383 case Type::FunctionProto:
1384 // GCC extension: alignof(function) = 32 bits
1389 case Type::IncompleteArray:
1390 case Type::VariableArray:
1392 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1395 case Type::ConstantArray: {
1396 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1398 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1399 uint64_t Size = CAT->getSize().getZExtValue();
1400 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1401 "Overflow in array type bit size evaluation");
1402 Width = EltInfo.first*Size;
1403 Align = EltInfo.second;
1404 Width = llvm::RoundUpToAlignment(Width, Align);
1407 case Type::ExtVector:
1408 case Type::Vector: {
1409 const VectorType *VT = cast<VectorType>(T);
1410 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1411 Width = EltInfo.first*VT->getNumElements();
1413 // If the alignment is not a power of 2, round up to the next power of 2.
1414 // This happens for non-power-of-2 length vectors.
1415 if (Align & (Align-1)) {
1416 Align = llvm::NextPowerOf2(Align);
1417 Width = llvm::RoundUpToAlignment(Width, Align);
1419 // Adjust the alignment based on the target max.
1420 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1421 if (TargetVectorAlign && TargetVectorAlign < Align)
1422 Align = TargetVectorAlign;
1427 switch (cast<BuiltinType>(T)->getKind()) {
1428 default: llvm_unreachable("Unknown builtin type!");
1429 case BuiltinType::Void:
1430 // GCC extension: alignof(void) = 8 bits.
1435 case BuiltinType::Bool:
1436 Width = Target->getBoolWidth();
1437 Align = Target->getBoolAlign();
1439 case BuiltinType::Char_S:
1440 case BuiltinType::Char_U:
1441 case BuiltinType::UChar:
1442 case BuiltinType::SChar:
1443 Width = Target->getCharWidth();
1444 Align = Target->getCharAlign();
1446 case BuiltinType::WChar_S:
1447 case BuiltinType::WChar_U:
1448 Width = Target->getWCharWidth();
1449 Align = Target->getWCharAlign();
1451 case BuiltinType::Char16:
1452 Width = Target->getChar16Width();
1453 Align = Target->getChar16Align();
1455 case BuiltinType::Char32:
1456 Width = Target->getChar32Width();
1457 Align = Target->getChar32Align();
1459 case BuiltinType::UShort:
1460 case BuiltinType::Short:
1461 Width = Target->getShortWidth();
1462 Align = Target->getShortAlign();
1464 case BuiltinType::UInt:
1465 case BuiltinType::Int:
1466 Width = Target->getIntWidth();
1467 Align = Target->getIntAlign();
1469 case BuiltinType::ULong:
1470 case BuiltinType::Long:
1471 Width = Target->getLongWidth();
1472 Align = Target->getLongAlign();
1474 case BuiltinType::ULongLong:
1475 case BuiltinType::LongLong:
1476 Width = Target->getLongLongWidth();
1477 Align = Target->getLongLongAlign();
1479 case BuiltinType::Int128:
1480 case BuiltinType::UInt128:
1482 Align = 128; // int128_t is 128-bit aligned on all targets.
1484 case BuiltinType::Half:
1485 Width = Target->getHalfWidth();
1486 Align = Target->getHalfAlign();
1488 case BuiltinType::Float:
1489 Width = Target->getFloatWidth();
1490 Align = Target->getFloatAlign();
1492 case BuiltinType::Double:
1493 Width = Target->getDoubleWidth();
1494 Align = Target->getDoubleAlign();
1496 case BuiltinType::LongDouble:
1497 Width = Target->getLongDoubleWidth();
1498 Align = Target->getLongDoubleAlign();
1500 case BuiltinType::NullPtr:
1501 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1502 Align = Target->getPointerAlign(0); // == sizeof(void*)
1504 case BuiltinType::ObjCId:
1505 case BuiltinType::ObjCClass:
1506 case BuiltinType::ObjCSel:
1507 Width = Target->getPointerWidth(0);
1508 Align = Target->getPointerAlign(0);
1510 case BuiltinType::OCLSampler:
1511 // Samplers are modeled as integers.
1512 Width = Target->getIntWidth();
1513 Align = Target->getIntAlign();
1515 case BuiltinType::OCLEvent:
1516 case BuiltinType::OCLImage1d:
1517 case BuiltinType::OCLImage1dArray:
1518 case BuiltinType::OCLImage1dBuffer:
1519 case BuiltinType::OCLImage2d:
1520 case BuiltinType::OCLImage2dArray:
1521 case BuiltinType::OCLImage3d:
1522 // Currently these types are pointers to opaque types.
1523 Width = Target->getPointerWidth(0);
1524 Align = Target->getPointerAlign(0);
1528 case Type::ObjCObjectPointer:
1529 Width = Target->getPointerWidth(0);
1530 Align = Target->getPointerAlign(0);
1532 case Type::BlockPointer: {
1533 unsigned AS = getTargetAddressSpace(
1534 cast<BlockPointerType>(T)->getPointeeType());
1535 Width = Target->getPointerWidth(AS);
1536 Align = Target->getPointerAlign(AS);
1539 case Type::LValueReference:
1540 case Type::RValueReference: {
1541 // alignof and sizeof should never enter this code path here, so we go
1542 // the pointer route.
1543 unsigned AS = getTargetAddressSpace(
1544 cast<ReferenceType>(T)->getPointeeType());
1545 Width = Target->getPointerWidth(AS);
1546 Align = Target->getPointerAlign(AS);
1549 case Type::Pointer: {
1550 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1551 Width = Target->getPointerWidth(AS);
1552 Align = Target->getPointerAlign(AS);
1555 case Type::MemberPointer: {
1556 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1557 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1560 case Type::Complex: {
1561 // Complex types have the same alignment as their elements, but twice the
1563 std::pair<uint64_t, unsigned> EltInfo =
1564 getTypeInfo(cast<ComplexType>(T)->getElementType());
1565 Width = EltInfo.first*2;
1566 Align = EltInfo.second;
1569 case Type::ObjCObject:
1570 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1571 case Type::ObjCInterface: {
1572 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1573 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1574 Width = toBits(Layout.getSize());
1575 Align = toBits(Layout.getAlignment());
1580 const TagType *TT = cast<TagType>(T);
1582 if (TT->getDecl()->isInvalidDecl()) {
1588 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1589 return getTypeInfo(ET->getDecl()->getIntegerType());
1591 const RecordType *RT = cast<RecordType>(TT);
1592 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1593 Width = toBits(Layout.getSize());
1594 Align = toBits(Layout.getAlignment());
1598 case Type::SubstTemplateTypeParm:
1599 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1600 getReplacementType().getTypePtr());
1603 const AutoType *A = cast<AutoType>(T);
1604 assert(!A->getDeducedType().isNull() &&
1605 "cannot request the size of an undeduced or dependent auto type");
1606 return getTypeInfo(A->getDeducedType().getTypePtr());
1610 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1612 case Type::Typedef: {
1613 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1614 std::pair<uint64_t, unsigned> Info
1615 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1616 // If the typedef has an aligned attribute on it, it overrides any computed
1617 // alignment we have. This violates the GCC documentation (which says that
1618 // attribute(aligned) can only round up) but matches its implementation.
1619 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1622 Align = Info.second;
1627 case Type::TypeOfExpr:
1628 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1632 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1634 case Type::Decltype:
1635 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1638 case Type::UnaryTransform:
1639 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1641 case Type::Elaborated:
1642 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1644 case Type::Attributed:
1646 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1648 case Type::TemplateSpecialization: {
1649 assert(getCanonicalType(T) != T &&
1650 "Cannot request the size of a dependent type");
1651 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1652 // A type alias template specialization may refer to a typedef with the
1653 // aligned attribute on it.
1654 if (TST->isTypeAlias())
1655 return getTypeInfo(TST->getAliasedType().getTypePtr());
1657 return getTypeInfo(getCanonicalType(T));
1660 case Type::Atomic: {
1661 // Start with the base type information.
1662 std::pair<uint64_t, unsigned> Info
1663 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1665 Align = Info.second;
1667 // If the size of the type doesn't exceed the platform's max
1668 // atomic promotion width, make the size and alignment more
1669 // favorable to atomic operations:
1670 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1671 // Round the size up to a power of 2.
1672 if (!llvm::isPowerOf2_64(Width))
1673 Width = llvm::NextPowerOf2(Width);
1675 // Set the alignment equal to the size.
1676 Align = static_cast<unsigned>(Width);
1682 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1683 return std::make_pair(Width, Align);
1686 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1687 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1688 return CharUnits::fromQuantity(BitSize / getCharWidth());
1691 /// toBits - Convert a size in characters to a size in characters.
1692 int64_t ASTContext::toBits(CharUnits CharSize) const {
1693 return CharSize.getQuantity() * getCharWidth();
1696 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1697 /// This method does not work on incomplete types.
1698 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1699 return toCharUnitsFromBits(getTypeSize(T));
1701 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1702 return toCharUnitsFromBits(getTypeSize(T));
1705 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1706 /// characters. This method does not work on incomplete types.
1707 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1708 return toCharUnitsFromBits(getTypeAlign(T));
1710 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1711 return toCharUnitsFromBits(getTypeAlign(T));
1714 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1715 /// type for the current target in bits. This can be different than the ABI
1716 /// alignment in cases where it is beneficial for performance to overalign
1718 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1719 unsigned ABIAlign = getTypeAlign(T);
1721 // Double and long long should be naturally aligned if possible.
1722 if (const ComplexType* CT = T->getAs<ComplexType>())
1723 T = CT->getElementType().getTypePtr();
1724 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1725 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1726 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1727 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1732 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1733 /// to a global variable of the specified type.
1734 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1735 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1738 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1739 /// should be given to a global variable of the specified type.
1740 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1741 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1744 /// DeepCollectObjCIvars -
1745 /// This routine first collects all declared, but not synthesized, ivars in
1746 /// super class and then collects all ivars, including those synthesized for
1747 /// current class. This routine is used for implementation of current class
1748 /// when all ivars, declared and synthesized are known.
1750 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1752 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1753 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1754 DeepCollectObjCIvars(SuperClass, false, Ivars);
1756 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1757 E = OI->ivar_end(); I != E; ++I)
1758 Ivars.push_back(*I);
1760 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1761 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1762 Iv= Iv->getNextIvar())
1763 Ivars.push_back(Iv);
1767 /// CollectInheritedProtocols - Collect all protocols in current class and
1768 /// those inherited by it.
1769 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1770 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1771 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1772 // We can use protocol_iterator here instead of
1773 // all_referenced_protocol_iterator since we are walking all categories.
1774 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1775 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1776 ObjCProtocolDecl *Proto = (*P);
1777 Protocols.insert(Proto->getCanonicalDecl());
1778 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1779 PE = Proto->protocol_end(); P != PE; ++P) {
1780 Protocols.insert((*P)->getCanonicalDecl());
1781 CollectInheritedProtocols(*P, Protocols);
1785 // Categories of this Interface.
1786 for (ObjCInterfaceDecl::visible_categories_iterator
1787 Cat = OI->visible_categories_begin(),
1788 CatEnd = OI->visible_categories_end();
1789 Cat != CatEnd; ++Cat) {
1790 CollectInheritedProtocols(*Cat, Protocols);
1793 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1795 CollectInheritedProtocols(SD, Protocols);
1796 SD = SD->getSuperClass();
1798 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1799 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1800 PE = OC->protocol_end(); P != PE; ++P) {
1801 ObjCProtocolDecl *Proto = (*P);
1802 Protocols.insert(Proto->getCanonicalDecl());
1803 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1804 PE = Proto->protocol_end(); P != PE; ++P)
1805 CollectInheritedProtocols(*P, Protocols);
1807 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1808 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1809 PE = OP->protocol_end(); P != PE; ++P) {
1810 ObjCProtocolDecl *Proto = (*P);
1811 Protocols.insert(Proto->getCanonicalDecl());
1812 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1813 PE = Proto->protocol_end(); P != PE; ++P)
1814 CollectInheritedProtocols(*P, Protocols);
1819 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1821 // Count ivars declared in class extension.
1822 for (ObjCInterfaceDecl::known_extensions_iterator
1823 Ext = OI->known_extensions_begin(),
1824 ExtEnd = OI->known_extensions_end();
1825 Ext != ExtEnd; ++Ext) {
1826 count += Ext->ivar_size();
1829 // Count ivar defined in this class's implementation. This
1830 // includes synthesized ivars.
1831 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1832 count += ImplDecl->ivar_size();
1837 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1841 // nullptr_t is always treated as null.
1842 if (E->getType()->isNullPtrType()) return true;
1844 if (E->getType()->isAnyPointerType() &&
1845 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1846 Expr::NPC_ValueDependentIsNull))
1849 // Unfortunately, __null has type 'int'.
1850 if (isa<GNUNullExpr>(E)) return true;
1855 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1856 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1857 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1858 I = ObjCImpls.find(D);
1859 if (I != ObjCImpls.end())
1860 return cast<ObjCImplementationDecl>(I->second);
1863 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1864 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1865 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1866 I = ObjCImpls.find(D);
1867 if (I != ObjCImpls.end())
1868 return cast<ObjCCategoryImplDecl>(I->second);
1872 /// \brief Set the implementation of ObjCInterfaceDecl.
1873 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1874 ObjCImplementationDecl *ImplD) {
1875 assert(IFaceD && ImplD && "Passed null params");
1876 ObjCImpls[IFaceD] = ImplD;
1878 /// \brief Set the implementation of ObjCCategoryDecl.
1879 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1880 ObjCCategoryImplDecl *ImplD) {
1881 assert(CatD && ImplD && "Passed null params");
1882 ObjCImpls[CatD] = ImplD;
1885 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1886 const NamedDecl *ND) const {
1887 if (const ObjCInterfaceDecl *ID =
1888 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1890 if (const ObjCCategoryDecl *CD =
1891 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1892 return CD->getClassInterface();
1893 if (const ObjCImplDecl *IMD =
1894 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1895 return IMD->getClassInterface();
1900 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1902 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1903 assert(VD && "Passed null params");
1904 assert(VD->hasAttr<BlocksAttr>() &&
1905 "getBlockVarCopyInits - not __block var");
1906 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1907 I = BlockVarCopyInits.find(VD);
1908 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1911 /// \brief Set the copy inialization expression of a block var decl.
1912 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1913 assert(VD && Init && "Passed null params");
1914 assert(VD->hasAttr<BlocksAttr>() &&
1915 "setBlockVarCopyInits - not __block var");
1916 BlockVarCopyInits[VD] = Init;
1919 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1920 unsigned DataSize) const {
1922 DataSize = TypeLoc::getFullDataSizeForType(T);
1924 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1925 "incorrect data size provided to CreateTypeSourceInfo!");
1927 TypeSourceInfo *TInfo =
1928 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1929 new (TInfo) TypeSourceInfo(T);
1933 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1934 SourceLocation L) const {
1935 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1936 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1940 const ASTRecordLayout &
1941 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1942 return getObjCLayout(D, 0);
1945 const ASTRecordLayout &
1946 ASTContext::getASTObjCImplementationLayout(
1947 const ObjCImplementationDecl *D) const {
1948 return getObjCLayout(D->getClassInterface(), D);
1951 //===----------------------------------------------------------------------===//
1952 // Type creation/memoization methods
1953 //===----------------------------------------------------------------------===//
1956 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1957 unsigned fastQuals = quals.getFastQualifiers();
1958 quals.removeFastQualifiers();
1960 // Check if we've already instantiated this type.
1961 llvm::FoldingSetNodeID ID;
1962 ExtQuals::Profile(ID, baseType, quals);
1963 void *insertPos = 0;
1964 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1965 assert(eq->getQualifiers() == quals);
1966 return QualType(eq, fastQuals);
1969 // If the base type is not canonical, make the appropriate canonical type.
1971 if (!baseType->isCanonicalUnqualified()) {
1972 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1973 canonSplit.Quals.addConsistentQualifiers(quals);
1974 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
1976 // Re-find the insert position.
1977 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1980 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1981 ExtQualNodes.InsertNode(eq, insertPos);
1982 return QualType(eq, fastQuals);
1986 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1987 QualType CanT = getCanonicalType(T);
1988 if (CanT.getAddressSpace() == AddressSpace)
1991 // If we are composing extended qualifiers together, merge together
1992 // into one ExtQuals node.
1993 QualifierCollector Quals;
1994 const Type *TypeNode = Quals.strip(T);
1996 // If this type already has an address space specified, it cannot get
1998 assert(!Quals.hasAddressSpace() &&
1999 "Type cannot be in multiple addr spaces!");
2000 Quals.addAddressSpace(AddressSpace);
2002 return getExtQualType(TypeNode, Quals);
2005 QualType ASTContext::getObjCGCQualType(QualType T,
2006 Qualifiers::GC GCAttr) const {
2007 QualType CanT = getCanonicalType(T);
2008 if (CanT.getObjCGCAttr() == GCAttr)
2011 if (const PointerType *ptr = T->getAs<PointerType>()) {
2012 QualType Pointee = ptr->getPointeeType();
2013 if (Pointee->isAnyPointerType()) {
2014 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2015 return getPointerType(ResultType);
2019 // If we are composing extended qualifiers together, merge together
2020 // into one ExtQuals node.
2021 QualifierCollector Quals;
2022 const Type *TypeNode = Quals.strip(T);
2024 // If this type already has an ObjCGC specified, it cannot get
2026 assert(!Quals.hasObjCGCAttr() &&
2027 "Type cannot have multiple ObjCGCs!");
2028 Quals.addObjCGCAttr(GCAttr);
2030 return getExtQualType(TypeNode, Quals);
2033 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2034 FunctionType::ExtInfo Info) {
2035 if (T->getExtInfo() == Info)
2039 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2040 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2042 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2043 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2045 Result = getFunctionType(FPT->getResultType(),
2046 ArrayRef<QualType>(FPT->arg_type_begin(),
2051 return cast<FunctionType>(Result.getTypePtr());
2054 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2055 QualType ResultType) {
2056 // FIXME: Need to inform serialization code about this!
2057 for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
2058 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2059 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2060 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2064 /// getComplexType - Return the uniqued reference to the type for a complex
2065 /// number with the specified element type.
2066 QualType ASTContext::getComplexType(QualType T) const {
2067 // Unique pointers, to guarantee there is only one pointer of a particular
2069 llvm::FoldingSetNodeID ID;
2070 ComplexType::Profile(ID, T);
2072 void *InsertPos = 0;
2073 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2074 return QualType(CT, 0);
2076 // If the pointee type isn't canonical, this won't be a canonical type either,
2077 // so fill in the canonical type field.
2079 if (!T.isCanonical()) {
2080 Canonical = getComplexType(getCanonicalType(T));
2082 // Get the new insert position for the node we care about.
2083 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2084 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2086 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2087 Types.push_back(New);
2088 ComplexTypes.InsertNode(New, InsertPos);
2089 return QualType(New, 0);
2092 /// getPointerType - Return the uniqued reference to the type for a pointer to
2093 /// the specified type.
2094 QualType ASTContext::getPointerType(QualType T) const {
2095 // Unique pointers, to guarantee there is only one pointer of a particular
2097 llvm::FoldingSetNodeID ID;
2098 PointerType::Profile(ID, T);
2100 void *InsertPos = 0;
2101 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2102 return QualType(PT, 0);
2104 // If the pointee type isn't canonical, this won't be a canonical type either,
2105 // so fill in the canonical type field.
2107 if (!T.isCanonical()) {
2108 Canonical = getPointerType(getCanonicalType(T));
2110 // Get the new insert position for the node we care about.
2111 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2112 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2114 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2115 Types.push_back(New);
2116 PointerTypes.InsertNode(New, InsertPos);
2117 return QualType(New, 0);
2120 /// getBlockPointerType - Return the uniqued reference to the type for
2121 /// a pointer to the specified block.
2122 QualType ASTContext::getBlockPointerType(QualType T) const {
2123 assert(T->isFunctionType() && "block of function types only");
2124 // Unique pointers, to guarantee there is only one block of a particular
2126 llvm::FoldingSetNodeID ID;
2127 BlockPointerType::Profile(ID, T);
2129 void *InsertPos = 0;
2130 if (BlockPointerType *PT =
2131 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2132 return QualType(PT, 0);
2134 // If the block pointee type isn't canonical, this won't be a canonical
2135 // type either so fill in the canonical type field.
2137 if (!T.isCanonical()) {
2138 Canonical = getBlockPointerType(getCanonicalType(T));
2140 // Get the new insert position for the node we care about.
2141 BlockPointerType *NewIP =
2142 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2143 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2145 BlockPointerType *New
2146 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2147 Types.push_back(New);
2148 BlockPointerTypes.InsertNode(New, InsertPos);
2149 return QualType(New, 0);
2152 /// getLValueReferenceType - Return the uniqued reference to the type for an
2153 /// lvalue reference to the specified type.
2155 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2156 assert(getCanonicalType(T) != OverloadTy &&
2157 "Unresolved overloaded function type");
2159 // Unique pointers, to guarantee there is only one pointer of a particular
2161 llvm::FoldingSetNodeID ID;
2162 ReferenceType::Profile(ID, T, SpelledAsLValue);
2164 void *InsertPos = 0;
2165 if (LValueReferenceType *RT =
2166 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2167 return QualType(RT, 0);
2169 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2171 // If the referencee type isn't canonical, this won't be a canonical type
2172 // either, so fill in the canonical type field.
2174 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2175 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2176 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2178 // Get the new insert position for the node we care about.
2179 LValueReferenceType *NewIP =
2180 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2184 LValueReferenceType *New
2185 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2187 Types.push_back(New);
2188 LValueReferenceTypes.InsertNode(New, InsertPos);
2190 return QualType(New, 0);
2193 /// getRValueReferenceType - Return the uniqued reference to the type for an
2194 /// rvalue reference to the specified type.
2195 QualType ASTContext::getRValueReferenceType(QualType T) const {
2196 // Unique pointers, to guarantee there is only one pointer of a particular
2198 llvm::FoldingSetNodeID ID;
2199 ReferenceType::Profile(ID, T, false);
2201 void *InsertPos = 0;
2202 if (RValueReferenceType *RT =
2203 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2204 return QualType(RT, 0);
2206 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2208 // If the referencee type isn't canonical, this won't be a canonical type
2209 // either, so fill in the canonical type field.
2211 if (InnerRef || !T.isCanonical()) {
2212 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2213 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2215 // Get the new insert position for the node we care about.
2216 RValueReferenceType *NewIP =
2217 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2218 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2221 RValueReferenceType *New
2222 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2223 Types.push_back(New);
2224 RValueReferenceTypes.InsertNode(New, InsertPos);
2225 return QualType(New, 0);
2228 /// getMemberPointerType - Return the uniqued reference to the type for a
2229 /// member pointer to the specified type, in the specified class.
2230 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2231 // Unique pointers, to guarantee there is only one pointer of a particular
2233 llvm::FoldingSetNodeID ID;
2234 MemberPointerType::Profile(ID, T, Cls);
2236 void *InsertPos = 0;
2237 if (MemberPointerType *PT =
2238 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2239 return QualType(PT, 0);
2241 // If the pointee or class type isn't canonical, this won't be a canonical
2242 // type either, so fill in the canonical type field.
2244 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2245 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2247 // Get the new insert position for the node we care about.
2248 MemberPointerType *NewIP =
2249 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2250 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2252 MemberPointerType *New
2253 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2254 Types.push_back(New);
2255 MemberPointerTypes.InsertNode(New, InsertPos);
2256 return QualType(New, 0);
2259 /// getConstantArrayType - Return the unique reference to the type for an
2260 /// array of the specified element type.
2261 QualType ASTContext::getConstantArrayType(QualType EltTy,
2262 const llvm::APInt &ArySizeIn,
2263 ArrayType::ArraySizeModifier ASM,
2264 unsigned IndexTypeQuals) const {
2265 assert((EltTy->isDependentType() ||
2266 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2267 "Constant array of VLAs is illegal!");
2269 // Convert the array size into a canonical width matching the pointer size for
2271 llvm::APInt ArySize(ArySizeIn);
2273 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2275 llvm::FoldingSetNodeID ID;
2276 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2278 void *InsertPos = 0;
2279 if (ConstantArrayType *ATP =
2280 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2281 return QualType(ATP, 0);
2283 // If the element type isn't canonical or has qualifiers, this won't
2284 // be a canonical type either, so fill in the canonical type field.
2286 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2287 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2288 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2289 ASM, IndexTypeQuals);
2290 Canon = getQualifiedType(Canon, canonSplit.Quals);
2292 // Get the new insert position for the node we care about.
2293 ConstantArrayType *NewIP =
2294 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2295 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2298 ConstantArrayType *New = new(*this,TypeAlignment)
2299 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2300 ConstantArrayTypes.InsertNode(New, InsertPos);
2301 Types.push_back(New);
2302 return QualType(New, 0);
2305 /// getVariableArrayDecayedType - Turns the given type, which may be
2306 /// variably-modified, into the corresponding type with all the known
2307 /// sizes replaced with [*].
2308 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2309 // Vastly most common case.
2310 if (!type->isVariablyModifiedType()) return type;
2314 SplitQualType split = type.getSplitDesugaredType();
2315 const Type *ty = split.Ty;
2316 switch (ty->getTypeClass()) {
2317 #define TYPE(Class, Base)
2318 #define ABSTRACT_TYPE(Class, Base)
2319 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2320 #include "clang/AST/TypeNodes.def"
2321 llvm_unreachable("didn't desugar past all non-canonical types?");
2323 // These types should never be variably-modified.
2327 case Type::ExtVector:
2328 case Type::DependentSizedExtVector:
2329 case Type::ObjCObject:
2330 case Type::ObjCInterface:
2331 case Type::ObjCObjectPointer:
2334 case Type::UnresolvedUsing:
2335 case Type::TypeOfExpr:
2337 case Type::Decltype:
2338 case Type::UnaryTransform:
2339 case Type::DependentName:
2340 case Type::InjectedClassName:
2341 case Type::TemplateSpecialization:
2342 case Type::DependentTemplateSpecialization:
2343 case Type::TemplateTypeParm:
2344 case Type::SubstTemplateTypeParmPack:
2346 case Type::PackExpansion:
2347 llvm_unreachable("type should never be variably-modified");
2349 // These types can be variably-modified but should never need to
2351 case Type::FunctionNoProto:
2352 case Type::FunctionProto:
2353 case Type::BlockPointer:
2354 case Type::MemberPointer:
2357 // These types can be variably-modified. All these modifications
2358 // preserve structure except as noted by comments.
2359 // TODO: if we ever care about optimizing VLAs, there are no-op
2360 // optimizations available here.
2362 result = getPointerType(getVariableArrayDecayedType(
2363 cast<PointerType>(ty)->getPointeeType()));
2366 case Type::LValueReference: {
2367 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2368 result = getLValueReferenceType(
2369 getVariableArrayDecayedType(lv->getPointeeType()),
2370 lv->isSpelledAsLValue());
2374 case Type::RValueReference: {
2375 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2376 result = getRValueReferenceType(
2377 getVariableArrayDecayedType(lv->getPointeeType()));
2381 case Type::Atomic: {
2382 const AtomicType *at = cast<AtomicType>(ty);
2383 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2387 case Type::ConstantArray: {
2388 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2389 result = getConstantArrayType(
2390 getVariableArrayDecayedType(cat->getElementType()),
2392 cat->getSizeModifier(),
2393 cat->getIndexTypeCVRQualifiers());
2397 case Type::DependentSizedArray: {
2398 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2399 result = getDependentSizedArrayType(
2400 getVariableArrayDecayedType(dat->getElementType()),
2402 dat->getSizeModifier(),
2403 dat->getIndexTypeCVRQualifiers(),
2404 dat->getBracketsRange());
2408 // Turn incomplete types into [*] types.
2409 case Type::IncompleteArray: {
2410 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2411 result = getVariableArrayType(
2412 getVariableArrayDecayedType(iat->getElementType()),
2415 iat->getIndexTypeCVRQualifiers(),
2420 // Turn VLA types into [*] types.
2421 case Type::VariableArray: {
2422 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2423 result = getVariableArrayType(
2424 getVariableArrayDecayedType(vat->getElementType()),
2427 vat->getIndexTypeCVRQualifiers(),
2428 vat->getBracketsRange());
2433 // Apply the top-level qualifiers from the original.
2434 return getQualifiedType(result, split.Quals);
2437 /// getVariableArrayType - Returns a non-unique reference to the type for a
2438 /// variable array of the specified element type.
2439 QualType ASTContext::getVariableArrayType(QualType EltTy,
2441 ArrayType::ArraySizeModifier ASM,
2442 unsigned IndexTypeQuals,
2443 SourceRange Brackets) const {
2444 // Since we don't unique expressions, it isn't possible to unique VLA's
2445 // that have an expression provided for their size.
2448 // Be sure to pull qualifiers off the element type.
2449 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2450 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2451 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2452 IndexTypeQuals, Brackets);
2453 Canon = getQualifiedType(Canon, canonSplit.Quals);
2456 VariableArrayType *New = new(*this, TypeAlignment)
2457 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2459 VariableArrayTypes.push_back(New);
2460 Types.push_back(New);
2461 return QualType(New, 0);
2464 /// getDependentSizedArrayType - Returns a non-unique reference to
2465 /// the type for a dependently-sized array of the specified element
2467 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2469 ArrayType::ArraySizeModifier ASM,
2470 unsigned elementTypeQuals,
2471 SourceRange brackets) const {
2472 assert((!numElements || numElements->isTypeDependent() ||
2473 numElements->isValueDependent()) &&
2474 "Size must be type- or value-dependent!");
2476 // Dependently-sized array types that do not have a specified number
2477 // of elements will have their sizes deduced from a dependent
2478 // initializer. We do no canonicalization here at all, which is okay
2479 // because they can't be used in most locations.
2481 DependentSizedArrayType *newType
2482 = new (*this, TypeAlignment)
2483 DependentSizedArrayType(*this, elementType, QualType(),
2484 numElements, ASM, elementTypeQuals,
2486 Types.push_back(newType);
2487 return QualType(newType, 0);
2490 // Otherwise, we actually build a new type every time, but we
2491 // also build a canonical type.
2493 SplitQualType canonElementType = getCanonicalType(elementType).split();
2495 void *insertPos = 0;
2496 llvm::FoldingSetNodeID ID;
2497 DependentSizedArrayType::Profile(ID, *this,
2498 QualType(canonElementType.Ty, 0),
2499 ASM, elementTypeQuals, numElements);
2501 // Look for an existing type with these properties.
2502 DependentSizedArrayType *canonTy =
2503 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2505 // If we don't have one, build one.
2507 canonTy = new (*this, TypeAlignment)
2508 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2509 QualType(), numElements, ASM, elementTypeQuals,
2511 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2512 Types.push_back(canonTy);
2515 // Apply qualifiers from the element type to the array.
2516 QualType canon = getQualifiedType(QualType(canonTy,0),
2517 canonElementType.Quals);
2519 // If we didn't need extra canonicalization for the element type,
2520 // then just use that as our result.
2521 if (QualType(canonElementType.Ty, 0) == elementType)
2524 // Otherwise, we need to build a type which follows the spelling
2525 // of the element type.
2526 DependentSizedArrayType *sugaredType
2527 = new (*this, TypeAlignment)
2528 DependentSizedArrayType(*this, elementType, canon, numElements,
2529 ASM, elementTypeQuals, brackets);
2530 Types.push_back(sugaredType);
2531 return QualType(sugaredType, 0);
2534 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2535 ArrayType::ArraySizeModifier ASM,
2536 unsigned elementTypeQuals) const {
2537 llvm::FoldingSetNodeID ID;
2538 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2540 void *insertPos = 0;
2541 if (IncompleteArrayType *iat =
2542 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2543 return QualType(iat, 0);
2545 // If the element type isn't canonical, this won't be a canonical type
2546 // either, so fill in the canonical type field. We also have to pull
2547 // qualifiers off the element type.
2550 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2551 SplitQualType canonSplit = getCanonicalType(elementType).split();
2552 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2553 ASM, elementTypeQuals);
2554 canon = getQualifiedType(canon, canonSplit.Quals);
2556 // Get the new insert position for the node we care about.
2557 IncompleteArrayType *existing =
2558 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2559 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2562 IncompleteArrayType *newType = new (*this, TypeAlignment)
2563 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2565 IncompleteArrayTypes.InsertNode(newType, insertPos);
2566 Types.push_back(newType);
2567 return QualType(newType, 0);
2570 /// getVectorType - Return the unique reference to a vector type of
2571 /// the specified element type and size. VectorType must be a built-in type.
2572 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2573 VectorType::VectorKind VecKind) const {
2574 assert(vecType->isBuiltinType());
2576 // Check if we've already instantiated a vector of this type.
2577 llvm::FoldingSetNodeID ID;
2578 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2580 void *InsertPos = 0;
2581 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2582 return QualType(VTP, 0);
2584 // If the element type isn't canonical, this won't be a canonical type either,
2585 // so fill in the canonical type field.
2587 if (!vecType.isCanonical()) {
2588 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2590 // Get the new insert position for the node we care about.
2591 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2592 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2594 VectorType *New = new (*this, TypeAlignment)
2595 VectorType(vecType, NumElts, Canonical, VecKind);
2596 VectorTypes.InsertNode(New, InsertPos);
2597 Types.push_back(New);
2598 return QualType(New, 0);
2601 /// getExtVectorType - Return the unique reference to an extended vector type of
2602 /// the specified element type and size. VectorType must be a built-in type.
2604 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2605 assert(vecType->isBuiltinType() || vecType->isDependentType());
2607 // Check if we've already instantiated a vector of this type.
2608 llvm::FoldingSetNodeID ID;
2609 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2610 VectorType::GenericVector);
2611 void *InsertPos = 0;
2612 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2613 return QualType(VTP, 0);
2615 // If the element type isn't canonical, this won't be a canonical type either,
2616 // so fill in the canonical type field.
2618 if (!vecType.isCanonical()) {
2619 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2621 // Get the new insert position for the node we care about.
2622 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2623 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2625 ExtVectorType *New = new (*this, TypeAlignment)
2626 ExtVectorType(vecType, NumElts, Canonical);
2627 VectorTypes.InsertNode(New, InsertPos);
2628 Types.push_back(New);
2629 return QualType(New, 0);
2633 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2635 SourceLocation AttrLoc) const {
2636 llvm::FoldingSetNodeID ID;
2637 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2640 void *InsertPos = 0;
2641 DependentSizedExtVectorType *Canon
2642 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 DependentSizedExtVectorType *New;
2645 // We already have a canonical version of this array type; use it as
2646 // the canonical type for a newly-built type.
2647 New = new (*this, TypeAlignment)
2648 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2651 QualType CanonVecTy = getCanonicalType(vecType);
2652 if (CanonVecTy == vecType) {
2653 New = new (*this, TypeAlignment)
2654 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2657 DependentSizedExtVectorType *CanonCheck
2658 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2659 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2661 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2663 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2665 New = new (*this, TypeAlignment)
2666 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2670 Types.push_back(New);
2671 return QualType(New, 0);
2674 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2677 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2678 const FunctionType::ExtInfo &Info) const {
2679 const CallingConv DefaultCC = Info.getCC();
2680 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2681 CC_X86StdCall : DefaultCC;
2682 // Unique functions, to guarantee there is only one function of a particular
2684 llvm::FoldingSetNodeID ID;
2685 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2687 void *InsertPos = 0;
2688 if (FunctionNoProtoType *FT =
2689 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2690 return QualType(FT, 0);
2693 if (!ResultTy.isCanonical() ||
2694 getCanonicalCallConv(CallConv) != CallConv) {
2696 getFunctionNoProtoType(getCanonicalType(ResultTy),
2697 Info.withCallingConv(getCanonicalCallConv(CallConv)));
2699 // Get the new insert position for the node we care about.
2700 FunctionNoProtoType *NewIP =
2701 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2705 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2706 FunctionNoProtoType *New = new (*this, TypeAlignment)
2707 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2708 Types.push_back(New);
2709 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2710 return QualType(New, 0);
2713 /// \brief Determine whether \p T is canonical as the result type of a function.
2714 static bool isCanonicalResultType(QualType T) {
2715 return T.isCanonical() &&
2716 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2717 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2720 /// getFunctionType - Return a normal function type with a typed argument
2721 /// list. isVariadic indicates whether the argument list includes '...'.
2723 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2724 const FunctionProtoType::ExtProtoInfo &EPI) const {
2725 size_t NumArgs = ArgArray.size();
2727 // Unique functions, to guarantee there is only one function of a particular
2729 llvm::FoldingSetNodeID ID;
2730 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2733 void *InsertPos = 0;
2734 if (FunctionProtoType *FTP =
2735 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2736 return QualType(FTP, 0);
2738 // Determine whether the type being created is already canonical or not.
2740 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2741 !EPI.HasTrailingReturn;
2742 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2743 if (!ArgArray[i].isCanonicalAsParam())
2744 isCanonical = false;
2746 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2747 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2748 CC_X86StdCall : DefaultCC;
2750 // If this type isn't canonical, get the canonical version of it.
2751 // The exception spec is not part of the canonical type.
2753 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2754 SmallVector<QualType, 16> CanonicalArgs;
2755 CanonicalArgs.reserve(NumArgs);
2756 for (unsigned i = 0; i != NumArgs; ++i)
2757 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2759 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2760 CanonicalEPI.HasTrailingReturn = false;
2761 CanonicalEPI.ExceptionSpecType = EST_None;
2762 CanonicalEPI.NumExceptions = 0;
2763 CanonicalEPI.ExtInfo
2764 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2766 // Result types do not have ARC lifetime qualifiers.
2767 QualType CanResultTy = getCanonicalType(ResultTy);
2768 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2769 Qualifiers Qs = CanResultTy.getQualifiers();
2770 Qs.removeObjCLifetime();
2771 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2774 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2776 // Get the new insert position for the node we care about.
2777 FunctionProtoType *NewIP =
2778 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2782 // FunctionProtoType objects are allocated with extra bytes after
2783 // them for three variable size arrays at the end:
2784 // - parameter types
2785 // - exception types
2786 // - consumed-arguments flags
2787 // Instead of the exception types, there could be a noexcept
2788 // expression, or information used to resolve the exception
2790 size_t Size = sizeof(FunctionProtoType) +
2791 NumArgs * sizeof(QualType);
2792 if (EPI.ExceptionSpecType == EST_Dynamic) {
2793 Size += EPI.NumExceptions * sizeof(QualType);
2794 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2795 Size += sizeof(Expr*);
2796 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2797 Size += 2 * sizeof(FunctionDecl*);
2798 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2799 Size += sizeof(FunctionDecl*);
2801 if (EPI.ConsumedArguments)
2802 Size += NumArgs * sizeof(bool);
2804 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2805 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2806 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2807 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2808 Types.push_back(FTP);
2809 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2810 return QualType(FTP, 0);
2814 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2815 if (!isa<CXXRecordDecl>(D)) return false;
2816 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2817 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2819 if (RD->getDescribedClassTemplate() &&
2820 !isa<ClassTemplateSpecializationDecl>(RD))
2826 /// getInjectedClassNameType - Return the unique reference to the
2827 /// injected class name type for the specified templated declaration.
2828 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2829 QualType TST) const {
2830 assert(NeedsInjectedClassNameType(Decl));
2831 if (Decl->TypeForDecl) {
2832 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2833 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2834 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2835 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2836 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2839 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2840 Decl->TypeForDecl = newType;
2841 Types.push_back(newType);
2843 return QualType(Decl->TypeForDecl, 0);
2846 /// getTypeDeclType - Return the unique reference to the type for the
2847 /// specified type declaration.
2848 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2849 assert(Decl && "Passed null for Decl param");
2850 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2852 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2853 return getTypedefType(Typedef);
2855 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2856 "Template type parameter types are always available.");
2858 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2859 assert(!Record->getPreviousDecl() &&
2860 "struct/union has previous declaration");
2861 assert(!NeedsInjectedClassNameType(Record));
2862 return getRecordType(Record);
2863 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2864 assert(!Enum->getPreviousDecl() &&
2865 "enum has previous declaration");
2866 return getEnumType(Enum);
2867 } else if (const UnresolvedUsingTypenameDecl *Using =
2868 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2869 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2870 Decl->TypeForDecl = newType;
2871 Types.push_back(newType);
2873 llvm_unreachable("TypeDecl without a type?");
2875 return QualType(Decl->TypeForDecl, 0);
2878 /// getTypedefType - Return the unique reference to the type for the
2879 /// specified typedef name decl.
2881 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2882 QualType Canonical) const {
2883 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2885 if (Canonical.isNull())
2886 Canonical = getCanonicalType(Decl->getUnderlyingType());
2887 TypedefType *newType = new(*this, TypeAlignment)
2888 TypedefType(Type::Typedef, Decl, Canonical);
2889 Decl->TypeForDecl = newType;
2890 Types.push_back(newType);
2891 return QualType(newType, 0);
2894 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2897 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2898 if (PrevDecl->TypeForDecl)
2899 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2901 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2902 Decl->TypeForDecl = newType;
2903 Types.push_back(newType);
2904 return QualType(newType, 0);
2907 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2908 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2910 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2911 if (PrevDecl->TypeForDecl)
2912 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2914 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2915 Decl->TypeForDecl = newType;
2916 Types.push_back(newType);
2917 return QualType(newType, 0);
2920 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2921 QualType modifiedType,
2922 QualType equivalentType) {
2923 llvm::FoldingSetNodeID id;
2924 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2926 void *insertPos = 0;
2927 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2928 if (type) return QualType(type, 0);
2930 QualType canon = getCanonicalType(equivalentType);
2931 type = new (*this, TypeAlignment)
2932 AttributedType(canon, attrKind, modifiedType, equivalentType);
2934 Types.push_back(type);
2935 AttributedTypes.InsertNode(type, insertPos);
2937 return QualType(type, 0);
2941 /// \brief Retrieve a substitution-result type.
2943 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2944 QualType Replacement) const {
2945 assert(Replacement.isCanonical()
2946 && "replacement types must always be canonical");
2948 llvm::FoldingSetNodeID ID;
2949 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2950 void *InsertPos = 0;
2951 SubstTemplateTypeParmType *SubstParm
2952 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2955 SubstParm = new (*this, TypeAlignment)
2956 SubstTemplateTypeParmType(Parm, Replacement);
2957 Types.push_back(SubstParm);
2958 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2961 return QualType(SubstParm, 0);
2964 /// \brief Retrieve a
2965 QualType ASTContext::getSubstTemplateTypeParmPackType(
2966 const TemplateTypeParmType *Parm,
2967 const TemplateArgument &ArgPack) {
2969 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2970 PEnd = ArgPack.pack_end();
2972 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2973 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2977 llvm::FoldingSetNodeID ID;
2978 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2979 void *InsertPos = 0;
2980 if (SubstTemplateTypeParmPackType *SubstParm
2981 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2982 return QualType(SubstParm, 0);
2985 if (!Parm->isCanonicalUnqualified()) {
2986 Canon = getCanonicalType(QualType(Parm, 0));
2987 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2989 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2992 SubstTemplateTypeParmPackType *SubstParm
2993 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2995 Types.push_back(SubstParm);
2996 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2997 return QualType(SubstParm, 0);
3000 /// \brief Retrieve the template type parameter type for a template
3001 /// parameter or parameter pack with the given depth, index, and (optionally)
3003 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3005 TemplateTypeParmDecl *TTPDecl) const {
3006 llvm::FoldingSetNodeID ID;
3007 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3008 void *InsertPos = 0;
3009 TemplateTypeParmType *TypeParm
3010 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3013 return QualType(TypeParm, 0);
3016 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3017 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3019 TemplateTypeParmType *TypeCheck
3020 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3021 assert(!TypeCheck && "Template type parameter canonical type broken");
3024 TypeParm = new (*this, TypeAlignment)
3025 TemplateTypeParmType(Depth, Index, ParameterPack);
3027 Types.push_back(TypeParm);
3028 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3030 return QualType(TypeParm, 0);
3034 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3035 SourceLocation NameLoc,
3036 const TemplateArgumentListInfo &Args,
3037 QualType Underlying) const {
3038 assert(!Name.getAsDependentTemplateName() &&
3039 "No dependent template names here!");
3040 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3042 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3043 TemplateSpecializationTypeLoc TL =
3044 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3045 TL.setTemplateKeywordLoc(SourceLocation());
3046 TL.setTemplateNameLoc(NameLoc);
3047 TL.setLAngleLoc(Args.getLAngleLoc());
3048 TL.setRAngleLoc(Args.getRAngleLoc());
3049 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3050 TL.setArgLocInfo(i, Args[i].getLocInfo());
3055 ASTContext::getTemplateSpecializationType(TemplateName Template,
3056 const TemplateArgumentListInfo &Args,
3057 QualType Underlying) const {
3058 assert(!Template.getAsDependentTemplateName() &&
3059 "No dependent template names here!");
3061 unsigned NumArgs = Args.size();
3063 SmallVector<TemplateArgument, 4> ArgVec;
3064 ArgVec.reserve(NumArgs);
3065 for (unsigned i = 0; i != NumArgs; ++i)
3066 ArgVec.push_back(Args[i].getArgument());
3068 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3073 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3075 for (unsigned I = 0; I != NumArgs; ++I)
3076 if (Args[I].isPackExpansion())
3084 ASTContext::getTemplateSpecializationType(TemplateName Template,
3085 const TemplateArgument *Args,
3087 QualType Underlying) const {
3088 assert(!Template.getAsDependentTemplateName() &&
3089 "No dependent template names here!");
3090 // Look through qualified template names.
3091 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3092 Template = TemplateName(QTN->getTemplateDecl());
3095 Template.getAsTemplateDecl() &&
3096 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3098 if (!Underlying.isNull())
3099 CanonType = getCanonicalType(Underlying);
3101 // We can get here with an alias template when the specialization contains
3102 // a pack expansion that does not match up with a parameter pack.
3103 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3104 "Caller must compute aliased type");
3105 IsTypeAlias = false;
3106 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3110 // Allocate the (non-canonical) template specialization type, but don't
3111 // try to unique it: these types typically have location information that
3112 // we don't unique and don't want to lose.
3113 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3114 sizeof(TemplateArgument) * NumArgs +
3115 (IsTypeAlias? sizeof(QualType) : 0),
3117 TemplateSpecializationType *Spec
3118 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3119 IsTypeAlias ? Underlying : QualType());
3121 Types.push_back(Spec);
3122 return QualType(Spec, 0);
3126 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3127 const TemplateArgument *Args,
3128 unsigned NumArgs) const {
3129 assert(!Template.getAsDependentTemplateName() &&
3130 "No dependent template names here!");
3132 // Look through qualified template names.
3133 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3134 Template = TemplateName(QTN->getTemplateDecl());
3136 // Build the canonical template specialization type.
3137 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3138 SmallVector<TemplateArgument, 4> CanonArgs;
3139 CanonArgs.reserve(NumArgs);
3140 for (unsigned I = 0; I != NumArgs; ++I)
3141 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3143 // Determine whether this canonical template specialization type already
3145 llvm::FoldingSetNodeID ID;
3146 TemplateSpecializationType::Profile(ID, CanonTemplate,
3147 CanonArgs.data(), NumArgs, *this);
3149 void *InsertPos = 0;
3150 TemplateSpecializationType *Spec
3151 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3154 // Allocate a new canonical template specialization type.
3155 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3156 sizeof(TemplateArgument) * NumArgs),
3158 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3159 CanonArgs.data(), NumArgs,
3160 QualType(), QualType());
3161 Types.push_back(Spec);
3162 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3165 assert(Spec->isDependentType() &&
3166 "Non-dependent template-id type must have a canonical type");
3167 return QualType(Spec, 0);
3171 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3172 NestedNameSpecifier *NNS,
3173 QualType NamedType) const {
3174 llvm::FoldingSetNodeID ID;
3175 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3177 void *InsertPos = 0;
3178 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3180 return QualType(T, 0);
3182 QualType Canon = NamedType;
3183 if (!Canon.isCanonical()) {
3184 Canon = getCanonicalType(NamedType);
3185 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3186 assert(!CheckT && "Elaborated canonical type broken");
3190 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3192 ElaboratedTypes.InsertNode(T, InsertPos);
3193 return QualType(T, 0);
3197 ASTContext::getParenType(QualType InnerType) const {
3198 llvm::FoldingSetNodeID ID;
3199 ParenType::Profile(ID, InnerType);
3201 void *InsertPos = 0;
3202 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3204 return QualType(T, 0);
3206 QualType Canon = InnerType;
3207 if (!Canon.isCanonical()) {
3208 Canon = getCanonicalType(InnerType);
3209 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3210 assert(!CheckT && "Paren canonical type broken");
3214 T = new (*this) ParenType(InnerType, Canon);
3216 ParenTypes.InsertNode(T, InsertPos);
3217 return QualType(T, 0);
3220 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3221 NestedNameSpecifier *NNS,
3222 const IdentifierInfo *Name,
3223 QualType Canon) const {
3224 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3226 if (Canon.isNull()) {
3227 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3228 ElaboratedTypeKeyword CanonKeyword = Keyword;
3229 if (Keyword == ETK_None)
3230 CanonKeyword = ETK_Typename;
3232 if (CanonNNS != NNS || CanonKeyword != Keyword)
3233 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3236 llvm::FoldingSetNodeID ID;
3237 DependentNameType::Profile(ID, Keyword, NNS, Name);
3239 void *InsertPos = 0;
3240 DependentNameType *T
3241 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3243 return QualType(T, 0);
3245 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3247 DependentNameTypes.InsertNode(T, InsertPos);
3248 return QualType(T, 0);
3252 ASTContext::getDependentTemplateSpecializationType(
3253 ElaboratedTypeKeyword Keyword,
3254 NestedNameSpecifier *NNS,
3255 const IdentifierInfo *Name,
3256 const TemplateArgumentListInfo &Args) const {
3257 // TODO: avoid this copy
3258 SmallVector<TemplateArgument, 16> ArgCopy;
3259 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3260 ArgCopy.push_back(Args[I].getArgument());
3261 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3267 ASTContext::getDependentTemplateSpecializationType(
3268 ElaboratedTypeKeyword Keyword,
3269 NestedNameSpecifier *NNS,
3270 const IdentifierInfo *Name,
3272 const TemplateArgument *Args) const {
3273 assert((!NNS || NNS->isDependent()) &&
3274 "nested-name-specifier must be dependent");
3276 llvm::FoldingSetNodeID ID;
3277 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3278 Name, NumArgs, Args);
3280 void *InsertPos = 0;
3281 DependentTemplateSpecializationType *T
3282 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3284 return QualType(T, 0);
3286 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3288 ElaboratedTypeKeyword CanonKeyword = Keyword;
3289 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3291 bool AnyNonCanonArgs = false;
3292 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3293 for (unsigned I = 0; I != NumArgs; ++I) {
3294 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3295 if (!CanonArgs[I].structurallyEquals(Args[I]))
3296 AnyNonCanonArgs = true;
3300 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3301 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3305 // Find the insert position again.
3306 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3309 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3310 sizeof(TemplateArgument) * NumArgs),
3312 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3313 Name, NumArgs, Args, Canon);
3315 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3316 return QualType(T, 0);
3319 QualType ASTContext::getPackExpansionType(QualType Pattern,
3320 Optional<unsigned> NumExpansions) {
3321 llvm::FoldingSetNodeID ID;
3322 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3324 assert(Pattern->containsUnexpandedParameterPack() &&
3325 "Pack expansions must expand one or more parameter packs");
3326 void *InsertPos = 0;
3327 PackExpansionType *T
3328 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3330 return QualType(T, 0);
3333 if (!Pattern.isCanonical()) {
3334 Canon = getCanonicalType(Pattern);
3335 // The canonical type might not contain an unexpanded parameter pack, if it
3336 // contains an alias template specialization which ignores one of its
3338 if (Canon->containsUnexpandedParameterPack()) {
3339 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
3341 // Find the insert position again, in case we inserted an element into
3342 // PackExpansionTypes and invalidated our insert position.
3343 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3347 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3349 PackExpansionTypes.InsertNode(T, InsertPos);
3350 return QualType(T, 0);
3353 /// CmpProtocolNames - Comparison predicate for sorting protocols
3355 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3356 const ObjCProtocolDecl *RHS) {
3357 return LHS->getDeclName() < RHS->getDeclName();
3360 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3361 unsigned NumProtocols) {
3362 if (NumProtocols == 0) return true;
3364 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3367 for (unsigned i = 1; i != NumProtocols; ++i)
3368 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3369 Protocols[i]->getCanonicalDecl() != Protocols[i])
3374 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3375 unsigned &NumProtocols) {
3376 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3378 // Sort protocols, keyed by name.
3379 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3382 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3383 Protocols[I] = Protocols[I]->getCanonicalDecl();
3385 // Remove duplicates.
3386 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3387 NumProtocols = ProtocolsEnd-Protocols;
3390 QualType ASTContext::getObjCObjectType(QualType BaseType,
3391 ObjCProtocolDecl * const *Protocols,
3392 unsigned NumProtocols) const {
3393 // If the base type is an interface and there aren't any protocols
3394 // to add, then the interface type will do just fine.
3395 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3398 // Look in the folding set for an existing type.
3399 llvm::FoldingSetNodeID ID;
3400 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3401 void *InsertPos = 0;
3402 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3403 return QualType(QT, 0);
3405 // Build the canonical type, which has the canonical base type and
3406 // a sorted-and-uniqued list of protocols.
3408 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3409 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3410 if (!ProtocolsSorted) {
3411 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3412 Protocols + NumProtocols);
3413 unsigned UniqueCount = NumProtocols;
3415 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3416 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3417 &Sorted[0], UniqueCount);
3419 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3420 Protocols, NumProtocols);
3423 // Regenerate InsertPos.
3424 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3427 unsigned Size = sizeof(ObjCObjectTypeImpl);
3428 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3429 void *Mem = Allocate(Size, TypeAlignment);
3430 ObjCObjectTypeImpl *T =
3431 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3434 ObjCObjectTypes.InsertNode(T, InsertPos);
3435 return QualType(T, 0);
3438 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3439 /// the given object type.
3440 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3441 llvm::FoldingSetNodeID ID;
3442 ObjCObjectPointerType::Profile(ID, ObjectT);
3444 void *InsertPos = 0;
3445 if (ObjCObjectPointerType *QT =
3446 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3447 return QualType(QT, 0);
3449 // Find the canonical object type.
3451 if (!ObjectT.isCanonical()) {
3452 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3454 // Regenerate InsertPos.
3455 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3459 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3460 ObjCObjectPointerType *QType =
3461 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3463 Types.push_back(QType);
3464 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3465 return QualType(QType, 0);
3468 /// getObjCInterfaceType - Return the unique reference to the type for the
3469 /// specified ObjC interface decl. The list of protocols is optional.
3470 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3471 ObjCInterfaceDecl *PrevDecl) const {
3472 if (Decl->TypeForDecl)
3473 return QualType(Decl->TypeForDecl, 0);
3476 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3477 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3478 return QualType(PrevDecl->TypeForDecl, 0);
3481 // Prefer the definition, if there is one.
3482 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3485 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3486 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3487 Decl->TypeForDecl = T;
3489 return QualType(T, 0);
3492 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3493 /// TypeOfExprType AST's (since expression's are never shared). For example,
3494 /// multiple declarations that refer to "typeof(x)" all contain different
3495 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3496 /// on canonical type's (which are always unique).
3497 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3498 TypeOfExprType *toe;
3499 if (tofExpr->isTypeDependent()) {
3500 llvm::FoldingSetNodeID ID;
3501 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3503 void *InsertPos = 0;
3504 DependentTypeOfExprType *Canon
3505 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3507 // We already have a "canonical" version of an identical, dependent
3508 // typeof(expr) type. Use that as our canonical type.
3509 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3510 QualType((TypeOfExprType*)Canon, 0));
3512 // Build a new, canonical typeof(expr) type.
3514 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3515 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3519 QualType Canonical = getCanonicalType(tofExpr->getType());
3520 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3522 Types.push_back(toe);
3523 return QualType(toe, 0);
3526 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3527 /// TypeOfType AST's. The only motivation to unique these nodes would be
3528 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3529 /// an issue. This doesn't effect the type checker, since it operates
3530 /// on canonical type's (which are always unique).
3531 QualType ASTContext::getTypeOfType(QualType tofType) const {
3532 QualType Canonical = getCanonicalType(tofType);
3533 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3534 Types.push_back(tot);
3535 return QualType(tot, 0);
3539 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3540 /// DecltypeType AST's. The only motivation to unique these nodes would be
3541 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3542 /// an issue. This doesn't effect the type checker, since it operates
3543 /// on canonical types (which are always unique).
3544 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3547 // C++0x [temp.type]p2:
3548 // If an expression e involves a template parameter, decltype(e) denotes a
3549 // unique dependent type. Two such decltype-specifiers refer to the same
3550 // type only if their expressions are equivalent (14.5.6.1).
3551 if (e->isInstantiationDependent()) {
3552 llvm::FoldingSetNodeID ID;
3553 DependentDecltypeType::Profile(ID, *this, e);
3555 void *InsertPos = 0;
3556 DependentDecltypeType *Canon
3557 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3559 // We already have a "canonical" version of an equivalent, dependent
3560 // decltype type. Use that as our canonical type.
3561 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3562 QualType((DecltypeType*)Canon, 0));
3564 // Build a new, canonical typeof(expr) type.
3565 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3566 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3570 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3571 getCanonicalType(UnderlyingType));
3573 Types.push_back(dt);
3574 return QualType(dt, 0);
3577 /// getUnaryTransformationType - We don't unique these, since the memory
3578 /// savings are minimal and these are rare.
3579 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3580 QualType UnderlyingType,
3581 UnaryTransformType::UTTKind Kind)
3583 UnaryTransformType *Ty =
3584 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3586 UnderlyingType->isDependentType() ?
3587 QualType() : getCanonicalType(UnderlyingType));
3588 Types.push_back(Ty);
3589 return QualType(Ty, 0);
3592 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3593 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3594 /// canonical deduced-but-dependent 'auto' type.
3595 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3596 bool IsDependent) const {
3597 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3598 return getAutoDeductType();
3600 // Look in the folding set for an existing type.
3601 void *InsertPos = 0;
3602 llvm::FoldingSetNodeID ID;
3603 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3604 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3605 return QualType(AT, 0);
3607 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3610 Types.push_back(AT);
3612 AutoTypes.InsertNode(AT, InsertPos);
3613 return QualType(AT, 0);
3616 /// getAtomicType - Return the uniqued reference to the atomic type for
3617 /// the given value type.
3618 QualType ASTContext::getAtomicType(QualType T) const {
3619 // Unique pointers, to guarantee there is only one pointer of a particular
3621 llvm::FoldingSetNodeID ID;
3622 AtomicType::Profile(ID, T);
3624 void *InsertPos = 0;
3625 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3626 return QualType(AT, 0);
3628 // If the atomic value type isn't canonical, this won't be a canonical type
3629 // either, so fill in the canonical type field.
3631 if (!T.isCanonical()) {
3632 Canonical = getAtomicType(getCanonicalType(T));
3634 // Get the new insert position for the node we care about.
3635 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3636 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3638 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3639 Types.push_back(New);
3640 AtomicTypes.InsertNode(New, InsertPos);
3641 return QualType(New, 0);
3644 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3645 QualType ASTContext::getAutoDeductType() const {
3646 if (AutoDeductTy.isNull())
3647 AutoDeductTy = QualType(
3648 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3649 /*dependent*/false),
3651 return AutoDeductTy;
3654 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3655 QualType ASTContext::getAutoRRefDeductType() const {
3656 if (AutoRRefDeductTy.isNull())
3657 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3658 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3659 return AutoRRefDeductTy;
3662 /// getTagDeclType - Return the unique reference to the type for the
3663 /// specified TagDecl (struct/union/class/enum) decl.
3664 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3666 // FIXME: What is the design on getTagDeclType when it requires casting
3667 // away const? mutable?
3668 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3671 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3672 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3673 /// needs to agree with the definition in <stddef.h>.
3674 CanQualType ASTContext::getSizeType() const {
3675 return getFromTargetType(Target->getSizeType());
3678 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3679 CanQualType ASTContext::getIntMaxType() const {
3680 return getFromTargetType(Target->getIntMaxType());
3683 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3684 CanQualType ASTContext::getUIntMaxType() const {
3685 return getFromTargetType(Target->getUIntMaxType());
3688 /// getSignedWCharType - Return the type of "signed wchar_t".
3689 /// Used when in C++, as a GCC extension.
3690 QualType ASTContext::getSignedWCharType() const {
3691 // FIXME: derive from "Target" ?
3695 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3696 /// Used when in C++, as a GCC extension.
3697 QualType ASTContext::getUnsignedWCharType() const {
3698 // FIXME: derive from "Target" ?
3699 return UnsignedIntTy;
3702 QualType ASTContext::getIntPtrType() const {
3703 return getFromTargetType(Target->getIntPtrType());
3706 QualType ASTContext::getUIntPtrType() const {
3707 return getCorrespondingUnsignedType(getIntPtrType());
3710 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3711 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3712 QualType ASTContext::getPointerDiffType() const {
3713 return getFromTargetType(Target->getPtrDiffType(0));
3716 /// \brief Return the unique type for "pid_t" defined in
3717 /// <sys/types.h>. We need this to compute the correct type for vfork().
3718 QualType ASTContext::getProcessIDType() const {
3719 return getFromTargetType(Target->getProcessIDType());
3722 //===----------------------------------------------------------------------===//
3724 //===----------------------------------------------------------------------===//
3726 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3727 // Push qualifiers into arrays, and then discard any remaining
3729 T = getCanonicalType(T);
3730 T = getVariableArrayDecayedType(T);
3731 const Type *Ty = T.getTypePtr();
3733 if (isa<ArrayType>(Ty)) {
3734 Result = getArrayDecayedType(QualType(Ty,0));
3735 } else if (isa<FunctionType>(Ty)) {
3736 Result = getPointerType(QualType(Ty, 0));
3738 Result = QualType(Ty, 0);
3741 return CanQualType::CreateUnsafe(Result);
3744 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3745 Qualifiers &quals) {
3746 SplitQualType splitType = type.getSplitUnqualifiedType();
3748 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3749 // the unqualified desugared type and then drops it on the floor.
3750 // We then have to strip that sugar back off with
3751 // getUnqualifiedDesugaredType(), which is silly.
3752 const ArrayType *AT =
3753 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3755 // If we don't have an array, just use the results in splitType.
3757 quals = splitType.Quals;
3758 return QualType(splitType.Ty, 0);
3761 // Otherwise, recurse on the array's element type.
3762 QualType elementType = AT->getElementType();
3763 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3765 // If that didn't change the element type, AT has no qualifiers, so we
3766 // can just use the results in splitType.
3767 if (elementType == unqualElementType) {
3768 assert(quals.empty()); // from the recursive call
3769 quals = splitType.Quals;
3770 return QualType(splitType.Ty, 0);
3773 // Otherwise, add in the qualifiers from the outermost type, then
3774 // build the type back up.
3775 quals.addConsistentQualifiers(splitType.Quals);
3777 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3778 return getConstantArrayType(unqualElementType, CAT->getSize(),
3779 CAT->getSizeModifier(), 0);
3782 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3783 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3786 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3787 return getVariableArrayType(unqualElementType,
3789 VAT->getSizeModifier(),
3790 VAT->getIndexTypeCVRQualifiers(),
3791 VAT->getBracketsRange());
3794 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3795 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3796 DSAT->getSizeModifier(), 0,
3800 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3801 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3802 /// they point to and return true. If T1 and T2 aren't pointer types
3803 /// or pointer-to-member types, or if they are not similar at this
3804 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3805 /// qualifiers on T1 and T2 are ignored. This function will typically
3806 /// be called in a loop that successively "unwraps" pointer and
3807 /// pointer-to-member types to compare them at each level.
3808 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3809 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3810 *T2PtrType = T2->getAs<PointerType>();
3811 if (T1PtrType && T2PtrType) {
3812 T1 = T1PtrType->getPointeeType();
3813 T2 = T2PtrType->getPointeeType();
3817 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3818 *T2MPType = T2->getAs<MemberPointerType>();
3819 if (T1MPType && T2MPType &&
3820 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3821 QualType(T2MPType->getClass(), 0))) {
3822 T1 = T1MPType->getPointeeType();
3823 T2 = T2MPType->getPointeeType();
3827 if (getLangOpts().ObjC1) {
3828 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3829 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3830 if (T1OPType && T2OPType) {
3831 T1 = T1OPType->getPointeeType();
3832 T2 = T2OPType->getPointeeType();
3837 // FIXME: Block pointers, too?
3843 ASTContext::getNameForTemplate(TemplateName Name,
3844 SourceLocation NameLoc) const {
3845 switch (Name.getKind()) {
3846 case TemplateName::QualifiedTemplate:
3847 case TemplateName::Template:
3848 // DNInfo work in progress: CHECKME: what about DNLoc?
3849 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3852 case TemplateName::OverloadedTemplate: {
3853 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3854 // DNInfo work in progress: CHECKME: what about DNLoc?
3855 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3858 case TemplateName::DependentTemplate: {
3859 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3860 DeclarationName DName;
3861 if (DTN->isIdentifier()) {
3862 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3863 return DeclarationNameInfo(DName, NameLoc);
3865 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3866 // DNInfo work in progress: FIXME: source locations?
3867 DeclarationNameLoc DNLoc;
3868 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3869 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3870 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3874 case TemplateName::SubstTemplateTemplateParm: {
3875 SubstTemplateTemplateParmStorage *subst
3876 = Name.getAsSubstTemplateTemplateParm();
3877 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3881 case TemplateName::SubstTemplateTemplateParmPack: {
3882 SubstTemplateTemplateParmPackStorage *subst
3883 = Name.getAsSubstTemplateTemplateParmPack();
3884 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3889 llvm_unreachable("bad template name kind!");
3892 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3893 switch (Name.getKind()) {
3894 case TemplateName::QualifiedTemplate:
3895 case TemplateName::Template: {
3896 TemplateDecl *Template = Name.getAsTemplateDecl();
3897 if (TemplateTemplateParmDecl *TTP
3898 = dyn_cast<TemplateTemplateParmDecl>(Template))
3899 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3901 // The canonical template name is the canonical template declaration.
3902 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3905 case TemplateName::OverloadedTemplate:
3906 llvm_unreachable("cannot canonicalize overloaded template");
3908 case TemplateName::DependentTemplate: {
3909 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3910 assert(DTN && "Non-dependent template names must refer to template decls.");
3911 return DTN->CanonicalTemplateName;
3914 case TemplateName::SubstTemplateTemplateParm: {
3915 SubstTemplateTemplateParmStorage *subst
3916 = Name.getAsSubstTemplateTemplateParm();
3917 return getCanonicalTemplateName(subst->getReplacement());
3920 case TemplateName::SubstTemplateTemplateParmPack: {
3921 SubstTemplateTemplateParmPackStorage *subst
3922 = Name.getAsSubstTemplateTemplateParmPack();
3923 TemplateTemplateParmDecl *canonParameter
3924 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3925 TemplateArgument canonArgPack
3926 = getCanonicalTemplateArgument(subst->getArgumentPack());
3927 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3931 llvm_unreachable("bad template name!");
3934 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3935 X = getCanonicalTemplateName(X);
3936 Y = getCanonicalTemplateName(Y);
3937 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3941 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3942 switch (Arg.getKind()) {
3943 case TemplateArgument::Null:
3946 case TemplateArgument::Expression:
3949 case TemplateArgument::Declaration: {
3950 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3951 return TemplateArgument(D, Arg.isDeclForReferenceParam());
3954 case TemplateArgument::NullPtr:
3955 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3958 case TemplateArgument::Template:
3959 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3961 case TemplateArgument::TemplateExpansion:
3962 return TemplateArgument(getCanonicalTemplateName(
3963 Arg.getAsTemplateOrTemplatePattern()),
3964 Arg.getNumTemplateExpansions());
3966 case TemplateArgument::Integral:
3967 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
3969 case TemplateArgument::Type:
3970 return TemplateArgument(getCanonicalType(Arg.getAsType()));
3972 case TemplateArgument::Pack: {
3973 if (Arg.pack_size() == 0)
3976 TemplateArgument *CanonArgs
3977 = new (*this) TemplateArgument[Arg.pack_size()];
3979 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3980 AEnd = Arg.pack_end();
3981 A != AEnd; (void)++A, ++Idx)
3982 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3984 return TemplateArgument(CanonArgs, Arg.pack_size());
3988 // Silence GCC warning
3989 llvm_unreachable("Unhandled template argument kind");
3992 NestedNameSpecifier *
3993 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3997 switch (NNS->getKind()) {
3998 case NestedNameSpecifier::Identifier:
3999 // Canonicalize the prefix but keep the identifier the same.
4000 return NestedNameSpecifier::Create(*this,
4001 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4002 NNS->getAsIdentifier());
4004 case NestedNameSpecifier::Namespace:
4005 // A namespace is canonical; build a nested-name-specifier with
4006 // this namespace and no prefix.
4007 return NestedNameSpecifier::Create(*this, 0,
4008 NNS->getAsNamespace()->getOriginalNamespace());
4010 case NestedNameSpecifier::NamespaceAlias:
4011 // A namespace is canonical; build a nested-name-specifier with
4012 // this namespace and no prefix.
4013 return NestedNameSpecifier::Create(*this, 0,
4014 NNS->getAsNamespaceAlias()->getNamespace()
4015 ->getOriginalNamespace());
4017 case NestedNameSpecifier::TypeSpec:
4018 case NestedNameSpecifier::TypeSpecWithTemplate: {
4019 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4021 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4022 // break it apart into its prefix and identifier, then reconsititute those
4023 // as the canonical nested-name-specifier. This is required to canonicalize
4024 // a dependent nested-name-specifier involving typedefs of dependent-name
4026 // typedef typename T::type T1;
4027 // typedef typename T1::type T2;
4028 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4029 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4030 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4032 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4033 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4035 return NestedNameSpecifier::Create(*this, 0, false,
4036 const_cast<Type*>(T.getTypePtr()));
4039 case NestedNameSpecifier::Global:
4040 // The global specifier is canonical and unique.
4044 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4048 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4049 // Handle the non-qualified case efficiently.
4050 if (!T.hasLocalQualifiers()) {
4051 // Handle the common positive case fast.
4052 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4056 // Handle the common negative case fast.
4057 if (!isa<ArrayType>(T.getCanonicalType()))
4060 // Apply any qualifiers from the array type to the element type. This
4061 // implements C99 6.7.3p8: "If the specification of an array type includes
4062 // any type qualifiers, the element type is so qualified, not the array type."
4064 // If we get here, we either have type qualifiers on the type, or we have
4065 // sugar such as a typedef in the way. If we have type qualifiers on the type
4066 // we must propagate them down into the element type.
4068 SplitQualType split = T.getSplitDesugaredType();
4069 Qualifiers qs = split.Quals;
4071 // If we have a simple case, just return now.
4072 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4073 if (ATy == 0 || qs.empty())
4076 // Otherwise, we have an array and we have qualifiers on it. Push the
4077 // qualifiers into the array element type and return a new array type.
4078 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4080 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4081 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4082 CAT->getSizeModifier(),
4083 CAT->getIndexTypeCVRQualifiers()));
4084 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4085 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4086 IAT->getSizeModifier(),
4087 IAT->getIndexTypeCVRQualifiers()));
4089 if (const DependentSizedArrayType *DSAT
4090 = dyn_cast<DependentSizedArrayType>(ATy))
4091 return cast<ArrayType>(
4092 getDependentSizedArrayType(NewEltTy,
4093 DSAT->getSizeExpr(),
4094 DSAT->getSizeModifier(),
4095 DSAT->getIndexTypeCVRQualifiers(),
4096 DSAT->getBracketsRange()));
4098 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4099 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4101 VAT->getSizeModifier(),
4102 VAT->getIndexTypeCVRQualifiers(),
4103 VAT->getBracketsRange()));
4106 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4108 // A declaration of a parameter as "array of type" shall be
4109 // adjusted to "qualified pointer to type", where the type
4110 // qualifiers (if any) are those specified within the [ and ] of
4111 // the array type derivation.
4112 if (T->isArrayType())
4113 return getArrayDecayedType(T);
4116 // A declaration of a parameter as "function returning type"
4117 // shall be adjusted to "pointer to function returning type", as
4119 if (T->isFunctionType())
4120 return getPointerType(T);
4125 QualType ASTContext::getSignatureParameterType(QualType T) const {
4126 T = getVariableArrayDecayedType(T);
4127 T = getAdjustedParameterType(T);
4128 return T.getUnqualifiedType();
4131 /// getArrayDecayedType - Return the properly qualified result of decaying the
4132 /// specified array type to a pointer. This operation is non-trivial when
4133 /// handling typedefs etc. The canonical type of "T" must be an array type,
4134 /// this returns a pointer to a properly qualified element of the array.
4136 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4137 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4138 // Get the element type with 'getAsArrayType' so that we don't lose any
4139 // typedefs in the element type of the array. This also handles propagation
4140 // of type qualifiers from the array type into the element type if present
4142 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4143 assert(PrettyArrayType && "Not an array type!");
4145 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4147 // int x[restrict 4] -> int *restrict
4148 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4151 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4152 return getBaseElementType(array->getElementType());
4155 QualType ASTContext::getBaseElementType(QualType type) const {
4158 SplitQualType split = type.getSplitDesugaredType();
4159 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4162 type = array->getElementType();
4163 qs.addConsistentQualifiers(split.Quals);
4166 return getQualifiedType(type, qs);
4169 /// getConstantArrayElementCount - Returns number of constant array elements.
4171 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4172 uint64_t ElementCount = 1;
4174 ElementCount *= CA->getSize().getZExtValue();
4175 CA = dyn_cast_or_null<ConstantArrayType>(
4176 CA->getElementType()->getAsArrayTypeUnsafe());
4178 return ElementCount;
4181 /// getFloatingRank - Return a relative rank for floating point types.
4182 /// This routine will assert if passed a built-in type that isn't a float.
4183 static FloatingRank getFloatingRank(QualType T) {
4184 if (const ComplexType *CT = T->getAs<ComplexType>())
4185 return getFloatingRank(CT->getElementType());
4187 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4188 switch (T->getAs<BuiltinType>()->getKind()) {
4189 default: llvm_unreachable("getFloatingRank(): not a floating type");
4190 case BuiltinType::Half: return HalfRank;
4191 case BuiltinType::Float: return FloatRank;
4192 case BuiltinType::Double: return DoubleRank;
4193 case BuiltinType::LongDouble: return LongDoubleRank;
4197 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4198 /// point or a complex type (based on typeDomain/typeSize).
4199 /// 'typeDomain' is a real floating point or complex type.
4200 /// 'typeSize' is a real floating point or complex type.
4201 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4202 QualType Domain) const {
4203 FloatingRank EltRank = getFloatingRank(Size);
4204 if (Domain->isComplexType()) {
4206 case HalfRank: llvm_unreachable("Complex half is not supported");
4207 case FloatRank: return FloatComplexTy;
4208 case DoubleRank: return DoubleComplexTy;
4209 case LongDoubleRank: return LongDoubleComplexTy;
4213 assert(Domain->isRealFloatingType() && "Unknown domain!");
4215 case HalfRank: return HalfTy;
4216 case FloatRank: return FloatTy;
4217 case DoubleRank: return DoubleTy;
4218 case LongDoubleRank: return LongDoubleTy;
4220 llvm_unreachable("getFloatingRank(): illegal value for rank");
4223 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4224 /// point types, ignoring the domain of the type (i.e. 'double' ==
4225 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4226 /// LHS < RHS, return -1.
4227 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4228 FloatingRank LHSR = getFloatingRank(LHS);
4229 FloatingRank RHSR = getFloatingRank(RHS);
4238 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4239 /// routine will assert if passed a built-in type that isn't an integer or enum,
4240 /// or if it is not canonicalized.
4241 unsigned ASTContext::getIntegerRank(const Type *T) const {
4242 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4244 switch (cast<BuiltinType>(T)->getKind()) {
4245 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4246 case BuiltinType::Bool:
4247 return 1 + (getIntWidth(BoolTy) << 3);
4248 case BuiltinType::Char_S:
4249 case BuiltinType::Char_U:
4250 case BuiltinType::SChar:
4251 case BuiltinType::UChar:
4252 return 2 + (getIntWidth(CharTy) << 3);
4253 case BuiltinType::Short:
4254 case BuiltinType::UShort:
4255 return 3 + (getIntWidth(ShortTy) << 3);
4256 case BuiltinType::Int:
4257 case BuiltinType::UInt:
4258 return 4 + (getIntWidth(IntTy) << 3);
4259 case BuiltinType::Long:
4260 case BuiltinType::ULong:
4261 return 5 + (getIntWidth(LongTy) << 3);
4262 case BuiltinType::LongLong:
4263 case BuiltinType::ULongLong:
4264 return 6 + (getIntWidth(LongLongTy) << 3);
4265 case BuiltinType::Int128:
4266 case BuiltinType::UInt128:
4267 return 7 + (getIntWidth(Int128Ty) << 3);
4271 /// \brief Whether this is a promotable bitfield reference according
4272 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4274 /// \returns the type this bit-field will promote to, or NULL if no
4275 /// promotion occurs.
4276 QualType ASTContext::isPromotableBitField(Expr *E) const {
4277 if (E->isTypeDependent() || E->isValueDependent())
4280 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4284 QualType FT = Field->getType();
4286 uint64_t BitWidth = Field->getBitWidthValue(*this);
4287 uint64_t IntSize = getTypeSize(IntTy);
4288 // GCC extension compatibility: if the bit-field size is less than or equal
4289 // to the size of int, it gets promoted no matter what its type is.
4290 // For instance, unsigned long bf : 4 gets promoted to signed int.
4291 if (BitWidth < IntSize)
4294 if (BitWidth == IntSize)
4295 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4297 // Types bigger than int are not subject to promotions, and therefore act
4298 // like the base type.
4299 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4304 /// getPromotedIntegerType - Returns the type that Promotable will
4305 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4307 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4308 assert(!Promotable.isNull());
4309 assert(Promotable->isPromotableIntegerType());
4310 if (const EnumType *ET = Promotable->getAs<EnumType>())
4311 return ET->getDecl()->getPromotionType();
4313 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4314 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4315 // (3.9.1) can be converted to a prvalue of the first of the following
4316 // types that can represent all the values of its underlying type:
4317 // int, unsigned int, long int, unsigned long int, long long int, or
4318 // unsigned long long int [...]
4319 // FIXME: Is there some better way to compute this?
4320 if (BT->getKind() == BuiltinType::WChar_S ||
4321 BT->getKind() == BuiltinType::WChar_U ||
4322 BT->getKind() == BuiltinType::Char16 ||
4323 BT->getKind() == BuiltinType::Char32) {
4324 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4325 uint64_t FromSize = getTypeSize(BT);
4326 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4327 LongLongTy, UnsignedLongLongTy };
4328 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4329 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4330 if (FromSize < ToSize ||
4331 (FromSize == ToSize &&
4332 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4333 return PromoteTypes[Idx];
4335 llvm_unreachable("char type should fit into long long");
4339 // At this point, we should have a signed or unsigned integer type.
4340 if (Promotable->isSignedIntegerType())
4342 uint64_t PromotableSize = getIntWidth(Promotable);
4343 uint64_t IntSize = getIntWidth(IntTy);
4344 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4345 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4348 /// \brief Recurses in pointer/array types until it finds an objc retainable
4349 /// type and returns its ownership.
4350 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4351 while (!T.isNull()) {
4352 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4353 return T.getObjCLifetime();
4354 if (T->isArrayType())
4355 T = getBaseElementType(T);
4356 else if (const PointerType *PT = T->getAs<PointerType>())
4357 T = PT->getPointeeType();
4358 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4359 T = RT->getPointeeType();
4364 return Qualifiers::OCL_None;
4367 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4368 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4369 /// LHS < RHS, return -1.
4370 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4371 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4372 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4373 if (LHSC == RHSC) return 0;
4375 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4376 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4378 unsigned LHSRank = getIntegerRank(LHSC);
4379 unsigned RHSRank = getIntegerRank(RHSC);
4381 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4382 if (LHSRank == RHSRank) return 0;
4383 return LHSRank > RHSRank ? 1 : -1;
4386 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4388 // If the unsigned [LHS] type is larger, return it.
4389 if (LHSRank >= RHSRank)
4392 // If the signed type can represent all values of the unsigned type, it
4393 // wins. Because we are dealing with 2's complement and types that are
4394 // powers of two larger than each other, this is always safe.
4398 // If the unsigned [RHS] type is larger, return it.
4399 if (RHSRank >= LHSRank)
4402 // If the signed type can represent all values of the unsigned type, it
4403 // wins. Because we are dealing with 2's complement and types that are
4404 // powers of two larger than each other, this is always safe.
4409 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4410 DeclContext *DC, IdentifierInfo *Id) {
4412 if (Ctx.getLangOpts().CPlusPlus)
4413 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4415 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4418 // getCFConstantStringType - Return the type used for constant CFStrings.
4419 QualType ASTContext::getCFConstantStringType() const {
4420 if (!CFConstantStringTypeDecl) {
4421 CFConstantStringTypeDecl =
4422 CreateRecordDecl(*this, TTK_Struct, TUDecl,
4423 &Idents.get("NSConstantString"));
4424 CFConstantStringTypeDecl->startDefinition();
4426 QualType FieldTypes[4];
4429 FieldTypes[0] = getPointerType(IntTy.withConst());
4431 FieldTypes[1] = IntTy;
4433 FieldTypes[2] = getPointerType(CharTy.withConst());
4435 FieldTypes[3] = LongTy;
4438 for (unsigned i = 0; i < 4; ++i) {
4439 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4441 SourceLocation(), 0,
4442 FieldTypes[i], /*TInfo=*/0,
4446 Field->setAccess(AS_public);
4447 CFConstantStringTypeDecl->addDecl(Field);
4450 CFConstantStringTypeDecl->completeDefinition();
4453 return getTagDeclType(CFConstantStringTypeDecl);
4456 QualType ASTContext::getObjCSuperType() const {
4457 if (ObjCSuperType.isNull()) {
4458 RecordDecl *ObjCSuperTypeDecl =
4459 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4460 TUDecl->addDecl(ObjCSuperTypeDecl);
4461 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4463 return ObjCSuperType;
4466 void ASTContext::setCFConstantStringType(QualType T) {
4467 const RecordType *Rec = T->getAs<RecordType>();
4468 assert(Rec && "Invalid CFConstantStringType");
4469 CFConstantStringTypeDecl = Rec->getDecl();
4472 QualType ASTContext::getBlockDescriptorType() const {
4473 if (BlockDescriptorType)
4474 return getTagDeclType(BlockDescriptorType);
4477 // FIXME: Needs the FlagAppleBlock bit.
4478 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4479 &Idents.get("__block_descriptor"));
4480 T->startDefinition();
4482 QualType FieldTypes[] = {
4487 const char *FieldNames[] = {
4492 for (size_t i = 0; i < 2; ++i) {
4493 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4495 &Idents.get(FieldNames[i]),
4496 FieldTypes[i], /*TInfo=*/0,
4500 Field->setAccess(AS_public);
4504 T->completeDefinition();
4506 BlockDescriptorType = T;
4508 return getTagDeclType(BlockDescriptorType);
4511 QualType ASTContext::getBlockDescriptorExtendedType() const {
4512 if (BlockDescriptorExtendedType)
4513 return getTagDeclType(BlockDescriptorExtendedType);
4516 // FIXME: Needs the FlagAppleBlock bit.
4517 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4518 &Idents.get("__block_descriptor_withcopydispose"));
4519 T->startDefinition();
4521 QualType FieldTypes[] = {
4524 getPointerType(VoidPtrTy),
4525 getPointerType(VoidPtrTy)
4528 const char *FieldNames[] = {
4535 for (size_t i = 0; i < 4; ++i) {
4536 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4538 &Idents.get(FieldNames[i]),
4539 FieldTypes[i], /*TInfo=*/0,
4543 Field->setAccess(AS_public);
4547 T->completeDefinition();
4549 BlockDescriptorExtendedType = T;
4551 return getTagDeclType(BlockDescriptorExtendedType);
4554 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4555 /// requires copy/dispose. Note that this must match the logic
4556 /// in buildByrefHelpers.
4557 bool ASTContext::BlockRequiresCopying(QualType Ty,
4559 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4560 const Expr *copyExpr = getBlockVarCopyInits(D);
4561 if (!copyExpr && record->hasTrivialDestructor()) return false;
4566 if (!Ty->isObjCRetainableType()) return false;
4568 Qualifiers qs = Ty.getQualifiers();
4570 // If we have lifetime, that dominates.
4571 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4572 assert(getLangOpts().ObjCAutoRefCount);
4575 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4577 // These are just bits as far as the runtime is concerned.
4578 case Qualifiers::OCL_ExplicitNone:
4579 case Qualifiers::OCL_Autoreleasing:
4582 // Tell the runtime that this is ARC __weak, called by the
4584 case Qualifiers::OCL_Weak:
4585 // ARC __strong __block variables need to be retained.
4586 case Qualifiers::OCL_Strong:
4589 llvm_unreachable("fell out of lifetime switch!");
4591 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4592 Ty->isObjCObjectPointerType());
4595 bool ASTContext::getByrefLifetime(QualType Ty,
4596 Qualifiers::ObjCLifetime &LifeTime,
4597 bool &HasByrefExtendedLayout) const {
4599 if (!getLangOpts().ObjC1 ||
4600 getLangOpts().getGC() != LangOptions::NonGC)
4603 HasByrefExtendedLayout = false;
4604 if (Ty->isRecordType()) {
4605 HasByrefExtendedLayout = true;
4606 LifeTime = Qualifiers::OCL_None;
4608 else if (getLangOpts().ObjCAutoRefCount)
4609 LifeTime = Ty.getObjCLifetime();
4611 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4612 LifeTime = Qualifiers::OCL_ExplicitNone;
4614 LifeTime = Qualifiers::OCL_None;
4618 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4619 if (!ObjCInstanceTypeDecl)
4620 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4621 getTranslationUnitDecl(),
4624 &Idents.get("instancetype"),
4625 getTrivialTypeSourceInfo(getObjCIdType()));
4626 return ObjCInstanceTypeDecl;
4629 // This returns true if a type has been typedefed to BOOL:
4630 // typedef <type> BOOL;
4631 static bool isTypeTypedefedAsBOOL(QualType T) {
4632 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4633 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4634 return II->isStr("BOOL");
4639 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4641 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4642 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4643 return CharUnits::Zero();
4645 CharUnits sz = getTypeSizeInChars(type);
4647 // Make all integer and enum types at least as large as an int
4648 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4649 sz = std::max(sz, getTypeSizeInChars(IntTy));
4650 // Treat arrays as pointers, since that's how they're passed in.
4651 else if (type->isArrayType())
4652 sz = getTypeSizeInChars(VoidPtrTy);
4657 std::string charUnitsToString(const CharUnits &CU) {
4658 return llvm::itostr(CU.getQuantity());
4661 /// getObjCEncodingForBlock - Return the encoded type for this block
4663 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4666 const BlockDecl *Decl = Expr->getBlockDecl();
4668 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4669 // Encode result type.
4670 if (getLangOpts().EncodeExtendedBlockSig)
4671 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4672 BlockTy->getAs<FunctionType>()->getResultType(),
4673 S, true /*Extended*/);
4675 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4677 // Compute size of all parameters.
4678 // Start with computing size of a pointer in number of bytes.
4679 // FIXME: There might(should) be a better way of doing this computation!
4681 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4682 CharUnits ParmOffset = PtrSize;
4683 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4684 E = Decl->param_end(); PI != E; ++PI) {
4685 QualType PType = (*PI)->getType();
4686 CharUnits sz = getObjCEncodingTypeSize(PType);
4689 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4692 // Size of the argument frame
4693 S += charUnitsToString(ParmOffset);
4694 // Block pointer and offset.
4698 ParmOffset = PtrSize;
4699 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4700 Decl->param_end(); PI != E; ++PI) {
4701 ParmVarDecl *PVDecl = *PI;
4702 QualType PType = PVDecl->getOriginalType();
4703 if (const ArrayType *AT =
4704 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4705 // Use array's original type only if it has known number of
4707 if (!isa<ConstantArrayType>(AT))
4708 PType = PVDecl->getType();
4709 } else if (PType->isFunctionType())
4710 PType = PVDecl->getType();
4711 if (getLangOpts().EncodeExtendedBlockSig)
4712 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4713 S, true /*Extended*/);
4715 getObjCEncodingForType(PType, S);
4716 S += charUnitsToString(ParmOffset);
4717 ParmOffset += getObjCEncodingTypeSize(PType);
4723 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4725 // Encode result type.
4726 getObjCEncodingForType(Decl->getResultType(), S);
4727 CharUnits ParmOffset;
4728 // Compute size of all parameters.
4729 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4730 E = Decl->param_end(); PI != E; ++PI) {
4731 QualType PType = (*PI)->getType();
4732 CharUnits sz = getObjCEncodingTypeSize(PType);
4736 assert (sz.isPositive() &&
4737 "getObjCEncodingForFunctionDecl - Incomplete param type");
4740 S += charUnitsToString(ParmOffset);
4741 ParmOffset = CharUnits::Zero();
4744 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4745 E = Decl->param_end(); PI != E; ++PI) {
4746 ParmVarDecl *PVDecl = *PI;
4747 QualType PType = PVDecl->getOriginalType();
4748 if (const ArrayType *AT =
4749 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4750 // Use array's original type only if it has known number of
4752 if (!isa<ConstantArrayType>(AT))
4753 PType = PVDecl->getType();
4754 } else if (PType->isFunctionType())
4755 PType = PVDecl->getType();
4756 getObjCEncodingForType(PType, S);
4757 S += charUnitsToString(ParmOffset);
4758 ParmOffset += getObjCEncodingTypeSize(PType);
4764 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4765 /// method parameter or return type. If Extended, include class names and
4766 /// block object types.
4767 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4768 QualType T, std::string& S,
4769 bool Extended) const {
4770 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4771 getObjCEncodingForTypeQualifier(QT, S);
4772 // Encode parameter type.
4773 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4774 true /*OutermostType*/,
4775 false /*EncodingProperty*/,
4776 false /*StructField*/,
4777 Extended /*EncodeBlockParameters*/,
4778 Extended /*EncodeClassNames*/);
4781 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4783 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4785 bool Extended) const {
4786 // FIXME: This is not very efficient.
4787 // Encode return type.
4788 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4789 Decl->getResultType(), S, Extended);
4790 // Compute size of all parameters.
4791 // Start with computing size of a pointer in number of bytes.
4792 // FIXME: There might(should) be a better way of doing this computation!
4794 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4795 // The first two arguments (self and _cmd) are pointers; account for
4797 CharUnits ParmOffset = 2 * PtrSize;
4798 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4799 E = Decl->sel_param_end(); PI != E; ++PI) {
4800 QualType PType = (*PI)->getType();
4801 CharUnits sz = getObjCEncodingTypeSize(PType);
4805 assert (sz.isPositive() &&
4806 "getObjCEncodingForMethodDecl - Incomplete param type");
4809 S += charUnitsToString(ParmOffset);
4811 S += charUnitsToString(PtrSize);
4814 ParmOffset = 2 * PtrSize;
4815 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4816 E = Decl->sel_param_end(); PI != E; ++PI) {
4817 const ParmVarDecl *PVDecl = *PI;
4818 QualType PType = PVDecl->getOriginalType();
4819 if (const ArrayType *AT =
4820 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4821 // Use array's original type only if it has known number of
4823 if (!isa<ConstantArrayType>(AT))
4824 PType = PVDecl->getType();
4825 } else if (PType->isFunctionType())
4826 PType = PVDecl->getType();
4827 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4828 PType, S, Extended);
4829 S += charUnitsToString(ParmOffset);
4830 ParmOffset += getObjCEncodingTypeSize(PType);
4836 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4837 /// property declaration. If non-NULL, Container must be either an
4838 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4839 /// NULL when getting encodings for protocol properties.
4840 /// Property attributes are stored as a comma-delimited C string. The simple
4841 /// attributes readonly and bycopy are encoded as single characters. The
4842 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4843 /// encoded as single characters, followed by an identifier. Property types
4844 /// are also encoded as a parametrized attribute. The characters used to encode
4845 /// these attributes are defined by the following enumeration:
4847 /// enum PropertyAttributes {
4848 /// kPropertyReadOnly = 'R', // property is read-only.
4849 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4850 /// kPropertyByref = '&', // property is a reference to the value last assigned
4851 /// kPropertyDynamic = 'D', // property is dynamic
4852 /// kPropertyGetter = 'G', // followed by getter selector name
4853 /// kPropertySetter = 'S', // followed by setter selector name
4854 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4855 /// kPropertyType = 'T' // followed by old-style type encoding.
4856 /// kPropertyWeak = 'W' // 'weak' property
4857 /// kPropertyStrong = 'P' // property GC'able
4858 /// kPropertyNonAtomic = 'N' // property non-atomic
4861 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4862 const Decl *Container,
4863 std::string& S) const {
4864 // Collect information from the property implementation decl(s).
4865 bool Dynamic = false;
4866 ObjCPropertyImplDecl *SynthesizePID = 0;
4868 // FIXME: Duplicated code due to poor abstraction.
4870 if (const ObjCCategoryImplDecl *CID =
4871 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4872 for (ObjCCategoryImplDecl::propimpl_iterator
4873 i = CID->propimpl_begin(), e = CID->propimpl_end();
4875 ObjCPropertyImplDecl *PID = *i;
4876 if (PID->getPropertyDecl() == PD) {
4877 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4880 SynthesizePID = PID;
4885 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4886 for (ObjCCategoryImplDecl::propimpl_iterator
4887 i = OID->propimpl_begin(), e = OID->propimpl_end();
4889 ObjCPropertyImplDecl *PID = *i;
4890 if (PID->getPropertyDecl() == PD) {
4891 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4894 SynthesizePID = PID;
4901 // FIXME: This is not very efficient.
4904 // Encode result type.
4905 // GCC has some special rules regarding encoding of properties which
4906 // closely resembles encoding of ivars.
4907 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4908 true /* outermost type */,
4909 true /* encoding for property */);
4911 if (PD->isReadOnly()) {
4914 switch (PD->getSetterKind()) {
4915 case ObjCPropertyDecl::Assign: break;
4916 case ObjCPropertyDecl::Copy: S += ",C"; break;
4917 case ObjCPropertyDecl::Retain: S += ",&"; break;
4918 case ObjCPropertyDecl::Weak: S += ",W"; break;
4922 // It really isn't clear at all what this means, since properties
4923 // are "dynamic by default".
4927 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4930 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4932 S += PD->getGetterName().getAsString();
4935 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4937 S += PD->getSetterName().getAsString();
4940 if (SynthesizePID) {
4941 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4943 S += OID->getNameAsString();
4946 // FIXME: OBJCGC: weak & strong
4949 /// getLegacyIntegralTypeEncoding -
4950 /// Another legacy compatibility encoding: 32-bit longs are encoded as
4951 /// 'l' or 'L' , but not always. For typedefs, we need to use
4952 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
4954 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4955 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4956 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4957 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4958 PointeeTy = UnsignedIntTy;
4960 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4966 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4967 const FieldDecl *Field) const {
4968 // We follow the behavior of gcc, expanding structures which are
4969 // directly pointed to, and expanding embedded structures. Note that
4970 // these rules are sufficient to prevent recursive encoding of the
4972 getObjCEncodingForTypeImpl(T, S, true, true, Field,
4973 true /* outermost type */);
4976 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4977 BuiltinType::Kind kind) {
4979 case BuiltinType::Void: return 'v';
4980 case BuiltinType::Bool: return 'B';
4981 case BuiltinType::Char_U:
4982 case BuiltinType::UChar: return 'C';
4983 case BuiltinType::Char16:
4984 case BuiltinType::UShort: return 'S';
4985 case BuiltinType::Char32:
4986 case BuiltinType::UInt: return 'I';
4987 case BuiltinType::ULong:
4988 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
4989 case BuiltinType::UInt128: return 'T';
4990 case BuiltinType::ULongLong: return 'Q';
4991 case BuiltinType::Char_S:
4992 case BuiltinType::SChar: return 'c';
4993 case BuiltinType::Short: return 's';
4994 case BuiltinType::WChar_S:
4995 case BuiltinType::WChar_U:
4996 case BuiltinType::Int: return 'i';
4997 case BuiltinType::Long:
4998 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
4999 case BuiltinType::LongLong: return 'q';
5000 case BuiltinType::Int128: return 't';
5001 case BuiltinType::Float: return 'f';
5002 case BuiltinType::Double: return 'd';
5003 case BuiltinType::LongDouble: return 'D';
5004 case BuiltinType::NullPtr: return '*'; // like char*
5006 case BuiltinType::Half:
5007 // FIXME: potentially need @encodes for these!
5010 case BuiltinType::ObjCId:
5011 case BuiltinType::ObjCClass:
5012 case BuiltinType::ObjCSel:
5013 llvm_unreachable("@encoding ObjC primitive type");
5015 // OpenCL and placeholder types don't need @encodings.
5016 case BuiltinType::OCLImage1d:
5017 case BuiltinType::OCLImage1dArray:
5018 case BuiltinType::OCLImage1dBuffer:
5019 case BuiltinType::OCLImage2d:
5020 case BuiltinType::OCLImage2dArray:
5021 case BuiltinType::OCLImage3d:
5022 case BuiltinType::OCLEvent:
5023 case BuiltinType::OCLSampler:
5024 case BuiltinType::Dependent:
5025 #define BUILTIN_TYPE(KIND, ID)
5026 #define PLACEHOLDER_TYPE(KIND, ID) \
5027 case BuiltinType::KIND:
5028 #include "clang/AST/BuiltinTypes.def"
5029 llvm_unreachable("invalid builtin type for @encode");
5031 llvm_unreachable("invalid BuiltinType::Kind value");
5034 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5035 EnumDecl *Enum = ET->getDecl();
5037 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5038 if (!Enum->isFixed())
5041 // The encoding of a fixed enum type matches its fixed underlying type.
5042 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5043 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5046 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5047 QualType T, const FieldDecl *FD) {
5048 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5050 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5051 // The GNU runtime requires more information; bitfields are encoded as b,
5052 // then the offset (in bits) of the first element, then the type of the
5053 // bitfield, then the size in bits. For example, in this structure:
5060 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5061 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5062 // information is not especially sensible, but we're stuck with it for
5063 // compatibility with GCC, although providing it breaks anything that
5064 // actually uses runtime introspection and wants to work on both runtimes...
5065 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5066 const RecordDecl *RD = FD->getParent();
5067 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5068 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5069 if (const EnumType *ET = T->getAs<EnumType>())
5070 S += ObjCEncodingForEnumType(Ctx, ET);
5072 const BuiltinType *BT = T->castAs<BuiltinType>();
5073 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5076 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5079 // FIXME: Use SmallString for accumulating string.
5080 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5081 bool ExpandPointedToStructures,
5082 bool ExpandStructures,
5083 const FieldDecl *FD,
5085 bool EncodingProperty,
5087 bool EncodeBlockParameters,
5088 bool EncodeClassNames,
5089 bool EncodePointerToObjCTypedef) const {
5090 CanQualType CT = getCanonicalType(T);
5091 switch (CT->getTypeClass()) {
5094 if (FD && FD->isBitField())
5095 return EncodeBitField(this, S, T, FD);
5096 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5097 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5099 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5102 case Type::Complex: {
5103 const ComplexType *CT = T->castAs<ComplexType>();
5105 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
5110 case Type::Atomic: {
5111 const AtomicType *AT = T->castAs<AtomicType>();
5113 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5118 // encoding for pointer or reference types.
5120 case Type::LValueReference:
5121 case Type::RValueReference: {
5123 if (isa<PointerType>(CT)) {
5124 const PointerType *PT = T->castAs<PointerType>();
5125 if (PT->isObjCSelType()) {
5129 PointeeTy = PT->getPointeeType();
5131 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5134 bool isReadOnly = false;
5135 // For historical/compatibility reasons, the read-only qualifier of the
5136 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5137 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5138 // Also, do not emit the 'r' for anything but the outermost type!
5139 if (isa<TypedefType>(T.getTypePtr())) {
5140 if (OutermostType && T.isConstQualified()) {
5144 } else if (OutermostType) {
5145 QualType P = PointeeTy;
5146 while (P->getAs<PointerType>())
5147 P = P->getAs<PointerType>()->getPointeeType();
5148 if (P.isConstQualified()) {
5154 // Another legacy compatibility encoding. Some ObjC qualifier and type
5155 // combinations need to be rearranged.
5156 // Rewrite "in const" from "nr" to "rn"
5157 if (StringRef(S).endswith("nr"))
5158 S.replace(S.end()-2, S.end(), "rn");
5161 if (PointeeTy->isCharType()) {
5162 // char pointer types should be encoded as '*' unless it is a
5163 // type that has been typedef'd to 'BOOL'.
5164 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5168 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5169 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5170 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5174 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5175 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5182 getLegacyIntegralTypeEncoding(PointeeTy);
5184 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5189 case Type::ConstantArray:
5190 case Type::IncompleteArray:
5191 case Type::VariableArray: {
5192 const ArrayType *AT = cast<ArrayType>(CT);
5194 if (isa<IncompleteArrayType>(AT) && !StructField) {
5195 // Incomplete arrays are encoded as a pointer to the array element.
5198 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5199 false, ExpandStructures, FD);
5203 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5204 if (getTypeSize(CAT->getElementType()) == 0)
5207 S += llvm::utostr(CAT->getSize().getZExtValue());
5209 //Variable length arrays are encoded as a regular array with 0 elements.
5210 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5211 "Unknown array type!");
5215 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5216 false, ExpandStructures, FD);
5222 case Type::FunctionNoProto:
5223 case Type::FunctionProto:
5227 case Type::Record: {
5228 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5229 S += RDecl->isUnion() ? '(' : '{';
5230 // Anonymous structures print as '?'
5231 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5233 if (ClassTemplateSpecializationDecl *Spec
5234 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5235 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5236 llvm::raw_string_ostream OS(S);
5237 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5238 TemplateArgs.data(),
5239 TemplateArgs.size(),
5240 (*this).getPrintingPolicy());
5245 if (ExpandStructures) {
5247 if (!RDecl->isUnion()) {
5248 getObjCEncodingForStructureImpl(RDecl, S, FD);
5250 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5251 FieldEnd = RDecl->field_end();
5252 Field != FieldEnd; ++Field) {
5255 S += Field->getNameAsString();
5259 // Special case bit-fields.
5260 if (Field->isBitField()) {
5261 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5264 QualType qt = Field->getType();
5265 getLegacyIntegralTypeEncoding(qt);
5266 getObjCEncodingForTypeImpl(qt, S, false, true,
5267 FD, /*OutermostType*/false,
5268 /*EncodingProperty*/false,
5269 /*StructField*/true);
5274 S += RDecl->isUnion() ? ')' : '}';
5278 case Type::BlockPointer: {
5279 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5280 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5281 if (EncodeBlockParameters) {
5282 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5285 // Block return type
5286 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5287 ExpandPointedToStructures, ExpandStructures,
5289 false /* OutermostType */,
5291 false /* StructField */,
5292 EncodeBlockParameters,
5297 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5298 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5299 E = FPT->arg_type_end(); I && (I != E); ++I) {
5300 getObjCEncodingForTypeImpl(*I, S,
5301 ExpandPointedToStructures,
5304 false /* OutermostType */,
5306 false /* StructField */,
5307 EncodeBlockParameters,
5316 case Type::ObjCObject:
5317 case Type::ObjCInterface: {
5318 // Ignore protocol qualifiers when mangling at this level.
5319 T = T->castAs<ObjCObjectType>()->getBaseType();
5321 // The assumption seems to be that this assert will succeed
5322 // because nested levels will have filtered out 'id' and 'Class'.
5323 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5324 // @encode(class_name)
5325 ObjCInterfaceDecl *OI = OIT->getDecl();
5327 const IdentifierInfo *II = OI->getIdentifier();
5330 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5331 DeepCollectObjCIvars(OI, true, Ivars);
5332 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5333 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5334 if (Field->isBitField())
5335 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5337 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5338 false, false, false, false, false,
5339 EncodePointerToObjCTypedef);
5345 case Type::ObjCObjectPointer: {
5346 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5347 if (OPT->isObjCIdType()) {
5352 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5353 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5354 // Since this is a binary compatibility issue, need to consult with runtime
5355 // folks. Fortunately, this is a *very* obsure construct.
5360 if (OPT->isObjCQualifiedIdType()) {
5361 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5362 ExpandPointedToStructures,
5363 ExpandStructures, FD);
5364 if (FD || EncodingProperty || EncodeClassNames) {
5365 // Note that we do extended encoding of protocol qualifer list
5366 // Only when doing ivar or property encoding.
5368 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5369 E = OPT->qual_end(); I != E; ++I) {
5371 S += (*I)->getNameAsString();
5379 QualType PointeeTy = OPT->getPointeeType();
5380 if (!EncodingProperty &&
5381 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5382 !EncodePointerToObjCTypedef) {
5383 // Another historical/compatibility reason.
5384 // We encode the underlying type which comes out as
5387 getObjCEncodingForTypeImpl(PointeeTy, S,
5388 false, ExpandPointedToStructures,
5390 false, false, false, false, false,
5391 /*EncodePointerToObjCTypedef*/true);
5396 if (OPT->getInterfaceDecl() &&
5397 (FD || EncodingProperty || EncodeClassNames)) {
5399 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5400 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5401 E = OPT->qual_end(); I != E; ++I) {
5403 S += (*I)->getNameAsString();
5411 // gcc just blithely ignores member pointers.
5412 // FIXME: we shoul do better than that. 'M' is available.
5413 case Type::MemberPointer:
5417 case Type::ExtVector:
5418 // This matches gcc's encoding, even though technically it is
5420 // FIXME. We should do a better job than gcc.
5424 // We could see an undeduced auto type here during error recovery.
5428 #define ABSTRACT_TYPE(KIND, BASE)
5429 #define TYPE(KIND, BASE)
5430 #define DEPENDENT_TYPE(KIND, BASE) \
5432 #define NON_CANONICAL_TYPE(KIND, BASE) \
5434 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5436 #include "clang/AST/TypeNodes.def"
5437 llvm_unreachable("@encode for dependent type!");
5439 llvm_unreachable("bad type kind!");
5442 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5444 const FieldDecl *FD,
5445 bool includeVBases) const {
5446 assert(RDecl && "Expected non-null RecordDecl");
5447 assert(!RDecl->isUnion() && "Should not be called for unions");
5448 if (!RDecl->getDefinition())
5451 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5452 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5453 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5456 for (CXXRecordDecl::base_class_iterator
5457 BI = CXXRec->bases_begin(),
5458 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5459 if (!BI->isVirtual()) {
5460 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5461 if (base->isEmpty())
5463 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5464 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5465 std::make_pair(offs, base));
5471 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5472 FieldEnd = RDecl->field_end();
5473 Field != FieldEnd; ++Field, ++i) {
5474 uint64_t offs = layout.getFieldOffset(i);
5475 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5476 std::make_pair(offs, *Field));
5479 if (CXXRec && includeVBases) {
5480 for (CXXRecordDecl::base_class_iterator
5481 BI = CXXRec->vbases_begin(),
5482 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5483 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5484 if (base->isEmpty())
5486 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5487 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5488 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5489 std::make_pair(offs, base));
5495 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5497 size = layout.getSize();
5500 uint64_t CurOffs = 0;
5501 std::multimap<uint64_t, NamedDecl *>::iterator
5502 CurLayObj = FieldOrBaseOffsets.begin();
5504 if (CXXRec && CXXRec->isDynamicClass() &&
5505 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5508 std::string recname = CXXRec->getNameAsString();
5509 if (recname.empty()) recname = "?";
5514 CurOffs += getTypeSize(VoidPtrTy);
5517 if (!RDecl->hasFlexibleArrayMember()) {
5518 // Mark the end of the structure.
5519 uint64_t offs = toBits(size);
5520 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5521 std::make_pair(offs, (NamedDecl*)0));
5524 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5525 assert(CurOffs <= CurLayObj->first);
5527 if (CurOffs < CurLayObj->first) {
5528 uint64_t padding = CurLayObj->first - CurOffs;
5529 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5530 // packing/alignment of members is different that normal, in which case
5531 // the encoding will be out-of-sync with the real layout.
5532 // If the runtime switches to just consider the size of types without
5533 // taking into account alignment, we could make padding explicit in the
5534 // encoding (e.g. using arrays of chars). The encoding strings would be
5535 // longer then though.
5539 NamedDecl *dcl = CurLayObj->second;
5541 break; // reached end of structure.
5543 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5544 // We expand the bases without their virtual bases since those are going
5545 // in the initial structure. Note that this differs from gcc which
5546 // expands virtual bases each time one is encountered in the hierarchy,
5547 // making the encoding type bigger than it really is.
5548 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5549 assert(!base->isEmpty());
5550 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5552 FieldDecl *field = cast<FieldDecl>(dcl);
5555 S += field->getNameAsString();
5559 if (field->isBitField()) {
5560 EncodeBitField(this, S, field->getType(), field);
5561 CurOffs += field->getBitWidthValue(*this);
5563 QualType qt = field->getType();
5564 getLegacyIntegralTypeEncoding(qt);
5565 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5566 /*OutermostType*/false,
5567 /*EncodingProperty*/false,
5568 /*StructField*/true);
5569 CurOffs += getTypeSize(field->getType());
5575 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5576 std::string& S) const {
5577 if (QT & Decl::OBJC_TQ_In)
5579 if (QT & Decl::OBJC_TQ_Inout)
5581 if (QT & Decl::OBJC_TQ_Out)
5583 if (QT & Decl::OBJC_TQ_Bycopy)
5585 if (QT & Decl::OBJC_TQ_Byref)
5587 if (QT & Decl::OBJC_TQ_Oneway)
5591 TypedefDecl *ASTContext::getObjCIdDecl() const {
5593 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5594 T = getObjCObjectPointerType(T);
5595 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5596 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5597 getTranslationUnitDecl(),
5598 SourceLocation(), SourceLocation(),
5599 &Idents.get("id"), IdInfo);
5605 TypedefDecl *ASTContext::getObjCSelDecl() const {
5607 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5608 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5609 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5610 getTranslationUnitDecl(),
5611 SourceLocation(), SourceLocation(),
5612 &Idents.get("SEL"), SelInfo);
5617 TypedefDecl *ASTContext::getObjCClassDecl() const {
5618 if (!ObjCClassDecl) {
5619 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5620 T = getObjCObjectPointerType(T);
5621 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5622 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5623 getTranslationUnitDecl(),
5624 SourceLocation(), SourceLocation(),
5625 &Idents.get("Class"), ClassInfo);
5628 return ObjCClassDecl;
5631 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5632 if (!ObjCProtocolClassDecl) {
5633 ObjCProtocolClassDecl
5634 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5636 &Idents.get("Protocol"),
5638 SourceLocation(), true);
5641 return ObjCProtocolClassDecl;
5644 //===----------------------------------------------------------------------===//
5645 // __builtin_va_list Construction Functions
5646 //===----------------------------------------------------------------------===//
5648 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5649 // typedef char* __builtin_va_list;
5650 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5651 TypeSourceInfo *TInfo
5652 = Context->getTrivialTypeSourceInfo(CharPtrType);
5654 TypedefDecl *VaListTypeDecl
5655 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5656 Context->getTranslationUnitDecl(),
5657 SourceLocation(), SourceLocation(),
5658 &Context->Idents.get("__builtin_va_list"),
5660 return VaListTypeDecl;
5663 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5664 // typedef void* __builtin_va_list;
5665 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5666 TypeSourceInfo *TInfo
5667 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5669 TypedefDecl *VaListTypeDecl
5670 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5671 Context->getTranslationUnitDecl(),
5672 SourceLocation(), SourceLocation(),
5673 &Context->Idents.get("__builtin_va_list"),
5675 return VaListTypeDecl;
5678 static TypedefDecl *
5679 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5680 RecordDecl *VaListTagDecl;
5681 if (Context->getLangOpts().CPlusPlus) {
5682 // namespace std { struct __va_list {
5684 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5685 Context->getTranslationUnitDecl(),
5686 /*Inline*/false, SourceLocation(),
5687 SourceLocation(), &Context->Idents.get("std"),
5690 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5691 Context->getTranslationUnitDecl(),
5692 SourceLocation(), SourceLocation(),
5693 &Context->Idents.get("__va_list"));
5694 VaListTagDecl->setDeclContext(NS);
5697 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5698 Context->getTranslationUnitDecl(),
5699 &Context->Idents.get("__va_list"));
5702 VaListTagDecl->startDefinition();
5704 const size_t NumFields = 5;
5705 QualType FieldTypes[NumFields];
5706 const char *FieldNames[NumFields];
5709 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5710 FieldNames[0] = "__stack";
5713 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5714 FieldNames[1] = "__gr_top";
5717 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5718 FieldNames[2] = "__vr_top";
5721 FieldTypes[3] = Context->IntTy;
5722 FieldNames[3] = "__gr_offs";
5725 FieldTypes[4] = Context->IntTy;
5726 FieldNames[4] = "__vr_offs";
5729 for (unsigned i = 0; i < NumFields; ++i) {
5730 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5734 &Context->Idents.get(FieldNames[i]),
5735 FieldTypes[i], /*TInfo=*/0,
5739 Field->setAccess(AS_public);
5740 VaListTagDecl->addDecl(Field);
5742 VaListTagDecl->completeDefinition();
5743 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5744 Context->VaListTagTy = VaListTagType;
5746 // } __builtin_va_list;
5747 TypedefDecl *VaListTypedefDecl
5748 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5749 Context->getTranslationUnitDecl(),
5750 SourceLocation(), SourceLocation(),
5751 &Context->Idents.get("__builtin_va_list"),
5752 Context->getTrivialTypeSourceInfo(VaListTagType));
5754 return VaListTypedefDecl;
5757 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5758 // typedef struct __va_list_tag {
5759 RecordDecl *VaListTagDecl;
5761 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5762 Context->getTranslationUnitDecl(),
5763 &Context->Idents.get("__va_list_tag"));
5764 VaListTagDecl->startDefinition();
5766 const size_t NumFields = 5;
5767 QualType FieldTypes[NumFields];
5768 const char *FieldNames[NumFields];
5770 // unsigned char gpr;
5771 FieldTypes[0] = Context->UnsignedCharTy;
5772 FieldNames[0] = "gpr";
5774 // unsigned char fpr;
5775 FieldTypes[1] = Context->UnsignedCharTy;
5776 FieldNames[1] = "fpr";
5778 // unsigned short reserved;
5779 FieldTypes[2] = Context->UnsignedShortTy;
5780 FieldNames[2] = "reserved";
5782 // void* overflow_arg_area;
5783 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5784 FieldNames[3] = "overflow_arg_area";
5786 // void* reg_save_area;
5787 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5788 FieldNames[4] = "reg_save_area";
5791 for (unsigned i = 0; i < NumFields; ++i) {
5792 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5795 &Context->Idents.get(FieldNames[i]),
5796 FieldTypes[i], /*TInfo=*/0,
5800 Field->setAccess(AS_public);
5801 VaListTagDecl->addDecl(Field);
5803 VaListTagDecl->completeDefinition();
5804 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5805 Context->VaListTagTy = VaListTagType;
5808 TypedefDecl *VaListTagTypedefDecl
5809 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5810 Context->getTranslationUnitDecl(),
5811 SourceLocation(), SourceLocation(),
5812 &Context->Idents.get("__va_list_tag"),
5813 Context->getTrivialTypeSourceInfo(VaListTagType));
5814 QualType VaListTagTypedefType =
5815 Context->getTypedefType(VaListTagTypedefDecl);
5817 // typedef __va_list_tag __builtin_va_list[1];
5818 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5819 QualType VaListTagArrayType
5820 = Context->getConstantArrayType(VaListTagTypedefType,
5821 Size, ArrayType::Normal, 0);
5822 TypeSourceInfo *TInfo
5823 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5824 TypedefDecl *VaListTypedefDecl
5825 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5826 Context->getTranslationUnitDecl(),
5827 SourceLocation(), SourceLocation(),
5828 &Context->Idents.get("__builtin_va_list"),
5831 return VaListTypedefDecl;
5834 static TypedefDecl *
5835 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5836 // typedef struct __va_list_tag {
5837 RecordDecl *VaListTagDecl;
5838 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5839 Context->getTranslationUnitDecl(),
5840 &Context->Idents.get("__va_list_tag"));
5841 VaListTagDecl->startDefinition();
5843 const size_t NumFields = 4;
5844 QualType FieldTypes[NumFields];
5845 const char *FieldNames[NumFields];
5847 // unsigned gp_offset;
5848 FieldTypes[0] = Context->UnsignedIntTy;
5849 FieldNames[0] = "gp_offset";
5851 // unsigned fp_offset;
5852 FieldTypes[1] = Context->UnsignedIntTy;
5853 FieldNames[1] = "fp_offset";
5855 // void* overflow_arg_area;
5856 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5857 FieldNames[2] = "overflow_arg_area";
5859 // void* reg_save_area;
5860 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5861 FieldNames[3] = "reg_save_area";
5864 for (unsigned i = 0; i < NumFields; ++i) {
5865 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5869 &Context->Idents.get(FieldNames[i]),
5870 FieldTypes[i], /*TInfo=*/0,
5874 Field->setAccess(AS_public);
5875 VaListTagDecl->addDecl(Field);
5877 VaListTagDecl->completeDefinition();
5878 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5879 Context->VaListTagTy = VaListTagType;
5882 TypedefDecl *VaListTagTypedefDecl
5883 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5884 Context->getTranslationUnitDecl(),
5885 SourceLocation(), SourceLocation(),
5886 &Context->Idents.get("__va_list_tag"),
5887 Context->getTrivialTypeSourceInfo(VaListTagType));
5888 QualType VaListTagTypedefType =
5889 Context->getTypedefType(VaListTagTypedefDecl);
5891 // typedef __va_list_tag __builtin_va_list[1];
5892 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5893 QualType VaListTagArrayType
5894 = Context->getConstantArrayType(VaListTagTypedefType,
5895 Size, ArrayType::Normal,0);
5896 TypeSourceInfo *TInfo
5897 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5898 TypedefDecl *VaListTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__builtin_va_list"),
5905 return VaListTypedefDecl;
5908 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5909 // typedef int __builtin_va_list[4];
5910 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5911 QualType IntArrayType
5912 = Context->getConstantArrayType(Context->IntTy,
5913 Size, ArrayType::Normal, 0);
5914 TypedefDecl *VaListTypedefDecl
5915 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 SourceLocation(), SourceLocation(),
5918 &Context->Idents.get("__builtin_va_list"),
5919 Context->getTrivialTypeSourceInfo(IntArrayType));
5921 return VaListTypedefDecl;
5924 static TypedefDecl *
5925 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5926 RecordDecl *VaListDecl;
5927 if (Context->getLangOpts().CPlusPlus) {
5928 // namespace std { struct __va_list {
5930 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5931 Context->getTranslationUnitDecl(),
5932 /*Inline*/false, SourceLocation(),
5933 SourceLocation(), &Context->Idents.get("std"),
5936 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5937 Context->getTranslationUnitDecl(),
5938 SourceLocation(), SourceLocation(),
5939 &Context->Idents.get("__va_list"));
5941 VaListDecl->setDeclContext(NS);
5944 // struct __va_list {
5945 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5946 Context->getTranslationUnitDecl(),
5947 &Context->Idents.get("__va_list"));
5950 VaListDecl->startDefinition();
5953 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5957 &Context->Idents.get("__ap"),
5958 Context->getPointerType(Context->VoidTy),
5963 Field->setAccess(AS_public);
5964 VaListDecl->addDecl(Field);
5967 VaListDecl->completeDefinition();
5969 // typedef struct __va_list __builtin_va_list;
5970 TypeSourceInfo *TInfo
5971 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5973 TypedefDecl *VaListTypeDecl
5974 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5975 Context->getTranslationUnitDecl(),
5976 SourceLocation(), SourceLocation(),
5977 &Context->Idents.get("__builtin_va_list"),
5980 return VaListTypeDecl;
5983 static TypedefDecl *
5984 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
5985 // typedef struct __va_list_tag {
5986 RecordDecl *VaListTagDecl;
5987 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5988 Context->getTranslationUnitDecl(),
5989 &Context->Idents.get("__va_list_tag"));
5990 VaListTagDecl->startDefinition();
5992 const size_t NumFields = 4;
5993 QualType FieldTypes[NumFields];
5994 const char *FieldNames[NumFields];
5997 FieldTypes[0] = Context->LongTy;
5998 FieldNames[0] = "__gpr";
6001 FieldTypes[1] = Context->LongTy;
6002 FieldNames[1] = "__fpr";
6004 // void *__overflow_arg_area;
6005 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6006 FieldNames[2] = "__overflow_arg_area";
6008 // void *__reg_save_area;
6009 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6010 FieldNames[3] = "__reg_save_area";
6013 for (unsigned i = 0; i < NumFields; ++i) {
6014 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6018 &Context->Idents.get(FieldNames[i]),
6019 FieldTypes[i], /*TInfo=*/0,
6023 Field->setAccess(AS_public);
6024 VaListTagDecl->addDecl(Field);
6026 VaListTagDecl->completeDefinition();
6027 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6028 Context->VaListTagTy = VaListTagType;
6031 TypedefDecl *VaListTagTypedefDecl
6032 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6033 Context->getTranslationUnitDecl(),
6034 SourceLocation(), SourceLocation(),
6035 &Context->Idents.get("__va_list_tag"),
6036 Context->getTrivialTypeSourceInfo(VaListTagType));
6037 QualType VaListTagTypedefType =
6038 Context->getTypedefType(VaListTagTypedefDecl);
6040 // typedef __va_list_tag __builtin_va_list[1];
6041 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6042 QualType VaListTagArrayType
6043 = Context->getConstantArrayType(VaListTagTypedefType,
6044 Size, ArrayType::Normal,0);
6045 TypeSourceInfo *TInfo
6046 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6047 TypedefDecl *VaListTypedefDecl
6048 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6049 Context->getTranslationUnitDecl(),
6050 SourceLocation(), SourceLocation(),
6051 &Context->Idents.get("__builtin_va_list"),
6054 return VaListTypedefDecl;
6057 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6058 TargetInfo::BuiltinVaListKind Kind) {
6060 case TargetInfo::CharPtrBuiltinVaList:
6061 return CreateCharPtrBuiltinVaListDecl(Context);
6062 case TargetInfo::VoidPtrBuiltinVaList:
6063 return CreateVoidPtrBuiltinVaListDecl(Context);
6064 case TargetInfo::AArch64ABIBuiltinVaList:
6065 return CreateAArch64ABIBuiltinVaListDecl(Context);
6066 case TargetInfo::PowerABIBuiltinVaList:
6067 return CreatePowerABIBuiltinVaListDecl(Context);
6068 case TargetInfo::X86_64ABIBuiltinVaList:
6069 return CreateX86_64ABIBuiltinVaListDecl(Context);
6070 case TargetInfo::PNaClABIBuiltinVaList:
6071 return CreatePNaClABIBuiltinVaListDecl(Context);
6072 case TargetInfo::AAPCSABIBuiltinVaList:
6073 return CreateAAPCSABIBuiltinVaListDecl(Context);
6074 case TargetInfo::SystemZBuiltinVaList:
6075 return CreateSystemZBuiltinVaListDecl(Context);
6078 llvm_unreachable("Unhandled __builtin_va_list type kind");
6081 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6082 if (!BuiltinVaListDecl)
6083 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6085 return BuiltinVaListDecl;
6088 QualType ASTContext::getVaListTagType() const {
6089 // Force the creation of VaListTagTy by building the __builtin_va_list
6091 if (VaListTagTy.isNull())
6092 (void) getBuiltinVaListDecl();
6097 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6098 assert(ObjCConstantStringType.isNull() &&
6099 "'NSConstantString' type already set!");
6101 ObjCConstantStringType = getObjCInterfaceType(Decl);
6104 /// \brief Retrieve the template name that corresponds to a non-empty
6107 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6108 UnresolvedSetIterator End) const {
6109 unsigned size = End - Begin;
6110 assert(size > 1 && "set is not overloaded!");
6112 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6113 size * sizeof(FunctionTemplateDecl*));
6114 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6116 NamedDecl **Storage = OT->getStorage();
6117 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6119 assert(isa<FunctionTemplateDecl>(D) ||
6120 (isa<UsingShadowDecl>(D) &&
6121 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6125 return TemplateName(OT);
6128 /// \brief Retrieve the template name that represents a qualified
6129 /// template name such as \c std::vector.
6131 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6132 bool TemplateKeyword,
6133 TemplateDecl *Template) const {
6134 assert(NNS && "Missing nested-name-specifier in qualified template name");
6136 // FIXME: Canonicalization?
6137 llvm::FoldingSetNodeID ID;
6138 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6140 void *InsertPos = 0;
6141 QualifiedTemplateName *QTN =
6142 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6144 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6145 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6146 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6149 return TemplateName(QTN);
6152 /// \brief Retrieve the template name that represents a dependent
6153 /// template name such as \c MetaFun::template apply.
6155 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6156 const IdentifierInfo *Name) const {
6157 assert((!NNS || NNS->isDependent()) &&
6158 "Nested name specifier must be dependent");
6160 llvm::FoldingSetNodeID ID;
6161 DependentTemplateName::Profile(ID, NNS, Name);
6163 void *InsertPos = 0;
6164 DependentTemplateName *QTN =
6165 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6168 return TemplateName(QTN);
6170 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6171 if (CanonNNS == NNS) {
6172 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6173 DependentTemplateName(NNS, Name);
6175 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6176 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6177 DependentTemplateName(NNS, Name, Canon);
6178 DependentTemplateName *CheckQTN =
6179 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6180 assert(!CheckQTN && "Dependent type name canonicalization broken");
6184 DependentTemplateNames.InsertNode(QTN, InsertPos);
6185 return TemplateName(QTN);
6188 /// \brief Retrieve the template name that represents a dependent
6189 /// template name such as \c MetaFun::template operator+.
6191 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6192 OverloadedOperatorKind Operator) const {
6193 assert((!NNS || NNS->isDependent()) &&
6194 "Nested name specifier must be dependent");
6196 llvm::FoldingSetNodeID ID;
6197 DependentTemplateName::Profile(ID, NNS, Operator);
6199 void *InsertPos = 0;
6200 DependentTemplateName *QTN
6201 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6204 return TemplateName(QTN);
6206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6207 if (CanonNNS == NNS) {
6208 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6209 DependentTemplateName(NNS, Operator);
6211 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Operator, Canon);
6215 DependentTemplateName *CheckQTN
6216 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6217 assert(!CheckQTN && "Dependent template name canonicalization broken");
6221 DependentTemplateNames.InsertNode(QTN, InsertPos);
6222 return TemplateName(QTN);
6226 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6227 TemplateName replacement) const {
6228 llvm::FoldingSetNodeID ID;
6229 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6231 void *insertPos = 0;
6232 SubstTemplateTemplateParmStorage *subst
6233 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6236 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6237 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6240 return TemplateName(subst);
6244 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6245 const TemplateArgument &ArgPack) const {
6246 ASTContext &Self = const_cast<ASTContext &>(*this);
6247 llvm::FoldingSetNodeID ID;
6248 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6250 void *InsertPos = 0;
6251 SubstTemplateTemplateParmPackStorage *Subst
6252 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6255 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6256 ArgPack.pack_size(),
6257 ArgPack.pack_begin());
6258 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6261 return TemplateName(Subst);
6264 /// getFromTargetType - Given one of the integer types provided by
6265 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6266 /// is actually a value of type @c TargetInfo::IntType.
6267 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6269 case TargetInfo::NoInt: return CanQualType();
6270 case TargetInfo::SignedShort: return ShortTy;
6271 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6272 case TargetInfo::SignedInt: return IntTy;
6273 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6274 case TargetInfo::SignedLong: return LongTy;
6275 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6276 case TargetInfo::SignedLongLong: return LongLongTy;
6277 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6280 llvm_unreachable("Unhandled TargetInfo::IntType value");
6283 //===----------------------------------------------------------------------===//
6285 //===----------------------------------------------------------------------===//
6287 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6288 /// garbage collection attribute.
6290 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6291 if (getLangOpts().getGC() == LangOptions::NonGC)
6292 return Qualifiers::GCNone;
6294 assert(getLangOpts().ObjC1);
6295 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6297 // Default behaviour under objective-C's gc is for ObjC pointers
6298 // (or pointers to them) be treated as though they were declared
6300 if (GCAttrs == Qualifiers::GCNone) {
6301 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6302 return Qualifiers::Strong;
6303 else if (Ty->isPointerType())
6304 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6306 // It's not valid to set GC attributes on anything that isn't a
6309 QualType CT = Ty->getCanonicalTypeInternal();
6310 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6311 CT = AT->getElementType();
6312 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6318 //===----------------------------------------------------------------------===//
6319 // Type Compatibility Testing
6320 //===----------------------------------------------------------------------===//
6322 /// areCompatVectorTypes - Return true if the two specified vector types are
6324 static bool areCompatVectorTypes(const VectorType *LHS,
6325 const VectorType *RHS) {
6326 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6327 return LHS->getElementType() == RHS->getElementType() &&
6328 LHS->getNumElements() == RHS->getNumElements();
6331 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6332 QualType SecondVec) {
6333 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6334 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6336 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6339 // Treat Neon vector types and most AltiVec vector types as if they are the
6340 // equivalent GCC vector types.
6341 const VectorType *First = FirstVec->getAs<VectorType>();
6342 const VectorType *Second = SecondVec->getAs<VectorType>();
6343 if (First->getNumElements() == Second->getNumElements() &&
6344 hasSameType(First->getElementType(), Second->getElementType()) &&
6345 First->getVectorKind() != VectorType::AltiVecPixel &&
6346 First->getVectorKind() != VectorType::AltiVecBool &&
6347 Second->getVectorKind() != VectorType::AltiVecPixel &&
6348 Second->getVectorKind() != VectorType::AltiVecBool)
6354 //===----------------------------------------------------------------------===//
6355 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6356 //===----------------------------------------------------------------------===//
6358 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6359 /// inheritance hierarchy of 'rProto'.
6361 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6362 ObjCProtocolDecl *rProto) const {
6363 if (declaresSameEntity(lProto, rProto))
6365 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6366 E = rProto->protocol_end(); PI != E; ++PI)
6367 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6372 /// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
6373 /// return true if lhs's protocols conform to rhs's protocol; false
6375 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6376 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6377 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6381 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6382 /// Class<pr1, ...>.
6383 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6385 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6386 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6387 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6389 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6390 E = lhsQID->qual_end(); I != E; ++I) {
6392 ObjCProtocolDecl *lhsProto = *I;
6393 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6394 E = rhsOPT->qual_end(); J != E; ++J) {
6395 ObjCProtocolDecl *rhsProto = *J;
6396 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6407 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6408 /// ObjCQualifiedIDType.
6409 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6411 // Allow id<P..> and an 'id' or void* type in all cases.
6412 if (lhs->isVoidPointerType() ||
6413 lhs->isObjCIdType() || lhs->isObjCClassType())
6415 else if (rhs->isVoidPointerType() ||
6416 rhs->isObjCIdType() || rhs->isObjCClassType())
6419 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6420 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6422 if (!rhsOPT) return false;
6424 if (rhsOPT->qual_empty()) {
6425 // If the RHS is a unqualified interface pointer "NSString*",
6426 // make sure we check the class hierarchy.
6427 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6428 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6429 E = lhsQID->qual_end(); I != E; ++I) {
6430 // when comparing an id<P> on lhs with a static type on rhs,
6431 // see if static class implements all of id's protocols, directly or
6432 // through its super class and categories.
6433 if (!rhsID->ClassImplementsProtocol(*I, true))
6437 // If there are no qualifiers and no interface, we have an 'id'.
6440 // Both the right and left sides have qualifiers.
6441 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6442 E = lhsQID->qual_end(); I != E; ++I) {
6443 ObjCProtocolDecl *lhsProto = *I;
6446 // when comparing an id<P> on lhs with a static type on rhs,
6447 // see if static class implements all of id's protocols, directly or
6448 // through its super class and categories.
6449 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6450 E = rhsOPT->qual_end(); J != E; ++J) {
6451 ObjCProtocolDecl *rhsProto = *J;
6452 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6453 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6458 // If the RHS is a qualified interface pointer "NSString<P>*",
6459 // make sure we check the class hierarchy.
6460 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6461 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6462 E = lhsQID->qual_end(); I != E; ++I) {
6463 // when comparing an id<P> on lhs with a static type on rhs,
6464 // see if static class implements all of id's protocols, directly or
6465 // through its super class and categories.
6466 if (rhsID->ClassImplementsProtocol(*I, true)) {
6479 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6480 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6482 if (const ObjCObjectPointerType *lhsOPT =
6483 lhs->getAsObjCInterfacePointerType()) {
6484 // If both the right and left sides have qualifiers.
6485 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6486 E = lhsOPT->qual_end(); I != E; ++I) {
6487 ObjCProtocolDecl *lhsProto = *I;
6490 // when comparing an id<P> on rhs with a static type on lhs,
6491 // see if static class implements all of id's protocols, directly or
6492 // through its super class and categories.
6493 // First, lhs protocols in the qualifier list must be found, direct
6494 // or indirect in rhs's qualifier list or it is a mismatch.
6495 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6496 E = rhsQID->qual_end(); J != E; ++J) {
6497 ObjCProtocolDecl *rhsProto = *J;
6498 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6499 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6508 // Static class's protocols, or its super class or category protocols
6509 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6510 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6511 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6512 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6513 // This is rather dubious but matches gcc's behavior. If lhs has
6514 // no type qualifier and its class has no static protocol(s)
6515 // assume that it is mismatch.
6516 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6518 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6519 LHSInheritedProtocols.begin(),
6520 E = LHSInheritedProtocols.end(); I != E; ++I) {
6522 ObjCProtocolDecl *lhsProto = (*I);
6523 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6524 E = rhsQID->qual_end(); J != E; ++J) {
6525 ObjCProtocolDecl *rhsProto = *J;
6526 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6527 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6541 /// canAssignObjCInterfaces - Return true if the two interface types are
6542 /// compatible for assignment from RHS to LHS. This handles validation of any
6543 /// protocol qualifiers on the LHS or RHS.
6545 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6546 const ObjCObjectPointerType *RHSOPT) {
6547 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6548 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6550 // If either type represents the built-in 'id' or 'Class' types, return true.
6551 if (LHS->isObjCUnqualifiedIdOrClass() ||
6552 RHS->isObjCUnqualifiedIdOrClass())
6555 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6556 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6560 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6561 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6562 QualType(RHSOPT,0));
6564 // If we have 2 user-defined types, fall into that path.
6565 if (LHS->getInterface() && RHS->getInterface())
6566 return canAssignObjCInterfaces(LHS, RHS);
6571 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6572 /// for providing type-safety for objective-c pointers used to pass/return
6573 /// arguments in block literals. When passed as arguments, passing 'A*' where
6574 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6575 /// not OK. For the return type, the opposite is not OK.
6576 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6577 const ObjCObjectPointerType *LHSOPT,
6578 const ObjCObjectPointerType *RHSOPT,
6579 bool BlockReturnType) {
6580 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6583 if (LHSOPT->isObjCBuiltinType()) {
6584 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6587 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6588 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6592 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6593 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6594 if (LHS && RHS) { // We have 2 user-defined types.
6596 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6597 return BlockReturnType;
6598 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6599 return !BlockReturnType;
6607 /// getIntersectionOfProtocols - This routine finds the intersection of set
6608 /// of protocols inherited from two distinct objective-c pointer objects.
6609 /// It is used to build composite qualifier list of the composite type of
6610 /// the conditional expression involving two objective-c pointer objects.
6612 void getIntersectionOfProtocols(ASTContext &Context,
6613 const ObjCObjectPointerType *LHSOPT,
6614 const ObjCObjectPointerType *RHSOPT,
6615 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6617 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6618 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6619 assert(LHS->getInterface() && "LHS must have an interface base");
6620 assert(RHS->getInterface() && "RHS must have an interface base");
6622 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6623 unsigned LHSNumProtocols = LHS->getNumProtocols();
6624 if (LHSNumProtocols > 0)
6625 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6627 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6628 Context.CollectInheritedProtocols(LHS->getInterface(),
6629 LHSInheritedProtocols);
6630 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6631 LHSInheritedProtocols.end());
6634 unsigned RHSNumProtocols = RHS->getNumProtocols();
6635 if (RHSNumProtocols > 0) {
6636 ObjCProtocolDecl **RHSProtocols =
6637 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6638 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6639 if (InheritedProtocolSet.count(RHSProtocols[i]))
6640 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6642 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6643 Context.CollectInheritedProtocols(RHS->getInterface(),
6644 RHSInheritedProtocols);
6645 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6646 RHSInheritedProtocols.begin(),
6647 E = RHSInheritedProtocols.end(); I != E; ++I)
6648 if (InheritedProtocolSet.count((*I)))
6649 IntersectionOfProtocols.push_back((*I));
6653 /// areCommonBaseCompatible - Returns common base class of the two classes if
6654 /// one found. Note that this is O'2 algorithm. But it will be called as the
6655 /// last type comparison in a ?-exp of ObjC pointer types before a
6656 /// warning is issued. So, its invokation is extremely rare.
6657 QualType ASTContext::areCommonBaseCompatible(
6658 const ObjCObjectPointerType *Lptr,
6659 const ObjCObjectPointerType *Rptr) {
6660 const ObjCObjectType *LHS = Lptr->getObjectType();
6661 const ObjCObjectType *RHS = Rptr->getObjectType();
6662 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6663 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6664 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6668 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6669 if (canAssignObjCInterfaces(LHS, RHS)) {
6670 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6671 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6673 QualType Result = QualType(LHS, 0);
6674 if (!Protocols.empty())
6675 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6676 Result = getObjCObjectPointerType(Result);
6679 } while ((LDecl = LDecl->getSuperClass()));
6684 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6685 const ObjCObjectType *RHS) {
6686 assert(LHS->getInterface() && "LHS is not an interface type");
6687 assert(RHS->getInterface() && "RHS is not an interface type");
6689 // Verify that the base decls are compatible: the RHS must be a subclass of
6691 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6694 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6695 // protocol qualified at all, then we are good.
6696 if (LHS->getNumProtocols() == 0)
6699 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6700 // more detailed analysis is required.
6701 if (RHS->getNumProtocols() == 0) {
6702 // OK, if LHS is a superclass of RHS *and*
6703 // this superclass is assignment compatible with LHS.
6706 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6708 // OK if conversion of LHS to SuperClass results in narrowing of types
6709 // ; i.e., SuperClass may implement at least one of the protocols
6710 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6711 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6712 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6713 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6714 // If super class has no protocols, it is not a match.
6715 if (SuperClassInheritedProtocols.empty())
6718 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6719 LHSPE = LHS->qual_end();
6720 LHSPI != LHSPE; LHSPI++) {
6721 bool SuperImplementsProtocol = false;
6722 ObjCProtocolDecl *LHSProto = (*LHSPI);
6724 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6725 SuperClassInheritedProtocols.begin(),
6726 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6727 ObjCProtocolDecl *SuperClassProto = (*I);
6728 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6729 SuperImplementsProtocol = true;
6733 if (!SuperImplementsProtocol)
6741 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6742 LHSPE = LHS->qual_end();
6743 LHSPI != LHSPE; LHSPI++) {
6744 bool RHSImplementsProtocol = false;
6746 // If the RHS doesn't implement the protocol on the left, the types
6747 // are incompatible.
6748 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6749 RHSPE = RHS->qual_end();
6750 RHSPI != RHSPE; RHSPI++) {
6751 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
6752 RHSImplementsProtocol = true;
6756 // FIXME: For better diagnostics, consider passing back the protocol name.
6757 if (!RHSImplementsProtocol)
6760 // The RHS implements all protocols listed on the LHS.
6764 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6765 // get the "pointed to" types
6766 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6767 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6769 if (!LHSOPT || !RHSOPT)
6772 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6773 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6776 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6777 return canAssignObjCInterfaces(
6778 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6779 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6782 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6783 /// both shall have the identically qualified version of a compatible type.
6784 /// C99 6.2.7p1: Two types have compatible types if their types are the
6785 /// same. See 6.7.[2,3,5] for additional rules.
6786 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6787 bool CompareUnqualified) {
6788 if (getLangOpts().CPlusPlus)
6789 return hasSameType(LHS, RHS);
6791 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6794 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6795 return typesAreCompatible(LHS, RHS);
6798 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6799 return !mergeTypes(LHS, RHS, true).isNull();
6802 /// mergeTransparentUnionType - if T is a transparent union type and a member
6803 /// of T is compatible with SubType, return the merged type, else return
6805 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6806 bool OfBlockPointer,
6808 if (const RecordType *UT = T->getAsUnionType()) {
6809 RecordDecl *UD = UT->getDecl();
6810 if (UD->hasAttr<TransparentUnionAttr>()) {
6811 for (RecordDecl::field_iterator it = UD->field_begin(),
6812 itend = UD->field_end(); it != itend; ++it) {
6813 QualType ET = it->getType().getUnqualifiedType();
6814 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6824 /// mergeFunctionArgumentTypes - merge two types which appear as function
6826 QualType ASTContext::mergeFunctionArgumentTypes(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->getResultType();
6859 QualType LHS = lbase->getResultType();
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->getResultType(), rbase->getResultType(), false,
6868 if (retType.isNull()) return QualType();
6871 retType = retType.getUnqualifiedType();
6873 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6874 CanQualType RRetType = getCanonicalType(rbase->getResultType());
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 (!isSameCallConv(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 unsigned lproto_nargs = lproto->getNumArgs();
6919 unsigned rproto_nargs = rproto->getNumArgs();
6921 // Compatible functions must have the same number of arguments
6922 if (lproto_nargs != rproto_nargs)
6925 // Variadic and non-variadic functions aren't compatible
6926 if (lproto->isVariadic() != rproto->isVariadic())
6929 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6932 if (LangOpts.ObjCAutoRefCount &&
6933 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6936 // Check argument compatibility
6937 SmallVector<QualType, 10> types;
6938 for (unsigned i = 0; i < lproto_nargs; i++) {
6939 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6940 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
6941 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6944 if (argtype.isNull()) return QualType();
6947 argtype = argtype.getUnqualifiedType();
6949 types.push_back(argtype);
6951 largtype = largtype.getUnqualifiedType();
6952 rargtype = rargtype.getUnqualifiedType();
6955 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6957 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6961 if (allLTypes) return lhs;
6962 if (allRTypes) return rhs;
6964 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6965 EPI.ExtInfo = einfo;
6966 return getFunctionType(retType, types, EPI);
6969 if (lproto) allRTypes = false;
6970 if (rproto) allLTypes = false;
6972 const FunctionProtoType *proto = lproto ? lproto : rproto;
6974 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
6975 if (proto->isVariadic()) return QualType();
6976 // Check that the types are compatible with the types that
6977 // would result from default argument promotions (C99 6.7.5.3p15).
6978 // The only types actually affected are promotable integer
6979 // types and floats, which would be passed as a different
6980 // type depending on whether the prototype is visible.
6981 unsigned proto_nargs = proto->getNumArgs();
6982 for (unsigned i = 0; i < proto_nargs; ++i) {
6983 QualType argTy = proto->getArgType(i);
6985 // Look at the converted type of enum types, since that is the type used
6986 // to pass enum values.
6987 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6988 argTy = Enum->getDecl()->getIntegerType();
6993 if (argTy->isPromotableIntegerType() ||
6994 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6998 if (allLTypes) return lhs;
6999 if (allRTypes) return rhs;
7001 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7002 EPI.ExtInfo = einfo;
7003 return getFunctionType(retType,
7004 ArrayRef<QualType>(proto->arg_type_begin(),
7005 proto->getNumArgs()),
7009 if (allLTypes) return lhs;
7010 if (allRTypes) return rhs;
7011 return getFunctionNoProtoType(retType, einfo);
7014 /// Given that we have an enum type and a non-enum type, try to merge them.
7015 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7016 QualType other, bool isBlockReturnType) {
7017 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7018 // a signed integer type, or an unsigned integer type.
7019 // Compatibility is based on the underlying type, not the promotion
7021 QualType underlyingType = ET->getDecl()->getIntegerType();
7022 if (underlyingType.isNull()) return QualType();
7023 if (Context.hasSameType(underlyingType, other))
7026 // In block return types, we're more permissive and accept any
7027 // integral type of the same size.
7028 if (isBlockReturnType && other->isIntegerType() &&
7029 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7035 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7036 bool OfBlockPointer,
7037 bool Unqualified, bool BlockReturnType) {
7038 // C++ [expr]: If an expression initially has the type "reference to T", the
7039 // type is adjusted to "T" prior to any further analysis, the expression
7040 // designates the object or function denoted by the reference, and the
7041 // expression is an lvalue unless the reference is an rvalue reference and
7042 // the expression is a function call (possibly inside parentheses).
7043 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7044 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7047 LHS = LHS.getUnqualifiedType();
7048 RHS = RHS.getUnqualifiedType();
7051 QualType LHSCan = getCanonicalType(LHS),
7052 RHSCan = getCanonicalType(RHS);
7054 // If two types are identical, they are compatible.
7055 if (LHSCan == RHSCan)
7058 // If the qualifiers are different, the types aren't compatible... mostly.
7059 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7060 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7061 if (LQuals != RQuals) {
7062 // If any of these qualifiers are different, we have a type
7064 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7065 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7066 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7069 // Exactly one GC qualifier difference is allowed: __strong is
7070 // okay if the other type has no GC qualifier but is an Objective
7071 // C object pointer (i.e. implicitly strong by default). We fix
7072 // this by pretending that the unqualified type was actually
7073 // qualified __strong.
7074 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7075 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7076 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7078 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7081 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7082 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7084 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7085 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7090 // Okay, qualifiers are equal.
7092 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7093 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7095 // We want to consider the two function types to be the same for these
7096 // comparisons, just force one to the other.
7097 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7098 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7100 // Same as above for arrays
7101 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7102 LHSClass = Type::ConstantArray;
7103 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7104 RHSClass = Type::ConstantArray;
7106 // ObjCInterfaces are just specialized ObjCObjects.
7107 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7108 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7110 // Canonicalize ExtVector -> Vector.
7111 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7112 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7114 // If the canonical type classes don't match.
7115 if (LHSClass != RHSClass) {
7116 // Note that we only have special rules for turning block enum
7117 // returns into block int returns, not vice-versa.
7118 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7119 return mergeEnumWithInteger(*this, ETy, RHS, false);
7121 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7122 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7124 // allow block pointer type to match an 'id' type.
7125 if (OfBlockPointer && !BlockReturnType) {
7126 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7128 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7135 // The canonical type classes match.
7137 #define TYPE(Class, Base)
7138 #define ABSTRACT_TYPE(Class, Base)
7139 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7140 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7141 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7142 #include "clang/AST/TypeNodes.def"
7143 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7146 case Type::LValueReference:
7147 case Type::RValueReference:
7148 case Type::MemberPointer:
7149 llvm_unreachable("C++ should never be in mergeTypes");
7151 case Type::ObjCInterface:
7152 case Type::IncompleteArray:
7153 case Type::VariableArray:
7154 case Type::FunctionProto:
7155 case Type::ExtVector:
7156 llvm_unreachable("Types are eliminated above");
7160 // Merge two pointer types, while trying to preserve typedef info
7161 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7162 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7164 LHSPointee = LHSPointee.getUnqualifiedType();
7165 RHSPointee = RHSPointee.getUnqualifiedType();
7167 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7169 if (ResultType.isNull()) return QualType();
7170 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7172 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7174 return getPointerType(ResultType);
7176 case Type::BlockPointer:
7178 // Merge two block pointer types, while trying to preserve typedef info
7179 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7180 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7182 LHSPointee = LHSPointee.getUnqualifiedType();
7183 RHSPointee = RHSPointee.getUnqualifiedType();
7185 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7187 if (ResultType.isNull()) return QualType();
7188 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7190 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7192 return getBlockPointerType(ResultType);
7196 // Merge two pointer types, while trying to preserve typedef info
7197 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7198 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7200 LHSValue = LHSValue.getUnqualifiedType();
7201 RHSValue = RHSValue.getUnqualifiedType();
7203 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7205 if (ResultType.isNull()) return QualType();
7206 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7208 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7210 return getAtomicType(ResultType);
7212 case Type::ConstantArray:
7214 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7215 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7216 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7219 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7220 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7222 LHSElem = LHSElem.getUnqualifiedType();
7223 RHSElem = RHSElem.getUnqualifiedType();
7226 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7227 if (ResultType.isNull()) return QualType();
7228 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7230 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7232 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7233 ArrayType::ArraySizeModifier(), 0);
7234 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7235 ArrayType::ArraySizeModifier(), 0);
7236 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7237 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7238 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7240 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7243 // FIXME: This isn't correct! But tricky to implement because
7244 // the array's size has to be the size of LHS, but the type
7245 // has to be different.
7249 // FIXME: This isn't correct! But tricky to implement because
7250 // the array's size has to be the size of RHS, but the type
7251 // has to be different.
7254 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7255 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7256 return getIncompleteArrayType(ResultType,
7257 ArrayType::ArraySizeModifier(), 0);
7259 case Type::FunctionNoProto:
7260 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7265 // Only exactly equal builtin types are compatible, which is tested above.
7268 // Distinct complex types are incompatible.
7271 // FIXME: The merged type should be an ExtVector!
7272 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7273 RHSCan->getAs<VectorType>()))
7276 case Type::ObjCObject: {
7277 // Check if the types are assignment compatible.
7278 // FIXME: This should be type compatibility, e.g. whether
7279 // "LHS x; RHS x;" at global scope is legal.
7280 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7281 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7282 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7287 case Type::ObjCObjectPointer: {
7288 if (OfBlockPointer) {
7289 if (canAssignObjCInterfacesInBlockPointer(
7290 LHS->getAs<ObjCObjectPointerType>(),
7291 RHS->getAs<ObjCObjectPointerType>(),
7296 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7297 RHS->getAs<ObjCObjectPointerType>()))
7304 llvm_unreachable("Invalid Type::Class!");
7307 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7308 const FunctionProtoType *FromFunctionType,
7309 const FunctionProtoType *ToFunctionType) {
7310 if (FromFunctionType->hasAnyConsumedArgs() !=
7311 ToFunctionType->hasAnyConsumedArgs())
7313 FunctionProtoType::ExtProtoInfo FromEPI =
7314 FromFunctionType->getExtProtoInfo();
7315 FunctionProtoType::ExtProtoInfo ToEPI =
7316 ToFunctionType->getExtProtoInfo();
7317 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7319 ArgIdx != NumArgs; ++ArgIdx) {
7320 if (FromEPI.ConsumedArguments[ArgIdx] !=
7321 ToEPI.ConsumedArguments[ArgIdx])
7327 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7328 /// 'RHS' attributes and returns the merged version; including for function
7330 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7331 QualType LHSCan = getCanonicalType(LHS),
7332 RHSCan = getCanonicalType(RHS);
7333 // If two types are identical, they are compatible.
7334 if (LHSCan == RHSCan)
7336 if (RHSCan->isFunctionType()) {
7337 if (!LHSCan->isFunctionType())
7339 QualType OldReturnType =
7340 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7341 QualType NewReturnType =
7342 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7343 QualType ResReturnType =
7344 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7345 if (ResReturnType.isNull())
7347 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7348 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7349 // In either case, use OldReturnType to build the new function type.
7350 const FunctionType *F = LHS->getAs<FunctionType>();
7351 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7352 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7353 EPI.ExtInfo = getFunctionExtInfo(LHS);
7355 = getFunctionType(OldReturnType,
7356 ArrayRef<QualType>(FPT->arg_type_begin(),
7365 // If the qualifiers are different, the types can still be merged.
7366 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7367 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7368 if (LQuals != RQuals) {
7369 // If any of these qualifiers are different, we have a type mismatch.
7370 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7371 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7374 // Exactly one GC qualifier difference is allowed: __strong is
7375 // okay if the other type has no GC qualifier but is an Objective
7376 // C object pointer (i.e. implicitly strong by default). We fix
7377 // this by pretending that the unqualified type was actually
7378 // qualified __strong.
7379 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7380 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7381 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7383 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7386 if (GC_L == Qualifiers::Strong)
7388 if (GC_R == Qualifiers::Strong)
7393 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7394 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7395 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7396 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7397 if (ResQT == LHSBaseQT)
7399 if (ResQT == RHSBaseQT)
7405 //===----------------------------------------------------------------------===//
7406 // Integer Predicates
7407 //===----------------------------------------------------------------------===//
7409 unsigned ASTContext::getIntWidth(QualType T) const {
7410 if (const EnumType *ET = dyn_cast<EnumType>(T))
7411 T = ET->getDecl()->getIntegerType();
7412 if (T->isBooleanType())
7414 // For builtin types, just use the standard type sizing method
7415 return (unsigned)getTypeSize(T);
7418 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7419 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7421 // Turn <4 x signed int> -> <4 x unsigned int>
7422 if (const VectorType *VTy = T->getAs<VectorType>())
7423 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7424 VTy->getNumElements(), VTy->getVectorKind());
7426 // For enums, we return the unsigned version of the base type.
7427 if (const EnumType *ETy = T->getAs<EnumType>())
7428 T = ETy->getDecl()->getIntegerType();
7430 const BuiltinType *BTy = T->getAs<BuiltinType>();
7431 assert(BTy && "Unexpected signed integer type");
7432 switch (BTy->getKind()) {
7433 case BuiltinType::Char_S:
7434 case BuiltinType::SChar:
7435 return UnsignedCharTy;
7436 case BuiltinType::Short:
7437 return UnsignedShortTy;
7438 case BuiltinType::Int:
7439 return UnsignedIntTy;
7440 case BuiltinType::Long:
7441 return UnsignedLongTy;
7442 case BuiltinType::LongLong:
7443 return UnsignedLongLongTy;
7444 case BuiltinType::Int128:
7445 return UnsignedInt128Ty;
7447 llvm_unreachable("Unexpected signed integer type");
7451 ASTMutationListener::~ASTMutationListener() { }
7454 //===----------------------------------------------------------------------===//
7455 // Builtin Type Computation
7456 //===----------------------------------------------------------------------===//
7458 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7459 /// pointer over the consumed characters. This returns the resultant type. If
7460 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7461 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7462 /// a vector of "i*".
7464 /// RequiresICE is filled in on return to indicate whether the value is required
7465 /// to be an Integer Constant Expression.
7466 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7467 ASTContext::GetBuiltinTypeError &Error,
7469 bool AllowTypeModifiers) {
7472 bool Signed = false, Unsigned = false;
7473 RequiresICE = false;
7475 // Read the prefixed modifiers first.
7479 default: Done = true; --Str; break;
7484 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7485 assert(!Signed && "Can't use 'S' modifier multiple times!");
7489 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7490 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7494 assert(HowLong <= 2 && "Can't have LLLL modifier");
7502 // Read the base type.
7504 default: llvm_unreachable("Unknown builtin type letter!");
7506 assert(HowLong == 0 && !Signed && !Unsigned &&
7507 "Bad modifiers used with 'v'!");
7508 Type = Context.VoidTy;
7511 assert(HowLong == 0 && !Signed && !Unsigned &&
7512 "Bad modifiers used with 'f'!");
7513 Type = Context.FloatTy;
7516 assert(HowLong < 2 && !Signed && !Unsigned &&
7517 "Bad modifiers used with 'd'!");
7519 Type = Context.LongDoubleTy;
7521 Type = Context.DoubleTy;
7524 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7526 Type = Context.UnsignedShortTy;
7528 Type = Context.ShortTy;
7532 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7533 else if (HowLong == 2)
7534 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7535 else if (HowLong == 1)
7536 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7538 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7541 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7543 Type = Context.SignedCharTy;
7545 Type = Context.UnsignedCharTy;
7547 Type = Context.CharTy;
7549 case 'b': // boolean
7550 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7551 Type = Context.BoolTy;
7553 case 'z': // size_t.
7554 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7555 Type = Context.getSizeType();
7558 Type = Context.getCFConstantStringType();
7561 Type = Context.getObjCIdType();
7564 Type = Context.getObjCSelType();
7567 Type = Context.getObjCSuperType();
7570 Type = Context.getBuiltinVaListType();
7571 assert(!Type.isNull() && "builtin va list type not initialized!");
7574 // This is a "reference" to a va_list; however, what exactly
7575 // this means depends on how va_list is defined. There are two
7576 // different kinds of va_list: ones passed by value, and ones
7577 // passed by reference. An example of a by-value va_list is
7578 // x86, where va_list is a char*. An example of by-ref va_list
7579 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7580 // we want this argument to be a char*&; for x86-64, we want
7581 // it to be a __va_list_tag*.
7582 Type = Context.getBuiltinVaListType();
7583 assert(!Type.isNull() && "builtin va list type not initialized!");
7584 if (Type->isArrayType())
7585 Type = Context.getArrayDecayedType(Type);
7587 Type = Context.getLValueReferenceType(Type);
7591 unsigned NumElements = strtoul(Str, &End, 10);
7592 assert(End != Str && "Missing vector size");
7595 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7596 RequiresICE, false);
7597 assert(!RequiresICE && "Can't require vector ICE");
7599 // TODO: No way to make AltiVec vectors in builtins yet.
7600 Type = Context.getVectorType(ElementType, NumElements,
7601 VectorType::GenericVector);
7607 unsigned NumElements = strtoul(Str, &End, 10);
7608 assert(End != Str && "Missing vector size");
7612 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7614 Type = Context.getExtVectorType(ElementType, NumElements);
7618 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7620 assert(!RequiresICE && "Can't require complex ICE");
7621 Type = Context.getComplexType(ElementType);
7625 Type = Context.getPointerDiffType();
7629 Type = Context.getFILEType();
7630 if (Type.isNull()) {
7631 Error = ASTContext::GE_Missing_stdio;
7637 Type = Context.getsigjmp_bufType();
7639 Type = Context.getjmp_bufType();
7641 if (Type.isNull()) {
7642 Error = ASTContext::GE_Missing_setjmp;
7647 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7648 Type = Context.getucontext_tType();
7650 if (Type.isNull()) {
7651 Error = ASTContext::GE_Missing_ucontext;
7656 Type = Context.getProcessIDType();
7660 // If there are modifiers and if we're allowed to parse them, go for it.
7661 Done = !AllowTypeModifiers;
7663 switch (char c = *Str++) {
7664 default: Done = true; --Str; break;
7667 // Both pointers and references can have their pointee types
7668 // qualified with an address space.
7670 unsigned AddrSpace = strtoul(Str, &End, 10);
7671 if (End != Str && AddrSpace != 0) {
7672 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7676 Type = Context.getPointerType(Type);
7678 Type = Context.getLValueReferenceType(Type);
7681 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7683 Type = Type.withConst();
7686 Type = Context.getVolatileType(Type);
7689 Type = Type.withRestrict();
7694 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7695 "Integer constant 'I' type must be an integer");
7700 /// GetBuiltinType - Return the type for the specified builtin.
7701 QualType ASTContext::GetBuiltinType(unsigned Id,
7702 GetBuiltinTypeError &Error,
7703 unsigned *IntegerConstantArgs) const {
7704 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7706 SmallVector<QualType, 8> ArgTypes;
7708 bool RequiresICE = false;
7710 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7712 if (Error != GE_None)
7715 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7717 while (TypeStr[0] && TypeStr[0] != '.') {
7718 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7719 if (Error != GE_None)
7722 // If this argument is required to be an IntegerConstantExpression and the
7723 // caller cares, fill in the bitmask we return.
7724 if (RequiresICE && IntegerConstantArgs)
7725 *IntegerConstantArgs |= 1 << ArgTypes.size();
7727 // Do array -> pointer decay. The builtin should use the decayed type.
7728 if (Ty->isArrayType())
7729 Ty = getArrayDecayedType(Ty);
7731 ArgTypes.push_back(Ty);
7734 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7735 "'.' should only occur at end of builtin type list!");
7737 FunctionType::ExtInfo EI;
7738 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7740 bool Variadic = (TypeStr[0] == '.');
7742 // We really shouldn't be making a no-proto type here, especially in C++.
7743 if (ArgTypes.empty() && Variadic)
7744 return getFunctionNoProtoType(ResType, EI);
7746 FunctionProtoType::ExtProtoInfo EPI;
7748 EPI.Variadic = Variadic;
7750 return getFunctionType(ResType, ArgTypes, EPI);
7753 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7754 GVALinkage External = GVA_StrongExternal;
7756 Linkage L = FD->getLinkage();
7759 case InternalLinkage:
7760 case UniqueExternalLinkage:
7761 return GVA_Internal;
7763 case ExternalLinkage:
7764 switch (FD->getTemplateSpecializationKind()) {
7765 case TSK_Undeclared:
7766 case TSK_ExplicitSpecialization:
7767 External = GVA_StrongExternal;
7770 case TSK_ExplicitInstantiationDefinition:
7771 return GVA_ExplicitTemplateInstantiation;
7773 case TSK_ExplicitInstantiationDeclaration:
7774 case TSK_ImplicitInstantiation:
7775 External = GVA_TemplateInstantiation;
7780 if (!FD->isInlined())
7783 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
7784 // GNU or C99 inline semantics. Determine whether this symbol should be
7785 // externally visible.
7786 if (FD->isInlineDefinitionExternallyVisible())
7789 // C99 inline semantics, where the symbol is not externally visible.
7790 return GVA_C99Inline;
7793 // C++0x [temp.explicit]p9:
7794 // [ Note: The intent is that an inline function that is the subject of
7795 // an explicit instantiation declaration will still be implicitly
7796 // instantiated when used so that the body can be considered for
7797 // inlining, but that no out-of-line copy of the inline function would be
7798 // generated in the translation unit. -- end note ]
7799 if (FD->getTemplateSpecializationKind()
7800 == TSK_ExplicitInstantiationDeclaration)
7801 return GVA_C99Inline;
7803 return GVA_CXXInline;
7806 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7807 // If this is a static data member, compute the kind of template
7808 // specialization. Otherwise, this variable is not part of a
7810 TemplateSpecializationKind TSK = TSK_Undeclared;
7811 if (VD->isStaticDataMember())
7812 TSK = VD->getTemplateSpecializationKind();
7814 Linkage L = VD->getLinkage();
7818 case InternalLinkage:
7819 case UniqueExternalLinkage:
7820 return GVA_Internal;
7822 case ExternalLinkage:
7824 case TSK_Undeclared:
7825 case TSK_ExplicitSpecialization:
7826 return GVA_StrongExternal;
7828 case TSK_ExplicitInstantiationDeclaration:
7829 llvm_unreachable("Variable should not be instantiated");
7830 // Fall through to treat this like any other instantiation.
7832 case TSK_ExplicitInstantiationDefinition:
7833 return GVA_ExplicitTemplateInstantiation;
7835 case TSK_ImplicitInstantiation:
7836 return GVA_TemplateInstantiation;
7840 llvm_unreachable("Invalid Linkage!");
7843 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7844 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7845 if (!VD->isFileVarDecl())
7847 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7848 // We never need to emit an uninstantiated function template.
7849 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7854 // If this is a member of a class template, we do not need to emit it.
7855 if (D->getDeclContext()->isDependentContext())
7858 // Weak references don't produce any output by themselves.
7859 if (D->hasAttr<WeakRefAttr>())
7862 // Aliases and used decls are required.
7863 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7866 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7867 // Forward declarations aren't required.
7868 if (!FD->doesThisDeclarationHaveABody())
7869 return FD->doesDeclarationForceExternallyVisibleDefinition();
7871 // Constructors and destructors are required.
7872 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7875 // The key function for a class is required. This rule only comes
7876 // into play when inline functions can be key functions, though.
7877 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7878 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7879 const CXXRecordDecl *RD = MD->getParent();
7880 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7881 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7882 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7888 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7890 // static, static inline, always_inline, and extern inline functions can
7891 // always be deferred. Normal inline functions can be deferred in C99/C++.
7892 // Implicit template instantiations can also be deferred in C++.
7893 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
7894 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7899 const VarDecl *VD = cast<VarDecl>(D);
7900 assert(VD->isFileVarDecl() && "Expected file scoped var");
7902 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7905 // Variables that can be needed in other TUs are required.
7906 GVALinkage L = GetGVALinkageForVariable(VD);
7907 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7910 // Variables that have destruction with side-effects are required.
7911 if (VD->getType().isDestructedType())
7914 // Variables that have initialization with side-effects are required.
7915 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7921 CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
7922 // Pass through to the C++ ABI object
7923 return ABI->getDefaultMethodCallConv(isVariadic);
7926 CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7927 if (CC == CC_C && !LangOpts.MRTD &&
7928 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
7933 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7934 // Pass through to the C++ ABI object
7935 return ABI->isNearlyEmpty(RD);
7938 MangleContext *ASTContext::createMangleContext() {
7939 switch (Target->getCXXABI().getKind()) {
7940 case TargetCXXABI::GenericAArch64:
7941 case TargetCXXABI::GenericItanium:
7942 case TargetCXXABI::GenericARM:
7943 case TargetCXXABI::iOS:
7944 return createItaniumMangleContext(*this, getDiagnostics());
7945 case TargetCXXABI::Microsoft:
7946 return createMicrosoftMangleContext(*this, getDiagnostics());
7948 llvm_unreachable("Unsupported ABI");
7951 CXXABI::~CXXABI() {}
7953 size_t ASTContext::getSideTableAllocatedMemory() const {
7954 return ASTRecordLayouts.getMemorySize()
7955 + llvm::capacity_in_bytes(ObjCLayouts)
7956 + llvm::capacity_in_bytes(KeyFunctions)
7957 + llvm::capacity_in_bytes(ObjCImpls)
7958 + llvm::capacity_in_bytes(BlockVarCopyInits)
7959 + llvm::capacity_in_bytes(DeclAttrs)
7960 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7961 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7962 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7963 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7964 + llvm::capacity_in_bytes(OverriddenMethods)
7965 + llvm::capacity_in_bytes(Types)
7966 + llvm::capacity_in_bytes(VariableArrayTypes)
7967 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
7970 void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7971 // FIXME: This mangling should be applied to function local classes too
7972 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7973 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7976 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7977 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7978 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7981 int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7982 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7983 UnnamedMangleNumbers.find(Tag);
7984 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7987 unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7988 CXXRecordDecl *Lambda = CallOperator->getParent();
7989 return LambdaMangleContexts[Lambda->getDeclContext()]
7990 .getManglingNumber(CallOperator);
7994 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7995 ParamIndices[D] = index;
7998 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7999 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8000 assert(I != ParamIndices.end() &&
8001 "ParmIndices lacks entry set by ParmVarDecl");