1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Triple.h"
38 #include "llvm/Support/Capacity.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
43 using namespace clang;
45 unsigned ASTContext::NumImplicitDefaultConstructors;
46 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
47 unsigned ASTContext::NumImplicitCopyConstructors;
48 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
49 unsigned ASTContext::NumImplicitMoveConstructors;
50 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
51 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
53 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
55 unsigned ASTContext::NumImplicitDestructors;
56 unsigned ASTContext::NumImplicitDestructorsDeclared;
59 HalfRank, FloatRank, DoubleRank, LongDoubleRank
62 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
63 if (!CommentsLoaded && ExternalSource) {
64 ExternalSource->ReadComments();
65 CommentsLoaded = true;
70 // User can not attach documentation to implicit declarations.
74 // User can not attach documentation to implicit instantiations.
75 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->isStaticDataMember() &&
82 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
91 if (const ClassTemplateSpecializationDecl *CTSD =
92 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94 if (TSK == TSK_ImplicitInstantiation ||
95 TSK == TSK_Undeclared)
99 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
103 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // When tag declaration (but not definition!) is part of the
105 // decl-specifier-seq of some other declaration, it doesn't get comment
106 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
109 // TODO: handle comments for function parameters properly.
110 if (isa<ParmVarDecl>(D))
113 // TODO: we could look up template parameter documentation in the template
115 if (isa<TemplateTypeParmDecl>(D) ||
116 isa<NonTypeTemplateParmDecl>(D) ||
117 isa<TemplateTemplateParmDecl>(D))
120 ArrayRef<RawComment *> RawComments = Comments.getComments();
122 // If there are no comments anywhere, we won't find anything.
123 if (RawComments.empty())
126 // Find declaration location.
127 // For Objective-C declarations we generally don't expect to have multiple
128 // declarators, thus use declaration starting location as the "declaration
130 // For all other declarations multiple declarators are used quite frequently,
131 // so we use the location of the identifier as the "declaration location".
132 SourceLocation DeclLoc;
133 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
134 isa<ObjCPropertyDecl>(D) ||
135 isa<RedeclarableTemplateDecl>(D) ||
136 isa<ClassTemplateSpecializationDecl>(D))
137 DeclLoc = D->getLocStart();
139 DeclLoc = D->getLocation();
140 // If location of the typedef name is in a macro, it is because being
141 // declared via a macro. Try using declaration's starting location
142 // as the "declaration location".
143 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144 DeclLoc = D->getLocStart();
147 // If the declaration doesn't map directly to a location in a file, we
148 // can't find the comment.
149 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
152 // Find the comment that occurs just after this declaration.
153 ArrayRef<RawComment *>::iterator Comment;
155 // When searching for comments during parsing, the comment we are looking
156 // for is usually among the last two comments we parsed -- check them
158 RawComment CommentAtDeclLoc(
159 SourceMgr, SourceRange(DeclLoc), false,
160 LangOpts.CommentOpts.ParseAllComments);
161 BeforeThanCompare<RawComment> Compare(SourceMgr);
162 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164 if (!Found && RawComments.size() >= 2) {
166 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
170 Comment = MaybeBeforeDecl + 1;
171 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172 &CommentAtDeclLoc, Compare));
175 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176 &CommentAtDeclLoc, Compare);
180 // Decompose the location for the declaration and find the beginning of the
182 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
184 // First check whether we have a trailing comment.
185 if (Comment != RawComments.end() &&
186 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
187 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
188 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
189 std::pair<FileID, unsigned> CommentBeginDecomp
190 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
191 // Check that Doxygen trailing comment comes after the declaration, starts
192 // on the same line and in the same file as the declaration.
193 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196 CommentBeginDecomp.second)) {
201 // The comment just after the declaration was not a trailing comment.
202 // Let's look at the previous comment.
203 if (Comment == RawComments.begin())
207 // Check that we actually have a non-member Doxygen comment.
208 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
211 // Decompose the end of the comment.
212 std::pair<FileID, unsigned> CommentEndDecomp
213 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
215 // If the comment and the declaration aren't in the same file, then they
217 if (DeclLocDecomp.first != CommentEndDecomp.first)
220 // Get the corresponding buffer.
221 bool Invalid = false;
222 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
227 // Extract text between the comment and declaration.
228 StringRef Text(Buffer + CommentEndDecomp.second,
229 DeclLocDecomp.second - CommentEndDecomp.second);
231 // There should be no other declarations or preprocessor directives between
232 // comment and declaration.
233 if (Text.find_first_of(";{}#@") != StringRef::npos)
240 /// If we have a 'templated' declaration for a template, adjust 'D' to
241 /// refer to the actual template.
242 /// If we have an implicit instantiation, adjust 'D' to refer to template.
243 const Decl *adjustDeclToTemplate(const Decl *D) {
244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245 // Is this function declaration part of a function template?
246 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
249 // Nothing to do if function is not an implicit instantiation.
250 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
253 // Function is an implicit instantiation of a function template?
254 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
257 // Function is instantiated from a member definition of a class template?
258 if (const FunctionDecl *MemberDecl =
259 FD->getInstantiatedFromMemberFunction())
264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265 // Static data member is instantiated from a member definition of a class
267 if (VD->isStaticDataMember())
268 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274 // Is this class declaration part of a class template?
275 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
278 // Class is an implicit instantiation of a class template or partial
280 if (const ClassTemplateSpecializationDecl *CTSD =
281 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
284 llvm::PointerUnion<ClassTemplateDecl *,
285 ClassTemplatePartialSpecializationDecl *>
286 PU = CTSD->getSpecializedTemplateOrPartial();
287 return PU.is<ClassTemplateDecl*>() ?
288 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289 static_cast<const Decl*>(
290 PU.get<ClassTemplatePartialSpecializationDecl *>());
293 // Class is instantiated from a member definition of a class template?
294 if (const MemberSpecializationInfo *Info =
295 CRD->getMemberSpecializationInfo())
296 return Info->getInstantiatedFrom();
300 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301 // Enum is instantiated from a member definition of a class template?
302 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
307 // FIXME: Adjust alias templates?
310 } // unnamed namespace
312 const RawComment *ASTContext::getRawCommentForAnyRedecl(
314 const Decl **OriginalDecl) const {
315 D = adjustDeclToTemplate(D);
317 // Check whether we have cached a comment for this declaration already.
319 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320 RedeclComments.find(D);
321 if (Pos != RedeclComments.end()) {
322 const RawCommentAndCacheFlags &Raw = Pos->second;
323 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 *OriginalDecl = Raw.getOriginalDecl();
331 // Search for comments attached to declarations in the redeclaration chain.
332 const RawComment *RC = NULL;
333 const Decl *OriginalDeclForRC = NULL;
334 for (Decl::redecl_iterator I = D->redecls_begin(),
335 E = D->redecls_end();
337 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338 RedeclComments.find(*I);
339 if (Pos != RedeclComments.end()) {
340 const RawCommentAndCacheFlags &Raw = Pos->second;
341 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
343 OriginalDeclForRC = Raw.getOriginalDecl();
347 RC = getRawCommentForDeclNoCache(*I);
348 OriginalDeclForRC = *I;
349 RawCommentAndCacheFlags Raw;
352 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
354 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
355 Raw.setOriginalDecl(*I);
356 RedeclComments[*I] = Raw;
362 // If we found a comment, it should be a documentation comment.
363 assert(!RC || RC->isDocumentation());
366 *OriginalDecl = OriginalDeclForRC;
368 // Update cache for every declaration in the redeclaration chain.
369 RawCommentAndCacheFlags Raw;
371 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
372 Raw.setOriginalDecl(OriginalDeclForRC);
374 for (Decl::redecl_iterator I = D->redecls_begin(),
375 E = D->redecls_end();
377 RawCommentAndCacheFlags &R = RedeclComments[*I];
378 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
385 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386 SmallVectorImpl<const NamedDecl *> &Redeclared) {
387 const DeclContext *DC = ObjCMethod->getDeclContext();
388 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
392 // Add redeclared method here.
393 for (ObjCInterfaceDecl::known_extensions_iterator
394 Ext = ID->known_extensions_begin(),
395 ExtEnd = ID->known_extensions_end();
396 Ext != ExtEnd; ++Ext) {
397 if (ObjCMethodDecl *RedeclaredMethod =
398 Ext->getMethod(ObjCMethod->getSelector(),
399 ObjCMethod->isInstanceMethod()))
400 Redeclared.push_back(RedeclaredMethod);
405 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406 const Decl *D) const {
407 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408 ThisDeclInfo->CommentDecl = D;
409 ThisDeclInfo->IsFilled = false;
410 ThisDeclInfo->fill();
411 ThisDeclInfo->CommentDecl = FC->getDecl();
412 comments::FullComment *CFC =
413 new (*this) comments::FullComment(FC->getBlocks(),
419 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420 const RawComment *RC = getRawCommentForDeclNoCache(D);
421 return RC ? RC->parse(*this, 0, D) : 0;
424 comments::FullComment *ASTContext::getCommentForDecl(
426 const Preprocessor *PP) const {
427 if (D->isInvalidDecl())
429 D = adjustDeclToTemplate(D);
431 const Decl *Canonical = D->getCanonicalDecl();
432 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433 ParsedComments.find(Canonical);
435 if (Pos != ParsedComments.end()) {
436 if (Canonical != D) {
437 comments::FullComment *FC = Pos->second;
438 comments::FullComment *CFC = cloneFullComment(FC, D);
444 const Decl *OriginalDecl;
446 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
448 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
449 SmallVector<const NamedDecl*, 8> Overridden;
450 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
451 if (OMD && OMD->isPropertyAccessor())
452 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454 return cloneFullComment(FC, D);
456 addRedeclaredMethods(OMD, Overridden);
457 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
458 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460 return cloneFullComment(FC, D);
462 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
463 // Attach any tag type's documentation to its typedef if latter
464 // does not have one of its own.
465 QualType QT = TD->getUnderlyingType();
466 if (const TagType *TT = QT->getAs<TagType>())
467 if (const Decl *TD = TT->getDecl())
468 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
469 return cloneFullComment(FC, D);
471 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472 while (IC->getSuperClass()) {
473 IC = IC->getSuperClass();
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
478 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481 return cloneFullComment(FC, D);
483 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484 if (!(RD = RD->getDefinition()))
486 // Check non-virtual bases.
487 for (CXXRecordDecl::base_class_const_iterator I =
488 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
489 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
491 QualType Ty = I->getType();
494 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
498 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499 return cloneFullComment(FC, D);
502 // Check virtual bases.
503 for (CXXRecordDecl::base_class_const_iterator I =
504 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
505 if (I->getAccessSpecifier() != AS_public)
507 QualType Ty = I->getType();
510 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(VirtualBase= VirtualBase->getDefinition()))
513 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514 return cloneFullComment(FC, D);
521 // If the RawComment was attached to other redeclaration of this Decl, we
522 // should parse the comment in context of that other Decl. This is important
523 // because comments can contain references to parameter names which can be
524 // different across redeclarations.
525 if (D != OriginalDecl)
526 return getCommentForDecl(OriginalDecl, PP);
528 comments::FullComment *FC = RC->parse(*this, PP, D);
529 ParsedComments[Canonical] = FC;
534 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535 TemplateTemplateParmDecl *Parm) {
536 ID.AddInteger(Parm->getDepth());
537 ID.AddInteger(Parm->getPosition());
538 ID.AddBoolean(Parm->isParameterPack());
540 TemplateParameterList *Params = Parm->getTemplateParameters();
541 ID.AddInteger(Params->size());
542 for (TemplateParameterList::const_iterator P = Params->begin(),
543 PEnd = Params->end();
545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
547 ID.AddBoolean(TTP->isParameterPack());
551 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
553 ID.AddBoolean(NTTP->isParameterPack());
554 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
555 if (NTTP->isExpandedParameterPack()) {
557 ID.AddInteger(NTTP->getNumExpansionTypes());
558 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559 QualType T = NTTP->getExpansionType(I);
560 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
563 ID.AddBoolean(false);
567 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
573 TemplateTemplateParmDecl *
574 ASTContext::getCanonicalTemplateTemplateParmDecl(
575 TemplateTemplateParmDecl *TTP) const {
576 // Check if we already have a canonical template template parameter.
577 llvm::FoldingSetNodeID ID;
578 CanonicalTemplateTemplateParm::Profile(ID, TTP);
580 CanonicalTemplateTemplateParm *Canonical
581 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
583 return Canonical->getParam();
585 // Build a canonical template parameter list.
586 TemplateParameterList *Params = TTP->getTemplateParameters();
587 SmallVector<NamedDecl *, 4> CanonParams;
588 CanonParams.reserve(Params->size());
589 for (TemplateParameterList::const_iterator P = Params->begin(),
590 PEnd = Params->end();
592 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593 CanonParams.push_back(
594 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
598 TTP->getIndex(), 0, false,
599 TTP->isParameterPack()));
600 else if (NonTypeTemplateParmDecl *NTTP
601 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602 QualType T = getCanonicalType(NTTP->getType());
603 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604 NonTypeTemplateParmDecl *Param;
605 if (NTTP->isExpandedParameterPack()) {
606 SmallVector<QualType, 2> ExpandedTypes;
607 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
608 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610 ExpandedTInfos.push_back(
611 getTrivialTypeSourceInfo(ExpandedTypes.back()));
614 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
618 NTTP->getPosition(), 0,
621 ExpandedTypes.data(),
622 ExpandedTypes.size(),
623 ExpandedTInfos.data());
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
629 NTTP->getPosition(), 0,
631 NTTP->isParameterPack(),
634 CanonParams.push_back(Param);
637 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638 cast<TemplateTemplateParmDecl>(*P)));
641 TemplateTemplateParmDecl *CanonTTP
642 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 SourceLocation(), TTP->getDepth(),
645 TTP->isParameterPack(),
647 TemplateParameterList::Create(*this, SourceLocation(),
653 // Get the new insert position for the node we care about.
654 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655 assert(Canonical == 0 && "Shouldn't be in the map!");
658 // Create the canonical template template parameter entry.
659 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
664 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
665 if (!LangOpts.CPlusPlus) return 0;
667 switch (T.getCXXABI().getKind()) {
668 case TargetCXXABI::GenericARM:
669 case TargetCXXABI::iOS:
670 return CreateARMCXXABI(*this);
671 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
672 case TargetCXXABI::GenericItanium:
673 return CreateItaniumCXXABI(*this);
674 case TargetCXXABI::Microsoft:
675 return CreateMicrosoftCXXABI(*this);
677 llvm_unreachable("Invalid CXXABI type!");
680 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
681 const LangOptions &LOpts) {
682 if (LOpts.FakeAddressSpaceMap) {
683 // The fake address space map must have a distinct entry for each
684 // language-specific address space.
685 static const unsigned FakeAddrSpaceMap[] = {
688 3, // opencl_constant
693 return &FakeAddrSpaceMap;
695 return &T.getAddressSpaceMap();
699 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700 const LangOptions &LangOpts) {
701 switch (LangOpts.getAddressSpaceMapMangling()) {
702 case LangOptions::ASMM_Target:
703 return TI.useAddressSpaceMapMangling();
704 case LangOptions::ASMM_On:
706 case LangOptions::ASMM_Off:
709 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
712 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
714 IdentifierTable &idents, SelectorTable &sels,
715 Builtin::Context &builtins,
716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
724 BuiltinVaListDecl(0),
725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
734 SourceMgr(SM), LangOpts(LOpts),
735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
739 ExternalSource(0), Listener(0),
740 Comments(SM), CommentsLoaded(false),
741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
744 if (size_reserve > 0) Types.reserve(size_reserve);
745 TUDecl = TranslationUnitDecl::Create(*this);
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
753 ASTContext::~ASTContext() {
754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
783 A->second->~AttrVec();
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
792 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
793 Deallocations[Callback].push_back(Data);
797 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
798 ExternalSource.reset(Source.take());
801 void ASTContext::PrintStats() const {
802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
805 unsigned counts[] = {
806 #define TYPE(Name, Parent) 0,
807 #define ABSTRACT_TYPE(Name, Parent)
808 #include "clang/AST/TypeNodes.def"
812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
814 counts[(unsigned)T->getTypeClass()]++;
818 unsigned TotalBytes = 0;
819 #define TYPE(Name, Parent) \
821 llvm::errs() << " " << counts[Idx] << " " << #Name \
823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
825 #define ABSTRACT_TYPE(Name, Parent)
826 #include "clang/AST/TypeNodes.def"
828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
830 // Implicit special member functions.
831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
837 if (getLangOpts().CPlusPlus)
838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
844 if (getLangOpts().CPlusPlus)
845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
852 if (ExternalSource.get()) {
853 llvm::errs() << "\n";
854 ExternalSource->PrintStats();
857 BumpAlloc.PrintStats();
860 TypedefDecl *ASTContext::getInt128Decl() const {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
863 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
867 &Idents.get("__int128_t"),
874 TypedefDecl *ASTContext::getUInt128Decl() const {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
877 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
878 getTranslationUnitDecl(),
881 &Idents.get("__uint128_t"),
888 TypeDecl *ASTContext::getFloat128StubType() const {
889 assert(LangOpts.CPlusPlus && "should only be called for c++");
890 if (!Float128StubDecl) {
891 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
893 getTranslationUnitDecl(),
896 &Idents.get("__float128"));
899 return Float128StubDecl;
902 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
903 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
904 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
908 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
909 assert((!this->Target || this->Target == &Target) &&
910 "Incorrect target reinitialization");
911 assert(VoidTy.isNull() && "Context reinitialized?");
913 this->Target = &Target;
915 ABI.reset(createCXXABI(Target));
916 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
917 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
920 InitBuiltinType(VoidTy, BuiltinType::Void);
923 InitBuiltinType(BoolTy, BuiltinType::Bool);
925 if (LangOpts.CharIsSigned)
926 InitBuiltinType(CharTy, BuiltinType::Char_S);
928 InitBuiltinType(CharTy, BuiltinType::Char_U);
930 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
931 InitBuiltinType(ShortTy, BuiltinType::Short);
932 InitBuiltinType(IntTy, BuiltinType::Int);
933 InitBuiltinType(LongTy, BuiltinType::Long);
934 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
937 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
938 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
939 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
940 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
941 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
944 InitBuiltinType(FloatTy, BuiltinType::Float);
945 InitBuiltinType(DoubleTy, BuiltinType::Double);
946 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
948 // GNU extension, 128-bit integers.
949 InitBuiltinType(Int128Ty, BuiltinType::Int128);
950 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
953 if (TargetInfo::isTypeSigned(Target.getWCharType()))
954 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
955 else // -fshort-wchar makes wchar_t be unsigned.
956 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
957 if (LangOpts.CPlusPlus && LangOpts.WChar)
958 WideCharTy = WCharTy;
960 // C99 (or C++ using -fno-wchar).
961 WideCharTy = getFromTargetType(Target.getWCharType());
964 WIntTy = getFromTargetType(Target.getWIntType());
966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char16Ty, BuiltinType::Char16);
969 Char16Ty = getFromTargetType(Target.getChar16Type());
971 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
972 InitBuiltinType(Char32Ty, BuiltinType::Char32);
974 Char32Ty = getFromTargetType(Target.getChar32Type());
976 // Placeholder type for type-dependent expressions whose type is
977 // completely unknown. No code should ever check a type against
978 // DependentTy and users should never see it; however, it is here to
979 // help diagnose failures to properly check for type-dependent
981 InitBuiltinType(DependentTy, BuiltinType::Dependent);
983 // Placeholder type for functions.
984 InitBuiltinType(OverloadTy, BuiltinType::Overload);
986 // Placeholder type for bound members.
987 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
989 // Placeholder type for pseudo-objects.
990 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
992 // "any" type; useful for debugger-like clients.
993 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
995 // Placeholder type for unbridged ARC casts.
996 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
998 // Placeholder type for builtin functions.
999 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1002 FloatComplexTy = getComplexType(FloatTy);
1003 DoubleComplexTy = getComplexType(DoubleTy);
1004 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1006 // Builtin types for 'id', 'Class', and 'SEL'.
1007 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1008 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1009 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1011 if (LangOpts.OpenCL) {
1012 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1013 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1014 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1015 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1016 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1017 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1019 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1020 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1023 // Builtin type for __objc_yes and __objc_no
1024 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1025 SignedCharTy : BoolTy);
1027 ObjCConstantStringType = QualType();
1029 ObjCSuperType = QualType();
1032 VoidPtrTy = getPointerType(VoidTy);
1034 // nullptr type (C++0x 2.14.7)
1035 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1037 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1038 InitBuiltinType(HalfTy, BuiltinType::Half);
1040 // Builtin type used to help define __builtin_va_list.
1041 VaListTagTy = QualType();
1044 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1045 return SourceMgr.getDiagnostics();
1048 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1049 AttrVec *&Result = DeclAttrs[D];
1051 void *Mem = Allocate(sizeof(AttrVec));
1052 Result = new (Mem) AttrVec;
1058 /// \brief Erase the attributes corresponding to the given declaration.
1059 void ASTContext::eraseDeclAttrs(const Decl *D) {
1060 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1061 if (Pos != DeclAttrs.end()) {
1062 Pos->second->~AttrVec();
1063 DeclAttrs.erase(Pos);
1068 MemberSpecializationInfo *
1069 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1070 assert(Var->isStaticDataMember() && "Not a static data member");
1071 return getTemplateOrSpecializationInfo(Var)
1072 .dyn_cast<MemberSpecializationInfo *>();
1075 ASTContext::TemplateOrSpecializationInfo
1076 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1077 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1078 TemplateOrInstantiation.find(Var);
1079 if (Pos == TemplateOrInstantiation.end())
1080 return TemplateOrSpecializationInfo();
1086 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1087 TemplateSpecializationKind TSK,
1088 SourceLocation PointOfInstantiation) {
1089 assert(Inst->isStaticDataMember() && "Not a static data member");
1090 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1091 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1092 Tmpl, TSK, PointOfInstantiation));
1096 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1097 TemplateOrSpecializationInfo TSI) {
1098 assert(!TemplateOrInstantiation[Inst] &&
1099 "Already noted what the variable was instantiated from");
1100 TemplateOrInstantiation[Inst] = TSI;
1103 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1104 const FunctionDecl *FD){
1105 assert(FD && "Specialization is 0");
1106 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1107 = ClassScopeSpecializationPattern.find(FD);
1108 if (Pos == ClassScopeSpecializationPattern.end())
1114 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1115 FunctionDecl *Pattern) {
1116 assert(FD && "Specialization is 0");
1117 assert(Pattern && "Class scope specialization pattern is 0");
1118 ClassScopeSpecializationPattern[FD] = Pattern;
1122 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1123 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1124 = InstantiatedFromUsingDecl.find(UUD);
1125 if (Pos == InstantiatedFromUsingDecl.end())
1132 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1133 assert((isa<UsingDecl>(Pattern) ||
1134 isa<UnresolvedUsingValueDecl>(Pattern) ||
1135 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1136 "pattern decl is not a using decl");
1137 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1138 InstantiatedFromUsingDecl[Inst] = Pattern;
1142 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1143 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1144 = InstantiatedFromUsingShadowDecl.find(Inst);
1145 if (Pos == InstantiatedFromUsingShadowDecl.end())
1152 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1153 UsingShadowDecl *Pattern) {
1154 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1155 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1158 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1159 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1160 = InstantiatedFromUnnamedFieldDecl.find(Field);
1161 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1167 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1169 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1170 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1171 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1172 "Already noted what unnamed field was instantiated from");
1174 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1177 ASTContext::overridden_cxx_method_iterator
1178 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1180 = OverriddenMethods.find(Method->getCanonicalDecl());
1181 if (Pos == OverriddenMethods.end())
1184 return Pos->second.begin();
1187 ASTContext::overridden_cxx_method_iterator
1188 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1190 = OverriddenMethods.find(Method->getCanonicalDecl());
1191 if (Pos == OverriddenMethods.end())
1194 return Pos->second.end();
1198 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1200 = OverriddenMethods.find(Method->getCanonicalDecl());
1201 if (Pos == OverriddenMethods.end())
1204 return Pos->second.size();
1207 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1208 const CXXMethodDecl *Overridden) {
1209 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1210 OverriddenMethods[Method].push_back(Overridden);
1213 void ASTContext::getOverriddenMethods(
1215 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1218 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1219 Overridden.append(overridden_methods_begin(CXXMethod),
1220 overridden_methods_end(CXXMethod));
1224 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1228 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1229 Method->getOverriddenMethods(OverDecls);
1230 Overridden.append(OverDecls.begin(), OverDecls.end());
1233 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1234 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1235 assert(!Import->isFromASTFile() && "Non-local import declaration");
1236 if (!FirstLocalImport) {
1237 FirstLocalImport = Import;
1238 LastLocalImport = Import;
1242 LastLocalImport->NextLocalImport = Import;
1243 LastLocalImport = Import;
1246 //===----------------------------------------------------------------------===//
1247 // Type Sizing and Analysis
1248 //===----------------------------------------------------------------------===//
1250 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1251 /// scalar floating point type.
1252 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1253 const BuiltinType *BT = T->getAs<BuiltinType>();
1254 assert(BT && "Not a floating point type!");
1255 switch (BT->getKind()) {
1256 default: llvm_unreachable("Not a floating point type!");
1257 case BuiltinType::Half: return Target->getHalfFormat();
1258 case BuiltinType::Float: return Target->getFloatFormat();
1259 case BuiltinType::Double: return Target->getDoubleFormat();
1260 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1264 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1265 unsigned Align = Target->getCharWidth();
1267 bool UseAlignAttrOnly = false;
1268 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1269 Align = AlignFromAttr;
1271 // __attribute__((aligned)) can increase or decrease alignment
1272 // *except* on a struct or struct member, where it only increases
1273 // alignment unless 'packed' is also specified.
1275 // It is an error for alignas to decrease alignment, so we can
1276 // ignore that possibility; Sema should diagnose it.
1277 if (isa<FieldDecl>(D)) {
1278 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1279 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1281 UseAlignAttrOnly = true;
1284 else if (isa<FieldDecl>(D))
1286 D->hasAttr<PackedAttr>() ||
1287 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1289 // If we're using the align attribute only, just ignore everything
1290 // else about the declaration and its type.
1291 if (UseAlignAttrOnly) {
1294 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1295 QualType T = VD->getType();
1296 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
1298 T = RT->getPointeeType();
1300 T = getPointerType(RT->getPointeeType());
1302 if (!T->isIncompleteType() && !T->isFunctionType()) {
1303 // Adjust alignments of declarations with array type by the
1304 // large-array alignment on the target.
1305 if (const ArrayType *arrayType = getAsArrayType(T)) {
1306 unsigned MinWidth = Target->getLargeArrayMinWidth();
1307 if (!ForAlignof && MinWidth) {
1308 if (isa<VariableArrayType>(arrayType))
1309 Align = std::max(Align, Target->getLargeArrayAlign());
1310 else if (isa<ConstantArrayType>(arrayType) &&
1311 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1315 // Walk through any array types while we're at it.
1316 T = getBaseElementType(arrayType);
1318 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1319 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1320 if (VD->hasGlobalStorage())
1321 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1325 // Fields can be subject to extra alignment constraints, like if
1326 // the field is packed, the struct is packed, or the struct has a
1327 // a max-field-alignment constraint (#pragma pack). So calculate
1328 // the actual alignment of the field within the struct, and then
1329 // (as we're expected to) constrain that by the alignment of the type.
1330 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1331 const RecordDecl *Parent = Field->getParent();
1332 // We can only produce a sensible answer if the record is valid.
1333 if (!Parent->isInvalidDecl()) {
1334 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1336 // Start with the record's overall alignment.
1337 unsigned FieldAlign = toBits(Layout.getAlignment());
1339 // Use the GCD of that and the offset within the record.
1340 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1342 // Alignment is always a power of 2, so the GCD will be a power of 2,
1343 // which means we get to do this crazy thing instead of Euclid's.
1344 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1345 if (LowBitOfOffset < FieldAlign)
1346 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1349 Align = std::min(Align, FieldAlign);
1354 return toCharUnitsFromBits(Align);
1357 // getTypeInfoDataSizeInChars - Return the size of a type, in
1358 // chars. If the type is a record, its data size is returned. This is
1359 // the size of the memcpy that's performed when assigning this type
1360 // using a trivial copy/move assignment operator.
1361 std::pair<CharUnits, CharUnits>
1362 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1363 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1365 // In C++, objects can sometimes be allocated into the tail padding
1366 // of a base-class subobject. We decide whether that's possible
1367 // during class layout, so here we can just trust the layout results.
1368 if (getLangOpts().CPlusPlus) {
1369 if (const RecordType *RT = T->getAs<RecordType>()) {
1370 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1371 sizeAndAlign.first = layout.getDataSize();
1375 return sizeAndAlign;
1378 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1379 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1380 std::pair<CharUnits, CharUnits>
1381 static getConstantArrayInfoInChars(const ASTContext &Context,
1382 const ConstantArrayType *CAT) {
1383 std::pair<CharUnits, CharUnits> EltInfo =
1384 Context.getTypeInfoInChars(CAT->getElementType());
1385 uint64_t Size = CAT->getSize().getZExtValue();
1386 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1387 (uint64_t)(-1)/Size) &&
1388 "Overflow in array type char size evaluation");
1389 uint64_t Width = EltInfo.first.getQuantity() * Size;
1390 unsigned Align = EltInfo.second.getQuantity();
1391 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1392 Context.getTargetInfo().getPointerWidth(0) == 64)
1393 Width = llvm::RoundUpToAlignment(Width, Align);
1394 return std::make_pair(CharUnits::fromQuantity(Width),
1395 CharUnits::fromQuantity(Align));
1398 std::pair<CharUnits, CharUnits>
1399 ASTContext::getTypeInfoInChars(const Type *T) const {
1400 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1401 return getConstantArrayInfoInChars(*this, CAT);
1402 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1403 return std::make_pair(toCharUnitsFromBits(Info.first),
1404 toCharUnitsFromBits(Info.second));
1407 std::pair<CharUnits, CharUnits>
1408 ASTContext::getTypeInfoInChars(QualType T) const {
1409 return getTypeInfoInChars(T.getTypePtr());
1412 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1413 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1414 if (it != MemoizedTypeInfo.end())
1417 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1418 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1422 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1423 /// method does not work on incomplete types.
1425 /// FIXME: Pointers into different addr spaces could have different sizes and
1426 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1427 /// should take a QualType, &c.
1428 std::pair<uint64_t, unsigned>
1429 ASTContext::getTypeInfoImpl(const Type *T) const {
1432 switch (T->getTypeClass()) {
1433 #define TYPE(Class, Base)
1434 #define ABSTRACT_TYPE(Class, Base)
1435 #define NON_CANONICAL_TYPE(Class, Base)
1436 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1437 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1439 assert(!T->isDependentType() && "should not see dependent types here"); \
1440 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1441 #include "clang/AST/TypeNodes.def"
1442 llvm_unreachable("Should not see dependent types");
1444 case Type::FunctionNoProto:
1445 case Type::FunctionProto:
1446 // GCC extension: alignof(function) = 32 bits
1451 case Type::IncompleteArray:
1452 case Type::VariableArray:
1454 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1457 case Type::ConstantArray: {
1458 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1460 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1461 uint64_t Size = CAT->getSize().getZExtValue();
1462 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1463 "Overflow in array type bit size evaluation");
1464 Width = EltInfo.first*Size;
1465 Align = EltInfo.second;
1466 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1467 getTargetInfo().getPointerWidth(0) == 64)
1468 Width = llvm::RoundUpToAlignment(Width, Align);
1471 case Type::ExtVector:
1472 case Type::Vector: {
1473 const VectorType *VT = cast<VectorType>(T);
1474 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1475 Width = EltInfo.first*VT->getNumElements();
1477 // If the alignment is not a power of 2, round up to the next power of 2.
1478 // This happens for non-power-of-2 length vectors.
1479 if (Align & (Align-1)) {
1480 Align = llvm::NextPowerOf2(Align);
1481 Width = llvm::RoundUpToAlignment(Width, Align);
1483 // Adjust the alignment based on the target max.
1484 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1485 if (TargetVectorAlign && TargetVectorAlign < Align)
1486 Align = TargetVectorAlign;
1491 switch (cast<BuiltinType>(T)->getKind()) {
1492 default: llvm_unreachable("Unknown builtin type!");
1493 case BuiltinType::Void:
1494 // GCC extension: alignof(void) = 8 bits.
1499 case BuiltinType::Bool:
1500 Width = Target->getBoolWidth();
1501 Align = Target->getBoolAlign();
1503 case BuiltinType::Char_S:
1504 case BuiltinType::Char_U:
1505 case BuiltinType::UChar:
1506 case BuiltinType::SChar:
1507 Width = Target->getCharWidth();
1508 Align = Target->getCharAlign();
1510 case BuiltinType::WChar_S:
1511 case BuiltinType::WChar_U:
1512 Width = Target->getWCharWidth();
1513 Align = Target->getWCharAlign();
1515 case BuiltinType::Char16:
1516 Width = Target->getChar16Width();
1517 Align = Target->getChar16Align();
1519 case BuiltinType::Char32:
1520 Width = Target->getChar32Width();
1521 Align = Target->getChar32Align();
1523 case BuiltinType::UShort:
1524 case BuiltinType::Short:
1525 Width = Target->getShortWidth();
1526 Align = Target->getShortAlign();
1528 case BuiltinType::UInt:
1529 case BuiltinType::Int:
1530 Width = Target->getIntWidth();
1531 Align = Target->getIntAlign();
1533 case BuiltinType::ULong:
1534 case BuiltinType::Long:
1535 Width = Target->getLongWidth();
1536 Align = Target->getLongAlign();
1538 case BuiltinType::ULongLong:
1539 case BuiltinType::LongLong:
1540 Width = Target->getLongLongWidth();
1541 Align = Target->getLongLongAlign();
1543 case BuiltinType::Int128:
1544 case BuiltinType::UInt128:
1546 Align = 128; // int128_t is 128-bit aligned on all targets.
1548 case BuiltinType::Half:
1549 Width = Target->getHalfWidth();
1550 Align = Target->getHalfAlign();
1552 case BuiltinType::Float:
1553 Width = Target->getFloatWidth();
1554 Align = Target->getFloatAlign();
1556 case BuiltinType::Double:
1557 Width = Target->getDoubleWidth();
1558 Align = Target->getDoubleAlign();
1560 case BuiltinType::LongDouble:
1561 Width = Target->getLongDoubleWidth();
1562 Align = Target->getLongDoubleAlign();
1564 case BuiltinType::NullPtr:
1565 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1566 Align = Target->getPointerAlign(0); // == sizeof(void*)
1568 case BuiltinType::ObjCId:
1569 case BuiltinType::ObjCClass:
1570 case BuiltinType::ObjCSel:
1571 Width = Target->getPointerWidth(0);
1572 Align = Target->getPointerAlign(0);
1574 case BuiltinType::OCLSampler:
1575 // Samplers are modeled as integers.
1576 Width = Target->getIntWidth();
1577 Align = Target->getIntAlign();
1579 case BuiltinType::OCLEvent:
1580 case BuiltinType::OCLImage1d:
1581 case BuiltinType::OCLImage1dArray:
1582 case BuiltinType::OCLImage1dBuffer:
1583 case BuiltinType::OCLImage2d:
1584 case BuiltinType::OCLImage2dArray:
1585 case BuiltinType::OCLImage3d:
1586 // Currently these types are pointers to opaque types.
1587 Width = Target->getPointerWidth(0);
1588 Align = Target->getPointerAlign(0);
1592 case Type::ObjCObjectPointer:
1593 Width = Target->getPointerWidth(0);
1594 Align = Target->getPointerAlign(0);
1596 case Type::BlockPointer: {
1597 unsigned AS = getTargetAddressSpace(
1598 cast<BlockPointerType>(T)->getPointeeType());
1599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
1603 case Type::LValueReference:
1604 case Type::RValueReference: {
1605 // alignof and sizeof should never enter this code path here, so we go
1606 // the pointer route.
1607 unsigned AS = getTargetAddressSpace(
1608 cast<ReferenceType>(T)->getPointeeType());
1609 Width = Target->getPointerWidth(AS);
1610 Align = Target->getPointerAlign(AS);
1613 case Type::Pointer: {
1614 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1615 Width = Target->getPointerWidth(AS);
1616 Align = Target->getPointerAlign(AS);
1619 case Type::MemberPointer: {
1620 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1621 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1624 case Type::Complex: {
1625 // Complex types have the same alignment as their elements, but twice the
1627 std::pair<uint64_t, unsigned> EltInfo =
1628 getTypeInfo(cast<ComplexType>(T)->getElementType());
1629 Width = EltInfo.first*2;
1630 Align = EltInfo.second;
1633 case Type::ObjCObject:
1634 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1636 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
1637 case Type::ObjCInterface: {
1638 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1639 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1640 Width = toBits(Layout.getSize());
1641 Align = toBits(Layout.getAlignment());
1646 const TagType *TT = cast<TagType>(T);
1648 if (TT->getDecl()->isInvalidDecl()) {
1654 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1655 return getTypeInfo(ET->getDecl()->getIntegerType());
1657 const RecordType *RT = cast<RecordType>(TT);
1658 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1659 Width = toBits(Layout.getSize());
1660 Align = toBits(Layout.getAlignment());
1664 case Type::SubstTemplateTypeParm:
1665 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1666 getReplacementType().getTypePtr());
1669 const AutoType *A = cast<AutoType>(T);
1670 assert(!A->getDeducedType().isNull() &&
1671 "cannot request the size of an undeduced or dependent auto type");
1672 return getTypeInfo(A->getDeducedType().getTypePtr());
1676 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1678 case Type::Typedef: {
1679 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1680 std::pair<uint64_t, unsigned> Info
1681 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1682 // If the typedef has an aligned attribute on it, it overrides any computed
1683 // alignment we have. This violates the GCC documentation (which says that
1684 // attribute(aligned) can only round up) but matches its implementation.
1685 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1688 Align = Info.second;
1693 case Type::Elaborated:
1694 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1696 case Type::Attributed:
1698 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1700 case Type::Atomic: {
1701 // Start with the base type information.
1702 std::pair<uint64_t, unsigned> Info
1703 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1705 Align = Info.second;
1707 // If the size of the type doesn't exceed the platform's max
1708 // atomic promotion width, make the size and alignment more
1709 // favorable to atomic operations:
1710 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1711 // Round the size up to a power of 2.
1712 if (!llvm::isPowerOf2_64(Width))
1713 Width = llvm::NextPowerOf2(Width);
1715 // Set the alignment equal to the size.
1716 Align = static_cast<unsigned>(Width);
1722 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1723 return std::make_pair(Width, Align);
1726 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1727 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1728 return CharUnits::fromQuantity(BitSize / getCharWidth());
1731 /// toBits - Convert a size in characters to a size in characters.
1732 int64_t ASTContext::toBits(CharUnits CharSize) const {
1733 return CharSize.getQuantity() * getCharWidth();
1736 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1737 /// This method does not work on incomplete types.
1738 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1739 return getTypeInfoInChars(T).first;
1741 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1742 return getTypeInfoInChars(T).first;
1745 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1746 /// characters. This method does not work on incomplete types.
1747 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1748 return toCharUnitsFromBits(getTypeAlign(T));
1750 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1751 return toCharUnitsFromBits(getTypeAlign(T));
1754 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1755 /// type for the current target in bits. This can be different than the ABI
1756 /// alignment in cases where it is beneficial for performance to overalign
1758 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1759 unsigned ABIAlign = getTypeAlign(T);
1761 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1762 return ABIAlign; // Never overalign on XCore.
1764 // Double and long long should be naturally aligned if possible.
1765 if (const ComplexType* CT = T->getAs<ComplexType>())
1766 T = CT->getElementType().getTypePtr();
1767 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1768 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1769 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1770 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1775 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1776 /// to a global variable of the specified type.
1777 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1778 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1781 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1782 /// should be given to a global variable of the specified type.
1783 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1784 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1787 /// DeepCollectObjCIvars -
1788 /// This routine first collects all declared, but not synthesized, ivars in
1789 /// super class and then collects all ivars, including those synthesized for
1790 /// current class. This routine is used for implementation of current class
1791 /// when all ivars, declared and synthesized are known.
1793 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1795 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1796 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1797 DeepCollectObjCIvars(SuperClass, false, Ivars);
1799 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1800 E = OI->ivar_end(); I != E; ++I)
1801 Ivars.push_back(*I);
1803 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1804 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1805 Iv= Iv->getNextIvar())
1806 Ivars.push_back(Iv);
1810 /// CollectInheritedProtocols - Collect all protocols in current class and
1811 /// those inherited by it.
1812 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1813 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1814 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1815 // We can use protocol_iterator here instead of
1816 // all_referenced_protocol_iterator since we are walking all categories.
1817 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1818 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1819 ObjCProtocolDecl *Proto = (*P);
1820 Protocols.insert(Proto->getCanonicalDecl());
1821 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1822 PE = Proto->protocol_end(); P != PE; ++P) {
1823 Protocols.insert((*P)->getCanonicalDecl());
1824 CollectInheritedProtocols(*P, Protocols);
1828 // Categories of this Interface.
1829 for (ObjCInterfaceDecl::visible_categories_iterator
1830 Cat = OI->visible_categories_begin(),
1831 CatEnd = OI->visible_categories_end();
1832 Cat != CatEnd; ++Cat) {
1833 CollectInheritedProtocols(*Cat, Protocols);
1836 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1838 CollectInheritedProtocols(SD, Protocols);
1839 SD = SD->getSuperClass();
1841 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1842 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1843 PE = OC->protocol_end(); P != PE; ++P) {
1844 ObjCProtocolDecl *Proto = (*P);
1845 Protocols.insert(Proto->getCanonicalDecl());
1846 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1847 PE = Proto->protocol_end(); P != PE; ++P)
1848 CollectInheritedProtocols(*P, Protocols);
1850 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1851 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1852 PE = OP->protocol_end(); P != PE; ++P) {
1853 ObjCProtocolDecl *Proto = (*P);
1854 Protocols.insert(Proto->getCanonicalDecl());
1855 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1856 PE = Proto->protocol_end(); P != PE; ++P)
1857 CollectInheritedProtocols(*P, Protocols);
1862 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1864 // Count ivars declared in class extension.
1865 for (ObjCInterfaceDecl::known_extensions_iterator
1866 Ext = OI->known_extensions_begin(),
1867 ExtEnd = OI->known_extensions_end();
1868 Ext != ExtEnd; ++Ext) {
1869 count += Ext->ivar_size();
1872 // Count ivar defined in this class's implementation. This
1873 // includes synthesized ivars.
1874 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1875 count += ImplDecl->ivar_size();
1880 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1884 // nullptr_t is always treated as null.
1885 if (E->getType()->isNullPtrType()) return true;
1887 if (E->getType()->isAnyPointerType() &&
1888 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1889 Expr::NPC_ValueDependentIsNull))
1892 // Unfortunately, __null has type 'int'.
1893 if (isa<GNUNullExpr>(E)) return true;
1898 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1899 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCImplementationDecl>(I->second);
1906 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1907 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1909 I = ObjCImpls.find(D);
1910 if (I != ObjCImpls.end())
1911 return cast<ObjCCategoryImplDecl>(I->second);
1915 /// \brief Set the implementation of ObjCInterfaceDecl.
1916 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1917 ObjCImplementationDecl *ImplD) {
1918 assert(IFaceD && ImplD && "Passed null params");
1919 ObjCImpls[IFaceD] = ImplD;
1921 /// \brief Set the implementation of ObjCCategoryDecl.
1922 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1923 ObjCCategoryImplDecl *ImplD) {
1924 assert(CatD && ImplD && "Passed null params");
1925 ObjCImpls[CatD] = ImplD;
1928 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1929 const NamedDecl *ND) const {
1930 if (const ObjCInterfaceDecl *ID =
1931 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1933 if (const ObjCCategoryDecl *CD =
1934 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1935 return CD->getClassInterface();
1936 if (const ObjCImplDecl *IMD =
1937 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1938 return IMD->getClassInterface();
1943 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1945 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1946 assert(VD && "Passed null params");
1947 assert(VD->hasAttr<BlocksAttr>() &&
1948 "getBlockVarCopyInits - not __block var");
1949 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1950 I = BlockVarCopyInits.find(VD);
1951 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1954 /// \brief Set the copy inialization expression of a block var decl.
1955 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1956 assert(VD && Init && "Passed null params");
1957 assert(VD->hasAttr<BlocksAttr>() &&
1958 "setBlockVarCopyInits - not __block var");
1959 BlockVarCopyInits[VD] = Init;
1962 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1963 unsigned DataSize) const {
1965 DataSize = TypeLoc::getFullDataSizeForType(T);
1967 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1968 "incorrect data size provided to CreateTypeSourceInfo!");
1970 TypeSourceInfo *TInfo =
1971 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1972 new (TInfo) TypeSourceInfo(T);
1976 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1977 SourceLocation L) const {
1978 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1979 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1983 const ASTRecordLayout &
1984 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1985 return getObjCLayout(D, 0);
1988 const ASTRecordLayout &
1989 ASTContext::getASTObjCImplementationLayout(
1990 const ObjCImplementationDecl *D) const {
1991 return getObjCLayout(D->getClassInterface(), D);
1994 //===----------------------------------------------------------------------===//
1995 // Type creation/memoization methods
1996 //===----------------------------------------------------------------------===//
1999 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2000 unsigned fastQuals = quals.getFastQualifiers();
2001 quals.removeFastQualifiers();
2003 // Check if we've already instantiated this type.
2004 llvm::FoldingSetNodeID ID;
2005 ExtQuals::Profile(ID, baseType, quals);
2006 void *insertPos = 0;
2007 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2008 assert(eq->getQualifiers() == quals);
2009 return QualType(eq, fastQuals);
2012 // If the base type is not canonical, make the appropriate canonical type.
2014 if (!baseType->isCanonicalUnqualified()) {
2015 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2016 canonSplit.Quals.addConsistentQualifiers(quals);
2017 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2019 // Re-find the insert position.
2020 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2023 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2024 ExtQualNodes.InsertNode(eq, insertPos);
2025 return QualType(eq, fastQuals);
2029 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2030 QualType CanT = getCanonicalType(T);
2031 if (CanT.getAddressSpace() == AddressSpace)
2034 // If we are composing extended qualifiers together, merge together
2035 // into one ExtQuals node.
2036 QualifierCollector Quals;
2037 const Type *TypeNode = Quals.strip(T);
2039 // If this type already has an address space specified, it cannot get
2041 assert(!Quals.hasAddressSpace() &&
2042 "Type cannot be in multiple addr spaces!");
2043 Quals.addAddressSpace(AddressSpace);
2045 return getExtQualType(TypeNode, Quals);
2048 QualType ASTContext::getObjCGCQualType(QualType T,
2049 Qualifiers::GC GCAttr) const {
2050 QualType CanT = getCanonicalType(T);
2051 if (CanT.getObjCGCAttr() == GCAttr)
2054 if (const PointerType *ptr = T->getAs<PointerType>()) {
2055 QualType Pointee = ptr->getPointeeType();
2056 if (Pointee->isAnyPointerType()) {
2057 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2058 return getPointerType(ResultType);
2062 // If we are composing extended qualifiers together, merge together
2063 // into one ExtQuals node.
2064 QualifierCollector Quals;
2065 const Type *TypeNode = Quals.strip(T);
2067 // If this type already has an ObjCGC specified, it cannot get
2069 assert(!Quals.hasObjCGCAttr() &&
2070 "Type cannot have multiple ObjCGCs!");
2071 Quals.addObjCGCAttr(GCAttr);
2073 return getExtQualType(TypeNode, Quals);
2076 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2077 FunctionType::ExtInfo Info) {
2078 if (T->getExtInfo() == Info)
2082 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2083 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2085 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2088 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
2091 return cast<FunctionType>(Result.getTypePtr());
2094 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2095 QualType ResultType) {
2096 FD = FD->getMostRecentDecl();
2098 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2100 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2101 if (FunctionDecl *Next = FD->getPreviousDecl())
2106 if (ASTMutationListener *L = getASTMutationListener())
2107 L->DeducedReturnType(FD, ResultType);
2110 /// getComplexType - Return the uniqued reference to the type for a complex
2111 /// number with the specified element type.
2112 QualType ASTContext::getComplexType(QualType T) const {
2113 // Unique pointers, to guarantee there is only one pointer of a particular
2115 llvm::FoldingSetNodeID ID;
2116 ComplexType::Profile(ID, T);
2118 void *InsertPos = 0;
2119 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2120 return QualType(CT, 0);
2122 // If the pointee type isn't canonical, this won't be a canonical type either,
2123 // so fill in the canonical type field.
2125 if (!T.isCanonical()) {
2126 Canonical = getComplexType(getCanonicalType(T));
2128 // Get the new insert position for the node we care about.
2129 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2130 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2132 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2133 Types.push_back(New);
2134 ComplexTypes.InsertNode(New, InsertPos);
2135 return QualType(New, 0);
2138 /// getPointerType - Return the uniqued reference to the type for a pointer to
2139 /// the specified type.
2140 QualType ASTContext::getPointerType(QualType T) const {
2141 // Unique pointers, to guarantee there is only one pointer of a particular
2143 llvm::FoldingSetNodeID ID;
2144 PointerType::Profile(ID, T);
2146 void *InsertPos = 0;
2147 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2148 return QualType(PT, 0);
2150 // If the pointee type isn't canonical, this won't be a canonical type either,
2151 // so fill in the canonical type field.
2153 if (!T.isCanonical()) {
2154 Canonical = getPointerType(getCanonicalType(T));
2156 // Get the new insert position for the node we care about.
2157 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2160 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2161 Types.push_back(New);
2162 PointerTypes.InsertNode(New, InsertPos);
2163 return QualType(New, 0);
2166 QualType ASTContext::getDecayedType(QualType T) const {
2167 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2169 llvm::FoldingSetNodeID ID;
2170 DecayedType::Profile(ID, T);
2171 void *InsertPos = 0;
2172 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2173 return QualType(DT, 0);
2178 // A declaration of a parameter as "array of type" shall be
2179 // adjusted to "qualified pointer to type", where the type
2180 // qualifiers (if any) are those specified within the [ and ] of
2181 // the array type derivation.
2182 if (T->isArrayType())
2183 Decayed = getArrayDecayedType(T);
2186 // A declaration of a parameter as "function returning type"
2187 // shall be adjusted to "pointer to function returning type", as
2189 if (T->isFunctionType())
2190 Decayed = getPointerType(T);
2192 QualType Canonical = getCanonicalType(Decayed);
2194 // Get the new insert position for the node we care about.
2195 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2199 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2200 Types.push_back(New);
2201 DecayedTypes.InsertNode(New, InsertPos);
2202 return QualType(New, 0);
2205 /// getBlockPointerType - Return the uniqued reference to the type for
2206 /// a pointer to the specified block.
2207 QualType ASTContext::getBlockPointerType(QualType T) const {
2208 assert(T->isFunctionType() && "block of function types only");
2209 // Unique pointers, to guarantee there is only one block of a particular
2211 llvm::FoldingSetNodeID ID;
2212 BlockPointerType::Profile(ID, T);
2214 void *InsertPos = 0;
2215 if (BlockPointerType *PT =
2216 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2217 return QualType(PT, 0);
2219 // If the block pointee type isn't canonical, this won't be a canonical
2220 // type either so fill in the canonical type field.
2222 if (!T.isCanonical()) {
2223 Canonical = getBlockPointerType(getCanonicalType(T));
2225 // Get the new insert position for the node we care about.
2226 BlockPointerType *NewIP =
2227 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2228 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2230 BlockPointerType *New
2231 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2232 Types.push_back(New);
2233 BlockPointerTypes.InsertNode(New, InsertPos);
2234 return QualType(New, 0);
2237 /// getLValueReferenceType - Return the uniqued reference to the type for an
2238 /// lvalue reference to the specified type.
2240 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2241 assert(getCanonicalType(T) != OverloadTy &&
2242 "Unresolved overloaded function type");
2244 // Unique pointers, to guarantee there is only one pointer of a particular
2246 llvm::FoldingSetNodeID ID;
2247 ReferenceType::Profile(ID, T, SpelledAsLValue);
2249 void *InsertPos = 0;
2250 if (LValueReferenceType *RT =
2251 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2252 return QualType(RT, 0);
2254 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2256 // If the referencee type isn't canonical, this won't be a canonical type
2257 // either, so fill in the canonical type field.
2259 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2260 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2261 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2263 // Get the new insert position for the node we care about.
2264 LValueReferenceType *NewIP =
2265 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2266 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2269 LValueReferenceType *New
2270 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2272 Types.push_back(New);
2273 LValueReferenceTypes.InsertNode(New, InsertPos);
2275 return QualType(New, 0);
2278 /// getRValueReferenceType - Return the uniqued reference to the type for an
2279 /// rvalue reference to the specified type.
2280 QualType ASTContext::getRValueReferenceType(QualType T) const {
2281 // Unique pointers, to guarantee there is only one pointer of a particular
2283 llvm::FoldingSetNodeID ID;
2284 ReferenceType::Profile(ID, T, false);
2286 void *InsertPos = 0;
2287 if (RValueReferenceType *RT =
2288 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2289 return QualType(RT, 0);
2291 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2293 // If the referencee type isn't canonical, this won't be a canonical type
2294 // either, so fill in the canonical type field.
2296 if (InnerRef || !T.isCanonical()) {
2297 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2298 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2300 // Get the new insert position for the node we care about.
2301 RValueReferenceType *NewIP =
2302 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2303 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2306 RValueReferenceType *New
2307 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2308 Types.push_back(New);
2309 RValueReferenceTypes.InsertNode(New, InsertPos);
2310 return QualType(New, 0);
2313 /// getMemberPointerType - Return the uniqued reference to the type for a
2314 /// member pointer to the specified type, in the specified class.
2315 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2316 // Unique pointers, to guarantee there is only one pointer of a particular
2318 llvm::FoldingSetNodeID ID;
2319 MemberPointerType::Profile(ID, T, Cls);
2321 void *InsertPos = 0;
2322 if (MemberPointerType *PT =
2323 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2324 return QualType(PT, 0);
2326 // If the pointee or class type isn't canonical, this won't be a canonical
2327 // type either, so fill in the canonical type field.
2329 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2330 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2332 // Get the new insert position for the node we care about.
2333 MemberPointerType *NewIP =
2334 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2337 MemberPointerType *New
2338 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2339 Types.push_back(New);
2340 MemberPointerTypes.InsertNode(New, InsertPos);
2341 return QualType(New, 0);
2344 /// getConstantArrayType - Return the unique reference to the type for an
2345 /// array of the specified element type.
2346 QualType ASTContext::getConstantArrayType(QualType EltTy,
2347 const llvm::APInt &ArySizeIn,
2348 ArrayType::ArraySizeModifier ASM,
2349 unsigned IndexTypeQuals) const {
2350 assert((EltTy->isDependentType() ||
2351 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2352 "Constant array of VLAs is illegal!");
2354 // Convert the array size into a canonical width matching the pointer size for
2356 llvm::APInt ArySize(ArySizeIn);
2358 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2360 llvm::FoldingSetNodeID ID;
2361 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2363 void *InsertPos = 0;
2364 if (ConstantArrayType *ATP =
2365 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2366 return QualType(ATP, 0);
2368 // If the element type isn't canonical or has qualifiers, this won't
2369 // be a canonical type either, so fill in the canonical type field.
2371 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2372 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2373 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2374 ASM, IndexTypeQuals);
2375 Canon = getQualifiedType(Canon, canonSplit.Quals);
2377 // Get the new insert position for the node we care about.
2378 ConstantArrayType *NewIP =
2379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2380 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2383 ConstantArrayType *New = new(*this,TypeAlignment)
2384 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2385 ConstantArrayTypes.InsertNode(New, InsertPos);
2386 Types.push_back(New);
2387 return QualType(New, 0);
2390 /// getVariableArrayDecayedType - Turns the given type, which may be
2391 /// variably-modified, into the corresponding type with all the known
2392 /// sizes replaced with [*].
2393 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2394 // Vastly most common case.
2395 if (!type->isVariablyModifiedType()) return type;
2399 SplitQualType split = type.getSplitDesugaredType();
2400 const Type *ty = split.Ty;
2401 switch (ty->getTypeClass()) {
2402 #define TYPE(Class, Base)
2403 #define ABSTRACT_TYPE(Class, Base)
2404 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2405 #include "clang/AST/TypeNodes.def"
2406 llvm_unreachable("didn't desugar past all non-canonical types?");
2408 // These types should never be variably-modified.
2412 case Type::ExtVector:
2413 case Type::DependentSizedExtVector:
2414 case Type::ObjCObject:
2415 case Type::ObjCInterface:
2416 case Type::ObjCObjectPointer:
2419 case Type::UnresolvedUsing:
2420 case Type::TypeOfExpr:
2422 case Type::Decltype:
2423 case Type::UnaryTransform:
2424 case Type::DependentName:
2425 case Type::InjectedClassName:
2426 case Type::TemplateSpecialization:
2427 case Type::DependentTemplateSpecialization:
2428 case Type::TemplateTypeParm:
2429 case Type::SubstTemplateTypeParmPack:
2431 case Type::PackExpansion:
2432 llvm_unreachable("type should never be variably-modified");
2434 // These types can be variably-modified but should never need to
2436 case Type::FunctionNoProto:
2437 case Type::FunctionProto:
2438 case Type::BlockPointer:
2439 case Type::MemberPointer:
2442 // These types can be variably-modified. All these modifications
2443 // preserve structure except as noted by comments.
2444 // TODO: if we ever care about optimizing VLAs, there are no-op
2445 // optimizations available here.
2447 result = getPointerType(getVariableArrayDecayedType(
2448 cast<PointerType>(ty)->getPointeeType()));
2451 case Type::LValueReference: {
2452 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2453 result = getLValueReferenceType(
2454 getVariableArrayDecayedType(lv->getPointeeType()),
2455 lv->isSpelledAsLValue());
2459 case Type::RValueReference: {
2460 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2461 result = getRValueReferenceType(
2462 getVariableArrayDecayedType(lv->getPointeeType()));
2466 case Type::Atomic: {
2467 const AtomicType *at = cast<AtomicType>(ty);
2468 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2472 case Type::ConstantArray: {
2473 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2474 result = getConstantArrayType(
2475 getVariableArrayDecayedType(cat->getElementType()),
2477 cat->getSizeModifier(),
2478 cat->getIndexTypeCVRQualifiers());
2482 case Type::DependentSizedArray: {
2483 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2484 result = getDependentSizedArrayType(
2485 getVariableArrayDecayedType(dat->getElementType()),
2487 dat->getSizeModifier(),
2488 dat->getIndexTypeCVRQualifiers(),
2489 dat->getBracketsRange());
2493 // Turn incomplete types into [*] types.
2494 case Type::IncompleteArray: {
2495 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2496 result = getVariableArrayType(
2497 getVariableArrayDecayedType(iat->getElementType()),
2500 iat->getIndexTypeCVRQualifiers(),
2505 // Turn VLA types into [*] types.
2506 case Type::VariableArray: {
2507 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2508 result = getVariableArrayType(
2509 getVariableArrayDecayedType(vat->getElementType()),
2512 vat->getIndexTypeCVRQualifiers(),
2513 vat->getBracketsRange());
2518 // Apply the top-level qualifiers from the original.
2519 return getQualifiedType(result, split.Quals);
2522 /// getVariableArrayType - Returns a non-unique reference to the type for a
2523 /// variable array of the specified element type.
2524 QualType ASTContext::getVariableArrayType(QualType EltTy,
2526 ArrayType::ArraySizeModifier ASM,
2527 unsigned IndexTypeQuals,
2528 SourceRange Brackets) const {
2529 // Since we don't unique expressions, it isn't possible to unique VLA's
2530 // that have an expression provided for their size.
2533 // Be sure to pull qualifiers off the element type.
2534 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2535 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2536 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2537 IndexTypeQuals, Brackets);
2538 Canon = getQualifiedType(Canon, canonSplit.Quals);
2541 VariableArrayType *New = new(*this, TypeAlignment)
2542 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2544 VariableArrayTypes.push_back(New);
2545 Types.push_back(New);
2546 return QualType(New, 0);
2549 /// getDependentSizedArrayType - Returns a non-unique reference to
2550 /// the type for a dependently-sized array of the specified element
2552 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2554 ArrayType::ArraySizeModifier ASM,
2555 unsigned elementTypeQuals,
2556 SourceRange brackets) const {
2557 assert((!numElements || numElements->isTypeDependent() ||
2558 numElements->isValueDependent()) &&
2559 "Size must be type- or value-dependent!");
2561 // Dependently-sized array types that do not have a specified number
2562 // of elements will have their sizes deduced from a dependent
2563 // initializer. We do no canonicalization here at all, which is okay
2564 // because they can't be used in most locations.
2566 DependentSizedArrayType *newType
2567 = new (*this, TypeAlignment)
2568 DependentSizedArrayType(*this, elementType, QualType(),
2569 numElements, ASM, elementTypeQuals,
2571 Types.push_back(newType);
2572 return QualType(newType, 0);
2575 // Otherwise, we actually build a new type every time, but we
2576 // also build a canonical type.
2578 SplitQualType canonElementType = getCanonicalType(elementType).split();
2580 void *insertPos = 0;
2581 llvm::FoldingSetNodeID ID;
2582 DependentSizedArrayType::Profile(ID, *this,
2583 QualType(canonElementType.Ty, 0),
2584 ASM, elementTypeQuals, numElements);
2586 // Look for an existing type with these properties.
2587 DependentSizedArrayType *canonTy =
2588 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2590 // If we don't have one, build one.
2592 canonTy = new (*this, TypeAlignment)
2593 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2594 QualType(), numElements, ASM, elementTypeQuals,
2596 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2597 Types.push_back(canonTy);
2600 // Apply qualifiers from the element type to the array.
2601 QualType canon = getQualifiedType(QualType(canonTy,0),
2602 canonElementType.Quals);
2604 // If we didn't need extra canonicalization for the element type,
2605 // then just use that as our result.
2606 if (QualType(canonElementType.Ty, 0) == elementType)
2609 // Otherwise, we need to build a type which follows the spelling
2610 // of the element type.
2611 DependentSizedArrayType *sugaredType
2612 = new (*this, TypeAlignment)
2613 DependentSizedArrayType(*this, elementType, canon, numElements,
2614 ASM, elementTypeQuals, brackets);
2615 Types.push_back(sugaredType);
2616 return QualType(sugaredType, 0);
2619 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2620 ArrayType::ArraySizeModifier ASM,
2621 unsigned elementTypeQuals) const {
2622 llvm::FoldingSetNodeID ID;
2623 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2625 void *insertPos = 0;
2626 if (IncompleteArrayType *iat =
2627 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2628 return QualType(iat, 0);
2630 // If the element type isn't canonical, this won't be a canonical type
2631 // either, so fill in the canonical type field. We also have to pull
2632 // qualifiers off the element type.
2635 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2636 SplitQualType canonSplit = getCanonicalType(elementType).split();
2637 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2638 ASM, elementTypeQuals);
2639 canon = getQualifiedType(canon, canonSplit.Quals);
2641 // Get the new insert position for the node we care about.
2642 IncompleteArrayType *existing =
2643 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2644 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2647 IncompleteArrayType *newType = new (*this, TypeAlignment)
2648 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2650 IncompleteArrayTypes.InsertNode(newType, insertPos);
2651 Types.push_back(newType);
2652 return QualType(newType, 0);
2655 /// getVectorType - Return the unique reference to a vector type of
2656 /// the specified element type and size. VectorType must be a built-in type.
2657 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2658 VectorType::VectorKind VecKind) const {
2659 assert(vecType->isBuiltinType());
2661 // Check if we've already instantiated a vector of this type.
2662 llvm::FoldingSetNodeID ID;
2663 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2665 void *InsertPos = 0;
2666 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2667 return QualType(VTP, 0);
2669 // If the element type isn't canonical, this won't be a canonical type either,
2670 // so fill in the canonical type field.
2672 if (!vecType.isCanonical()) {
2673 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2675 // Get the new insert position for the node we care about.
2676 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2677 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2679 VectorType *New = new (*this, TypeAlignment)
2680 VectorType(vecType, NumElts, Canonical, VecKind);
2681 VectorTypes.InsertNode(New, InsertPos);
2682 Types.push_back(New);
2683 return QualType(New, 0);
2686 /// getExtVectorType - Return the unique reference to an extended vector type of
2687 /// the specified element type and size. VectorType must be a built-in type.
2689 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2690 assert(vecType->isBuiltinType() || vecType->isDependentType());
2692 // Check if we've already instantiated a vector of this type.
2693 llvm::FoldingSetNodeID ID;
2694 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2695 VectorType::GenericVector);
2696 void *InsertPos = 0;
2697 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2698 return QualType(VTP, 0);
2700 // If the element type isn't canonical, this won't be a canonical type either,
2701 // so fill in the canonical type field.
2703 if (!vecType.isCanonical()) {
2704 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2706 // Get the new insert position for the node we care about.
2707 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2710 ExtVectorType *New = new (*this, TypeAlignment)
2711 ExtVectorType(vecType, NumElts, Canonical);
2712 VectorTypes.InsertNode(New, InsertPos);
2713 Types.push_back(New);
2714 return QualType(New, 0);
2718 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2720 SourceLocation AttrLoc) const {
2721 llvm::FoldingSetNodeID ID;
2722 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2725 void *InsertPos = 0;
2726 DependentSizedExtVectorType *Canon
2727 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2728 DependentSizedExtVectorType *New;
2730 // We already have a canonical version of this array type; use it as
2731 // the canonical type for a newly-built type.
2732 New = new (*this, TypeAlignment)
2733 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2736 QualType CanonVecTy = getCanonicalType(vecType);
2737 if (CanonVecTy == vecType) {
2738 New = new (*this, TypeAlignment)
2739 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2742 DependentSizedExtVectorType *CanonCheck
2743 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2744 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2746 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2748 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2750 New = new (*this, TypeAlignment)
2751 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2755 Types.push_back(New);
2756 return QualType(New, 0);
2759 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2762 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2763 const FunctionType::ExtInfo &Info) const {
2764 const CallingConv CallConv = Info.getCC();
2766 // Unique functions, to guarantee there is only one function of a particular
2768 llvm::FoldingSetNodeID ID;
2769 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2771 void *InsertPos = 0;
2772 if (FunctionNoProtoType *FT =
2773 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2774 return QualType(FT, 0);
2777 if (!ResultTy.isCanonical()) {
2778 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2780 // Get the new insert position for the node we care about.
2781 FunctionNoProtoType *NewIP =
2782 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2786 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2787 FunctionNoProtoType *New = new (*this, TypeAlignment)
2788 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2789 Types.push_back(New);
2790 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2791 return QualType(New, 0);
2794 /// \brief Determine whether \p T is canonical as the result type of a function.
2795 static bool isCanonicalResultType(QualType T) {
2796 return T.isCanonical() &&
2797 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2798 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2801 /// getFunctionType - Return a normal function type with a typed argument
2802 /// list. isVariadic indicates whether the argument list includes '...'.
2804 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2805 const FunctionProtoType::ExtProtoInfo &EPI) const {
2806 size_t NumArgs = ArgArray.size();
2808 // Unique functions, to guarantee there is only one function of a particular
2810 llvm::FoldingSetNodeID ID;
2811 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2814 void *InsertPos = 0;
2815 if (FunctionProtoType *FTP =
2816 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2817 return QualType(FTP, 0);
2819 // Determine whether the type being created is already canonical or not.
2821 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2822 !EPI.HasTrailingReturn;
2823 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2824 if (!ArgArray[i].isCanonicalAsParam())
2825 isCanonical = false;
2827 // If this type isn't canonical, get the canonical version of it.
2828 // The exception spec is not part of the canonical type.
2831 SmallVector<QualType, 16> CanonicalArgs;
2832 CanonicalArgs.reserve(NumArgs);
2833 for (unsigned i = 0; i != NumArgs; ++i)
2834 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2836 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2837 CanonicalEPI.HasTrailingReturn = false;
2838 CanonicalEPI.ExceptionSpecType = EST_None;
2839 CanonicalEPI.NumExceptions = 0;
2841 // Result types do not have ARC lifetime qualifiers.
2842 QualType CanResultTy = getCanonicalType(ResultTy);
2843 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2844 Qualifiers Qs = CanResultTy.getQualifiers();
2845 Qs.removeObjCLifetime();
2846 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2849 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2851 // Get the new insert position for the node we care about.
2852 FunctionProtoType *NewIP =
2853 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2854 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2857 // FunctionProtoType objects are allocated with extra bytes after
2858 // them for three variable size arrays at the end:
2859 // - parameter types
2860 // - exception types
2861 // - consumed-arguments flags
2862 // Instead of the exception types, there could be a noexcept
2863 // expression, or information used to resolve the exception
2865 size_t Size = sizeof(FunctionProtoType) +
2866 NumArgs * sizeof(QualType);
2867 if (EPI.ExceptionSpecType == EST_Dynamic) {
2868 Size += EPI.NumExceptions * sizeof(QualType);
2869 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2870 Size += sizeof(Expr*);
2871 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2872 Size += 2 * sizeof(FunctionDecl*);
2873 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2874 Size += sizeof(FunctionDecl*);
2876 if (EPI.ConsumedArguments)
2877 Size += NumArgs * sizeof(bool);
2879 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2880 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2881 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2882 Types.push_back(FTP);
2883 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2884 return QualType(FTP, 0);
2888 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2889 if (!isa<CXXRecordDecl>(D)) return false;
2890 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2891 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2893 if (RD->getDescribedClassTemplate() &&
2894 !isa<ClassTemplateSpecializationDecl>(RD))
2900 /// getInjectedClassNameType - Return the unique reference to the
2901 /// injected class name type for the specified templated declaration.
2902 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2903 QualType TST) const {
2904 assert(NeedsInjectedClassNameType(Decl));
2905 if (Decl->TypeForDecl) {
2906 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2907 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2908 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2909 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2910 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2913 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2914 Decl->TypeForDecl = newType;
2915 Types.push_back(newType);
2917 return QualType(Decl->TypeForDecl, 0);
2920 /// getTypeDeclType - Return the unique reference to the type for the
2921 /// specified type declaration.
2922 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2923 assert(Decl && "Passed null for Decl param");
2924 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2926 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2927 return getTypedefType(Typedef);
2929 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2930 "Template type parameter types are always available.");
2932 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2933 assert(Record->isFirstDecl() && "struct/union has previous declaration");
2934 assert(!NeedsInjectedClassNameType(Record));
2935 return getRecordType(Record);
2936 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2937 assert(Enum->isFirstDecl() && "enum has previous declaration");
2938 return getEnumType(Enum);
2939 } else if (const UnresolvedUsingTypenameDecl *Using =
2940 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2941 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2942 Decl->TypeForDecl = newType;
2943 Types.push_back(newType);
2945 llvm_unreachable("TypeDecl without a type?");
2947 return QualType(Decl->TypeForDecl, 0);
2950 /// getTypedefType - Return the unique reference to the type for the
2951 /// specified typedef name decl.
2953 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2954 QualType Canonical) const {
2955 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2957 if (Canonical.isNull())
2958 Canonical = getCanonicalType(Decl->getUnderlyingType());
2959 TypedefType *newType = new(*this, TypeAlignment)
2960 TypedefType(Type::Typedef, Decl, Canonical);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
2963 return QualType(newType, 0);
2966 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2967 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2969 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2970 if (PrevDecl->TypeForDecl)
2971 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2973 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2974 Decl->TypeForDecl = newType;
2975 Types.push_back(newType);
2976 return QualType(newType, 0);
2979 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2980 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2982 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2983 if (PrevDecl->TypeForDecl)
2984 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2986 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2987 Decl->TypeForDecl = newType;
2988 Types.push_back(newType);
2989 return QualType(newType, 0);
2992 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2993 QualType modifiedType,
2994 QualType equivalentType) {
2995 llvm::FoldingSetNodeID id;
2996 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2998 void *insertPos = 0;
2999 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3000 if (type) return QualType(type, 0);
3002 QualType canon = getCanonicalType(equivalentType);
3003 type = new (*this, TypeAlignment)
3004 AttributedType(canon, attrKind, modifiedType, equivalentType);
3006 Types.push_back(type);
3007 AttributedTypes.InsertNode(type, insertPos);
3009 return QualType(type, 0);
3013 /// \brief Retrieve a substitution-result type.
3015 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3016 QualType Replacement) const {
3017 assert(Replacement.isCanonical()
3018 && "replacement types must always be canonical");
3020 llvm::FoldingSetNodeID ID;
3021 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3022 void *InsertPos = 0;
3023 SubstTemplateTypeParmType *SubstParm
3024 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3027 SubstParm = new (*this, TypeAlignment)
3028 SubstTemplateTypeParmType(Parm, Replacement);
3029 Types.push_back(SubstParm);
3030 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3033 return QualType(SubstParm, 0);
3036 /// \brief Retrieve a
3037 QualType ASTContext::getSubstTemplateTypeParmPackType(
3038 const TemplateTypeParmType *Parm,
3039 const TemplateArgument &ArgPack) {
3041 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3042 PEnd = ArgPack.pack_end();
3044 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3045 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3049 llvm::FoldingSetNodeID ID;
3050 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3051 void *InsertPos = 0;
3052 if (SubstTemplateTypeParmPackType *SubstParm
3053 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3054 return QualType(SubstParm, 0);
3057 if (!Parm->isCanonicalUnqualified()) {
3058 Canon = getCanonicalType(QualType(Parm, 0));
3059 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3061 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3064 SubstTemplateTypeParmPackType *SubstParm
3065 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3067 Types.push_back(SubstParm);
3068 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3069 return QualType(SubstParm, 0);
3072 /// \brief Retrieve the template type parameter type for a template
3073 /// parameter or parameter pack with the given depth, index, and (optionally)
3075 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3077 TemplateTypeParmDecl *TTPDecl) const {
3078 llvm::FoldingSetNodeID ID;
3079 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3080 void *InsertPos = 0;
3081 TemplateTypeParmType *TypeParm
3082 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3085 return QualType(TypeParm, 0);
3088 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3089 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3091 TemplateTypeParmType *TypeCheck
3092 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3093 assert(!TypeCheck && "Template type parameter canonical type broken");
3096 TypeParm = new (*this, TypeAlignment)
3097 TemplateTypeParmType(Depth, Index, ParameterPack);
3099 Types.push_back(TypeParm);
3100 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3102 return QualType(TypeParm, 0);
3106 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3107 SourceLocation NameLoc,
3108 const TemplateArgumentListInfo &Args,
3109 QualType Underlying) const {
3110 assert(!Name.getAsDependentTemplateName() &&
3111 "No dependent template names here!");
3112 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3114 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3115 TemplateSpecializationTypeLoc TL =
3116 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3117 TL.setTemplateKeywordLoc(SourceLocation());
3118 TL.setTemplateNameLoc(NameLoc);
3119 TL.setLAngleLoc(Args.getLAngleLoc());
3120 TL.setRAngleLoc(Args.getRAngleLoc());
3121 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3122 TL.setArgLocInfo(i, Args[i].getLocInfo());
3127 ASTContext::getTemplateSpecializationType(TemplateName Template,
3128 const TemplateArgumentListInfo &Args,
3129 QualType Underlying) const {
3130 assert(!Template.getAsDependentTemplateName() &&
3131 "No dependent template names here!");
3133 unsigned NumArgs = Args.size();
3135 SmallVector<TemplateArgument, 4> ArgVec;
3136 ArgVec.reserve(NumArgs);
3137 for (unsigned i = 0; i != NumArgs; ++i)
3138 ArgVec.push_back(Args[i].getArgument());
3140 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3145 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3147 for (unsigned I = 0; I != NumArgs; ++I)
3148 if (Args[I].isPackExpansion())
3156 ASTContext::getTemplateSpecializationType(TemplateName Template,
3157 const TemplateArgument *Args,
3159 QualType Underlying) const {
3160 assert(!Template.getAsDependentTemplateName() &&
3161 "No dependent template names here!");
3162 // Look through qualified template names.
3163 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3164 Template = TemplateName(QTN->getTemplateDecl());
3167 Template.getAsTemplateDecl() &&
3168 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3170 if (!Underlying.isNull())
3171 CanonType = getCanonicalType(Underlying);
3173 // We can get here with an alias template when the specialization contains
3174 // a pack expansion that does not match up with a parameter pack.
3175 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3176 "Caller must compute aliased type");
3177 IsTypeAlias = false;
3178 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3182 // Allocate the (non-canonical) template specialization type, but don't
3183 // try to unique it: these types typically have location information that
3184 // we don't unique and don't want to lose.
3185 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3186 sizeof(TemplateArgument) * NumArgs +
3187 (IsTypeAlias? sizeof(QualType) : 0),
3189 TemplateSpecializationType *Spec
3190 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3191 IsTypeAlias ? Underlying : QualType());
3193 Types.push_back(Spec);
3194 return QualType(Spec, 0);
3198 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3199 const TemplateArgument *Args,
3200 unsigned NumArgs) const {
3201 assert(!Template.getAsDependentTemplateName() &&
3202 "No dependent template names here!");
3204 // Look through qualified template names.
3205 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3206 Template = TemplateName(QTN->getTemplateDecl());
3208 // Build the canonical template specialization type.
3209 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3210 SmallVector<TemplateArgument, 4> CanonArgs;
3211 CanonArgs.reserve(NumArgs);
3212 for (unsigned I = 0; I != NumArgs; ++I)
3213 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3215 // Determine whether this canonical template specialization type already
3217 llvm::FoldingSetNodeID ID;
3218 TemplateSpecializationType::Profile(ID, CanonTemplate,
3219 CanonArgs.data(), NumArgs, *this);
3221 void *InsertPos = 0;
3222 TemplateSpecializationType *Spec
3223 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3226 // Allocate a new canonical template specialization type.
3227 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3228 sizeof(TemplateArgument) * NumArgs),
3230 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3231 CanonArgs.data(), NumArgs,
3232 QualType(), QualType());
3233 Types.push_back(Spec);
3234 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3237 assert(Spec->isDependentType() &&
3238 "Non-dependent template-id type must have a canonical type");
3239 return QualType(Spec, 0);
3243 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3244 NestedNameSpecifier *NNS,
3245 QualType NamedType) const {
3246 llvm::FoldingSetNodeID ID;
3247 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3249 void *InsertPos = 0;
3250 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3252 return QualType(T, 0);
3254 QualType Canon = NamedType;
3255 if (!Canon.isCanonical()) {
3256 Canon = getCanonicalType(NamedType);
3257 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 assert(!CheckT && "Elaborated canonical type broken");
3262 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3264 ElaboratedTypes.InsertNode(T, InsertPos);
3265 return QualType(T, 0);
3269 ASTContext::getParenType(QualType InnerType) const {
3270 llvm::FoldingSetNodeID ID;
3271 ParenType::Profile(ID, InnerType);
3273 void *InsertPos = 0;
3274 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3276 return QualType(T, 0);
3278 QualType Canon = InnerType;
3279 if (!Canon.isCanonical()) {
3280 Canon = getCanonicalType(InnerType);
3281 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 assert(!CheckT && "Paren canonical type broken");
3286 T = new (*this) ParenType(InnerType, Canon);
3288 ParenTypes.InsertNode(T, InsertPos);
3289 return QualType(T, 0);
3292 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3293 NestedNameSpecifier *NNS,
3294 const IdentifierInfo *Name,
3295 QualType Canon) const {
3296 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3298 if (Canon.isNull()) {
3299 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3300 ElaboratedTypeKeyword CanonKeyword = Keyword;
3301 if (Keyword == ETK_None)
3302 CanonKeyword = ETK_Typename;
3304 if (CanonNNS != NNS || CanonKeyword != Keyword)
3305 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3308 llvm::FoldingSetNodeID ID;
3309 DependentNameType::Profile(ID, Keyword, NNS, Name);
3311 void *InsertPos = 0;
3312 DependentNameType *T
3313 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3315 return QualType(T, 0);
3317 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3319 DependentNameTypes.InsertNode(T, InsertPos);
3320 return QualType(T, 0);
3324 ASTContext::getDependentTemplateSpecializationType(
3325 ElaboratedTypeKeyword Keyword,
3326 NestedNameSpecifier *NNS,
3327 const IdentifierInfo *Name,
3328 const TemplateArgumentListInfo &Args) const {
3329 // TODO: avoid this copy
3330 SmallVector<TemplateArgument, 16> ArgCopy;
3331 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3332 ArgCopy.push_back(Args[I].getArgument());
3333 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3339 ASTContext::getDependentTemplateSpecializationType(
3340 ElaboratedTypeKeyword Keyword,
3341 NestedNameSpecifier *NNS,
3342 const IdentifierInfo *Name,
3344 const TemplateArgument *Args) const {
3345 assert((!NNS || NNS->isDependent()) &&
3346 "nested-name-specifier must be dependent");
3348 llvm::FoldingSetNodeID ID;
3349 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3350 Name, NumArgs, Args);
3352 void *InsertPos = 0;
3353 DependentTemplateSpecializationType *T
3354 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3356 return QualType(T, 0);
3358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3360 ElaboratedTypeKeyword CanonKeyword = Keyword;
3361 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3363 bool AnyNonCanonArgs = false;
3364 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3365 for (unsigned I = 0; I != NumArgs; ++I) {
3366 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3367 if (!CanonArgs[I].structurallyEquals(Args[I]))
3368 AnyNonCanonArgs = true;
3372 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3373 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3377 // Find the insert position again.
3378 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3382 sizeof(TemplateArgument) * NumArgs),
3384 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3385 Name, NumArgs, Args, Canon);
3387 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3388 return QualType(T, 0);
3391 QualType ASTContext::getPackExpansionType(QualType Pattern,
3392 Optional<unsigned> NumExpansions) {
3393 llvm::FoldingSetNodeID ID;
3394 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3396 assert(Pattern->containsUnexpandedParameterPack() &&
3397 "Pack expansions must expand one or more parameter packs");
3398 void *InsertPos = 0;
3399 PackExpansionType *T
3400 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3402 return QualType(T, 0);
3405 if (!Pattern.isCanonical()) {
3406 Canon = getCanonicalType(Pattern);
3407 // The canonical type might not contain an unexpanded parameter pack, if it
3408 // contains an alias template specialization which ignores one of its
3410 if (Canon->containsUnexpandedParameterPack()) {
3411 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
3413 // Find the insert position again, in case we inserted an element into
3414 // PackExpansionTypes and invalidated our insert position.
3415 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3419 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3421 PackExpansionTypes.InsertNode(T, InsertPos);
3422 return QualType(T, 0);
3425 /// CmpProtocolNames - Comparison predicate for sorting protocols
3427 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3428 const ObjCProtocolDecl *RHS) {
3429 return LHS->getDeclName() < RHS->getDeclName();
3432 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3433 unsigned NumProtocols) {
3434 if (NumProtocols == 0) return true;
3436 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3439 for (unsigned i = 1; i != NumProtocols; ++i)
3440 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3441 Protocols[i]->getCanonicalDecl() != Protocols[i])
3446 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3447 unsigned &NumProtocols) {
3448 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3450 // Sort protocols, keyed by name.
3451 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3454 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3455 Protocols[I] = Protocols[I]->getCanonicalDecl();
3457 // Remove duplicates.
3458 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3459 NumProtocols = ProtocolsEnd-Protocols;
3462 QualType ASTContext::getObjCObjectType(QualType BaseType,
3463 ObjCProtocolDecl * const *Protocols,
3464 unsigned NumProtocols) const {
3465 // If the base type is an interface and there aren't any protocols
3466 // to add, then the interface type will do just fine.
3467 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3470 // Look in the folding set for an existing type.
3471 llvm::FoldingSetNodeID ID;
3472 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3473 void *InsertPos = 0;
3474 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3475 return QualType(QT, 0);
3477 // Build the canonical type, which has the canonical base type and
3478 // a sorted-and-uniqued list of protocols.
3480 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3481 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3482 if (!ProtocolsSorted) {
3483 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3484 Protocols + NumProtocols);
3485 unsigned UniqueCount = NumProtocols;
3487 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3488 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3489 &Sorted[0], UniqueCount);
3491 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3492 Protocols, NumProtocols);
3495 // Regenerate InsertPos.
3496 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3499 unsigned Size = sizeof(ObjCObjectTypeImpl);
3500 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3501 void *Mem = Allocate(Size, TypeAlignment);
3502 ObjCObjectTypeImpl *T =
3503 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3506 ObjCObjectTypes.InsertNode(T, InsertPos);
3507 return QualType(T, 0);
3510 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3511 /// the given object type.
3512 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3513 llvm::FoldingSetNodeID ID;
3514 ObjCObjectPointerType::Profile(ID, ObjectT);
3516 void *InsertPos = 0;
3517 if (ObjCObjectPointerType *QT =
3518 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3519 return QualType(QT, 0);
3521 // Find the canonical object type.
3523 if (!ObjectT.isCanonical()) {
3524 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3526 // Regenerate InsertPos.
3527 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3531 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3532 ObjCObjectPointerType *QType =
3533 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3535 Types.push_back(QType);
3536 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3537 return QualType(QType, 0);
3540 /// getObjCInterfaceType - Return the unique reference to the type for the
3541 /// specified ObjC interface decl. The list of protocols is optional.
3542 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3543 ObjCInterfaceDecl *PrevDecl) const {
3544 if (Decl->TypeForDecl)
3545 return QualType(Decl->TypeForDecl, 0);
3548 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3549 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3550 return QualType(PrevDecl->TypeForDecl, 0);
3553 // Prefer the definition, if there is one.
3554 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3557 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3558 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3559 Decl->TypeForDecl = T;
3561 return QualType(T, 0);
3564 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3565 /// TypeOfExprType AST's (since expression's are never shared). For example,
3566 /// multiple declarations that refer to "typeof(x)" all contain different
3567 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3568 /// on canonical type's (which are always unique).
3569 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3570 TypeOfExprType *toe;
3571 if (tofExpr->isTypeDependent()) {
3572 llvm::FoldingSetNodeID ID;
3573 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3575 void *InsertPos = 0;
3576 DependentTypeOfExprType *Canon
3577 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3579 // We already have a "canonical" version of an identical, dependent
3580 // typeof(expr) type. Use that as our canonical type.
3581 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3582 QualType((TypeOfExprType*)Canon, 0));
3584 // Build a new, canonical typeof(expr) type.
3586 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3587 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3591 QualType Canonical = getCanonicalType(tofExpr->getType());
3592 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3594 Types.push_back(toe);
3595 return QualType(toe, 0);
3598 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3599 /// TypeOfType AST's. The only motivation to unique these nodes would be
3600 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3601 /// an issue. This doesn't effect the type checker, since it operates
3602 /// on canonical type's (which are always unique).
3603 QualType ASTContext::getTypeOfType(QualType tofType) const {
3604 QualType Canonical = getCanonicalType(tofType);
3605 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3606 Types.push_back(tot);
3607 return QualType(tot, 0);
3611 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3612 /// DecltypeType AST's. The only motivation to unique these nodes would be
3613 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3614 /// an issue. This doesn't effect the type checker, since it operates
3615 /// on canonical types (which are always unique).
3616 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3619 // C++0x [temp.type]p2:
3620 // If an expression e involves a template parameter, decltype(e) denotes a
3621 // unique dependent type. Two such decltype-specifiers refer to the same
3622 // type only if their expressions are equivalent (14.5.6.1).
3623 if (e->isInstantiationDependent()) {
3624 llvm::FoldingSetNodeID ID;
3625 DependentDecltypeType::Profile(ID, *this, e);
3627 void *InsertPos = 0;
3628 DependentDecltypeType *Canon
3629 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3631 // We already have a "canonical" version of an equivalent, dependent
3632 // decltype type. Use that as our canonical type.
3633 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3634 QualType((DecltypeType*)Canon, 0));
3636 // Build a new, canonical typeof(expr) type.
3637 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3638 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3642 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3643 getCanonicalType(UnderlyingType));
3645 Types.push_back(dt);
3646 return QualType(dt, 0);
3649 /// getUnaryTransformationType - We don't unique these, since the memory
3650 /// savings are minimal and these are rare.
3651 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3652 QualType UnderlyingType,
3653 UnaryTransformType::UTTKind Kind)
3655 UnaryTransformType *Ty =
3656 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3658 UnderlyingType->isDependentType() ?
3659 QualType() : getCanonicalType(UnderlyingType));
3660 Types.push_back(Ty);
3661 return QualType(Ty, 0);
3664 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3665 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3666 /// canonical deduced-but-dependent 'auto' type.
3667 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3668 bool IsDependent) const {
3669 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3670 return getAutoDeductType();
3672 // Look in the folding set for an existing type.
3673 void *InsertPos = 0;
3674 llvm::FoldingSetNodeID ID;
3675 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3676 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3677 return QualType(AT, 0);
3679 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3682 Types.push_back(AT);
3684 AutoTypes.InsertNode(AT, InsertPos);
3685 return QualType(AT, 0);
3688 /// getAtomicType - Return the uniqued reference to the atomic type for
3689 /// the given value type.
3690 QualType ASTContext::getAtomicType(QualType T) const {
3691 // Unique pointers, to guarantee there is only one pointer of a particular
3693 llvm::FoldingSetNodeID ID;
3694 AtomicType::Profile(ID, T);
3696 void *InsertPos = 0;
3697 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3698 return QualType(AT, 0);
3700 // If the atomic value type isn't canonical, this won't be a canonical type
3701 // either, so fill in the canonical type field.
3703 if (!T.isCanonical()) {
3704 Canonical = getAtomicType(getCanonicalType(T));
3706 // Get the new insert position for the node we care about.
3707 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3710 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3711 Types.push_back(New);
3712 AtomicTypes.InsertNode(New, InsertPos);
3713 return QualType(New, 0);
3716 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3717 QualType ASTContext::getAutoDeductType() const {
3718 if (AutoDeductTy.isNull())
3719 AutoDeductTy = QualType(
3720 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3721 /*dependent*/false),
3723 return AutoDeductTy;
3726 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3727 QualType ASTContext::getAutoRRefDeductType() const {
3728 if (AutoRRefDeductTy.isNull())
3729 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3730 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3731 return AutoRRefDeductTy;
3734 /// getTagDeclType - Return the unique reference to the type for the
3735 /// specified TagDecl (struct/union/class/enum) decl.
3736 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3738 // FIXME: What is the design on getTagDeclType when it requires casting
3739 // away const? mutable?
3740 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3743 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3744 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3745 /// needs to agree with the definition in <stddef.h>.
3746 CanQualType ASTContext::getSizeType() const {
3747 return getFromTargetType(Target->getSizeType());
3750 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3751 CanQualType ASTContext::getIntMaxType() const {
3752 return getFromTargetType(Target->getIntMaxType());
3755 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3756 CanQualType ASTContext::getUIntMaxType() const {
3757 return getFromTargetType(Target->getUIntMaxType());
3760 /// getSignedWCharType - Return the type of "signed wchar_t".
3761 /// Used when in C++, as a GCC extension.
3762 QualType ASTContext::getSignedWCharType() const {
3763 // FIXME: derive from "Target" ?
3767 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3768 /// Used when in C++, as a GCC extension.
3769 QualType ASTContext::getUnsignedWCharType() const {
3770 // FIXME: derive from "Target" ?
3771 return UnsignedIntTy;
3774 QualType ASTContext::getIntPtrType() const {
3775 return getFromTargetType(Target->getIntPtrType());
3778 QualType ASTContext::getUIntPtrType() const {
3779 return getCorrespondingUnsignedType(getIntPtrType());
3782 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3783 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3784 QualType ASTContext::getPointerDiffType() const {
3785 return getFromTargetType(Target->getPtrDiffType(0));
3788 /// \brief Return the unique type for "pid_t" defined in
3789 /// <sys/types.h>. We need this to compute the correct type for vfork().
3790 QualType ASTContext::getProcessIDType() const {
3791 return getFromTargetType(Target->getProcessIDType());
3794 //===----------------------------------------------------------------------===//
3796 //===----------------------------------------------------------------------===//
3798 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3799 // Push qualifiers into arrays, and then discard any remaining
3801 T = getCanonicalType(T);
3802 T = getVariableArrayDecayedType(T);
3803 const Type *Ty = T.getTypePtr();
3805 if (isa<ArrayType>(Ty)) {
3806 Result = getArrayDecayedType(QualType(Ty,0));
3807 } else if (isa<FunctionType>(Ty)) {
3808 Result = getPointerType(QualType(Ty, 0));
3810 Result = QualType(Ty, 0);
3813 return CanQualType::CreateUnsafe(Result);
3816 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3817 Qualifiers &quals) {
3818 SplitQualType splitType = type.getSplitUnqualifiedType();
3820 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3821 // the unqualified desugared type and then drops it on the floor.
3822 // We then have to strip that sugar back off with
3823 // getUnqualifiedDesugaredType(), which is silly.
3824 const ArrayType *AT =
3825 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3827 // If we don't have an array, just use the results in splitType.
3829 quals = splitType.Quals;
3830 return QualType(splitType.Ty, 0);
3833 // Otherwise, recurse on the array's element type.
3834 QualType elementType = AT->getElementType();
3835 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3837 // If that didn't change the element type, AT has no qualifiers, so we
3838 // can just use the results in splitType.
3839 if (elementType == unqualElementType) {
3840 assert(quals.empty()); // from the recursive call
3841 quals = splitType.Quals;
3842 return QualType(splitType.Ty, 0);
3845 // Otherwise, add in the qualifiers from the outermost type, then
3846 // build the type back up.
3847 quals.addConsistentQualifiers(splitType.Quals);
3849 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3850 return getConstantArrayType(unqualElementType, CAT->getSize(),
3851 CAT->getSizeModifier(), 0);
3854 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3855 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3858 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3859 return getVariableArrayType(unqualElementType,
3861 VAT->getSizeModifier(),
3862 VAT->getIndexTypeCVRQualifiers(),
3863 VAT->getBracketsRange());
3866 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3867 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3868 DSAT->getSizeModifier(), 0,
3872 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3873 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3874 /// they point to and return true. If T1 and T2 aren't pointer types
3875 /// or pointer-to-member types, or if they are not similar at this
3876 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3877 /// qualifiers on T1 and T2 are ignored. This function will typically
3878 /// be called in a loop that successively "unwraps" pointer and
3879 /// pointer-to-member types to compare them at each level.
3880 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3881 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3882 *T2PtrType = T2->getAs<PointerType>();
3883 if (T1PtrType && T2PtrType) {
3884 T1 = T1PtrType->getPointeeType();
3885 T2 = T2PtrType->getPointeeType();
3889 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3890 *T2MPType = T2->getAs<MemberPointerType>();
3891 if (T1MPType && T2MPType &&
3892 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3893 QualType(T2MPType->getClass(), 0))) {
3894 T1 = T1MPType->getPointeeType();
3895 T2 = T2MPType->getPointeeType();
3899 if (getLangOpts().ObjC1) {
3900 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3901 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3902 if (T1OPType && T2OPType) {
3903 T1 = T1OPType->getPointeeType();
3904 T2 = T2OPType->getPointeeType();
3909 // FIXME: Block pointers, too?
3915 ASTContext::getNameForTemplate(TemplateName Name,
3916 SourceLocation NameLoc) const {
3917 switch (Name.getKind()) {
3918 case TemplateName::QualifiedTemplate:
3919 case TemplateName::Template:
3920 // DNInfo work in progress: CHECKME: what about DNLoc?
3921 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3924 case TemplateName::OverloadedTemplate: {
3925 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3926 // DNInfo work in progress: CHECKME: what about DNLoc?
3927 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3930 case TemplateName::DependentTemplate: {
3931 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3932 DeclarationName DName;
3933 if (DTN->isIdentifier()) {
3934 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3935 return DeclarationNameInfo(DName, NameLoc);
3937 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3938 // DNInfo work in progress: FIXME: source locations?
3939 DeclarationNameLoc DNLoc;
3940 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3941 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3942 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3946 case TemplateName::SubstTemplateTemplateParm: {
3947 SubstTemplateTemplateParmStorage *subst
3948 = Name.getAsSubstTemplateTemplateParm();
3949 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3953 case TemplateName::SubstTemplateTemplateParmPack: {
3954 SubstTemplateTemplateParmPackStorage *subst
3955 = Name.getAsSubstTemplateTemplateParmPack();
3956 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3961 llvm_unreachable("bad template name kind!");
3964 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3965 switch (Name.getKind()) {
3966 case TemplateName::QualifiedTemplate:
3967 case TemplateName::Template: {
3968 TemplateDecl *Template = Name.getAsTemplateDecl();
3969 if (TemplateTemplateParmDecl *TTP
3970 = dyn_cast<TemplateTemplateParmDecl>(Template))
3971 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3973 // The canonical template name is the canonical template declaration.
3974 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3977 case TemplateName::OverloadedTemplate:
3978 llvm_unreachable("cannot canonicalize overloaded template");
3980 case TemplateName::DependentTemplate: {
3981 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3982 assert(DTN && "Non-dependent template names must refer to template decls.");
3983 return DTN->CanonicalTemplateName;
3986 case TemplateName::SubstTemplateTemplateParm: {
3987 SubstTemplateTemplateParmStorage *subst
3988 = Name.getAsSubstTemplateTemplateParm();
3989 return getCanonicalTemplateName(subst->getReplacement());
3992 case TemplateName::SubstTemplateTemplateParmPack: {
3993 SubstTemplateTemplateParmPackStorage *subst
3994 = Name.getAsSubstTemplateTemplateParmPack();
3995 TemplateTemplateParmDecl *canonParameter
3996 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3997 TemplateArgument canonArgPack
3998 = getCanonicalTemplateArgument(subst->getArgumentPack());
3999 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4003 llvm_unreachable("bad template name!");
4006 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4007 X = getCanonicalTemplateName(X);
4008 Y = getCanonicalTemplateName(Y);
4009 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4013 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4014 switch (Arg.getKind()) {
4015 case TemplateArgument::Null:
4018 case TemplateArgument::Expression:
4021 case TemplateArgument::Declaration: {
4022 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4023 return TemplateArgument(D, Arg.isDeclForReferenceParam());
4026 case TemplateArgument::NullPtr:
4027 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4030 case TemplateArgument::Template:
4031 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4033 case TemplateArgument::TemplateExpansion:
4034 return TemplateArgument(getCanonicalTemplateName(
4035 Arg.getAsTemplateOrTemplatePattern()),
4036 Arg.getNumTemplateExpansions());
4038 case TemplateArgument::Integral:
4039 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4041 case TemplateArgument::Type:
4042 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4044 case TemplateArgument::Pack: {
4045 if (Arg.pack_size() == 0)
4048 TemplateArgument *CanonArgs
4049 = new (*this) TemplateArgument[Arg.pack_size()];
4051 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4052 AEnd = Arg.pack_end();
4053 A != AEnd; (void)++A, ++Idx)
4054 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4056 return TemplateArgument(CanonArgs, Arg.pack_size());
4060 // Silence GCC warning
4061 llvm_unreachable("Unhandled template argument kind");
4064 NestedNameSpecifier *
4065 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4069 switch (NNS->getKind()) {
4070 case NestedNameSpecifier::Identifier:
4071 // Canonicalize the prefix but keep the identifier the same.
4072 return NestedNameSpecifier::Create(*this,
4073 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4074 NNS->getAsIdentifier());
4076 case NestedNameSpecifier::Namespace:
4077 // A namespace is canonical; build a nested-name-specifier with
4078 // this namespace and no prefix.
4079 return NestedNameSpecifier::Create(*this, 0,
4080 NNS->getAsNamespace()->getOriginalNamespace());
4082 case NestedNameSpecifier::NamespaceAlias:
4083 // A namespace is canonical; build a nested-name-specifier with
4084 // this namespace and no prefix.
4085 return NestedNameSpecifier::Create(*this, 0,
4086 NNS->getAsNamespaceAlias()->getNamespace()
4087 ->getOriginalNamespace());
4089 case NestedNameSpecifier::TypeSpec:
4090 case NestedNameSpecifier::TypeSpecWithTemplate: {
4091 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4093 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4094 // break it apart into its prefix and identifier, then reconsititute those
4095 // as the canonical nested-name-specifier. This is required to canonicalize
4096 // a dependent nested-name-specifier involving typedefs of dependent-name
4098 // typedef typename T::type T1;
4099 // typedef typename T1::type T2;
4100 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4101 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4102 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4104 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4105 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4107 return NestedNameSpecifier::Create(*this, 0, false,
4108 const_cast<Type*>(T.getTypePtr()));
4111 case NestedNameSpecifier::Global:
4112 // The global specifier is canonical and unique.
4116 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4120 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4121 // Handle the non-qualified case efficiently.
4122 if (!T.hasLocalQualifiers()) {
4123 // Handle the common positive case fast.
4124 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4128 // Handle the common negative case fast.
4129 if (!isa<ArrayType>(T.getCanonicalType()))
4132 // Apply any qualifiers from the array type to the element type. This
4133 // implements C99 6.7.3p8: "If the specification of an array type includes
4134 // any type qualifiers, the element type is so qualified, not the array type."
4136 // If we get here, we either have type qualifiers on the type, or we have
4137 // sugar such as a typedef in the way. If we have type qualifiers on the type
4138 // we must propagate them down into the element type.
4140 SplitQualType split = T.getSplitDesugaredType();
4141 Qualifiers qs = split.Quals;
4143 // If we have a simple case, just return now.
4144 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4145 if (ATy == 0 || qs.empty())
4148 // Otherwise, we have an array and we have qualifiers on it. Push the
4149 // qualifiers into the array element type and return a new array type.
4150 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4153 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4154 CAT->getSizeModifier(),
4155 CAT->getIndexTypeCVRQualifiers()));
4156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4157 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4158 IAT->getSizeModifier(),
4159 IAT->getIndexTypeCVRQualifiers()));
4161 if (const DependentSizedArrayType *DSAT
4162 = dyn_cast<DependentSizedArrayType>(ATy))
4163 return cast<ArrayType>(
4164 getDependentSizedArrayType(NewEltTy,
4165 DSAT->getSizeExpr(),
4166 DSAT->getSizeModifier(),
4167 DSAT->getIndexTypeCVRQualifiers(),
4168 DSAT->getBracketsRange()));
4170 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4171 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4173 VAT->getSizeModifier(),
4174 VAT->getIndexTypeCVRQualifiers(),
4175 VAT->getBracketsRange()));
4178 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4179 if (T->isArrayType() || T->isFunctionType())
4180 return getDecayedType(T);
4184 QualType ASTContext::getSignatureParameterType(QualType T) const {
4185 T = getVariableArrayDecayedType(T);
4186 T = getAdjustedParameterType(T);
4187 return T.getUnqualifiedType();
4190 /// getArrayDecayedType - Return the properly qualified result of decaying the
4191 /// specified array type to a pointer. This operation is non-trivial when
4192 /// handling typedefs etc. The canonical type of "T" must be an array type,
4193 /// this returns a pointer to a properly qualified element of the array.
4195 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4196 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4197 // Get the element type with 'getAsArrayType' so that we don't lose any
4198 // typedefs in the element type of the array. This also handles propagation
4199 // of type qualifiers from the array type into the element type if present
4201 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4202 assert(PrettyArrayType && "Not an array type!");
4204 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4206 // int x[restrict 4] -> int *restrict
4207 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4210 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4211 return getBaseElementType(array->getElementType());
4214 QualType ASTContext::getBaseElementType(QualType type) const {
4217 SplitQualType split = type.getSplitDesugaredType();
4218 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4221 type = array->getElementType();
4222 qs.addConsistentQualifiers(split.Quals);
4225 return getQualifiedType(type, qs);
4228 /// getConstantArrayElementCount - Returns number of constant array elements.
4230 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4231 uint64_t ElementCount = 1;
4233 ElementCount *= CA->getSize().getZExtValue();
4234 CA = dyn_cast_or_null<ConstantArrayType>(
4235 CA->getElementType()->getAsArrayTypeUnsafe());
4237 return ElementCount;
4240 /// getFloatingRank - Return a relative rank for floating point types.
4241 /// This routine will assert if passed a built-in type that isn't a float.
4242 static FloatingRank getFloatingRank(QualType T) {
4243 if (const ComplexType *CT = T->getAs<ComplexType>())
4244 return getFloatingRank(CT->getElementType());
4246 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4247 switch (T->getAs<BuiltinType>()->getKind()) {
4248 default: llvm_unreachable("getFloatingRank(): not a floating type");
4249 case BuiltinType::Half: return HalfRank;
4250 case BuiltinType::Float: return FloatRank;
4251 case BuiltinType::Double: return DoubleRank;
4252 case BuiltinType::LongDouble: return LongDoubleRank;
4256 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4257 /// point or a complex type (based on typeDomain/typeSize).
4258 /// 'typeDomain' is a real floating point or complex type.
4259 /// 'typeSize' is a real floating point or complex type.
4260 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4261 QualType Domain) const {
4262 FloatingRank EltRank = getFloatingRank(Size);
4263 if (Domain->isComplexType()) {
4265 case HalfRank: llvm_unreachable("Complex half is not supported");
4266 case FloatRank: return FloatComplexTy;
4267 case DoubleRank: return DoubleComplexTy;
4268 case LongDoubleRank: return LongDoubleComplexTy;
4272 assert(Domain->isRealFloatingType() && "Unknown domain!");
4274 case HalfRank: return HalfTy;
4275 case FloatRank: return FloatTy;
4276 case DoubleRank: return DoubleTy;
4277 case LongDoubleRank: return LongDoubleTy;
4279 llvm_unreachable("getFloatingRank(): illegal value for rank");
4282 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4283 /// point types, ignoring the domain of the type (i.e. 'double' ==
4284 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4285 /// LHS < RHS, return -1.
4286 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4287 FloatingRank LHSR = getFloatingRank(LHS);
4288 FloatingRank RHSR = getFloatingRank(RHS);
4297 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4298 /// routine will assert if passed a built-in type that isn't an integer or enum,
4299 /// or if it is not canonicalized.
4300 unsigned ASTContext::getIntegerRank(const Type *T) const {
4301 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4303 switch (cast<BuiltinType>(T)->getKind()) {
4304 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4305 case BuiltinType::Bool:
4306 return 1 + (getIntWidth(BoolTy) << 3);
4307 case BuiltinType::Char_S:
4308 case BuiltinType::Char_U:
4309 case BuiltinType::SChar:
4310 case BuiltinType::UChar:
4311 return 2 + (getIntWidth(CharTy) << 3);
4312 case BuiltinType::Short:
4313 case BuiltinType::UShort:
4314 return 3 + (getIntWidth(ShortTy) << 3);
4315 case BuiltinType::Int:
4316 case BuiltinType::UInt:
4317 return 4 + (getIntWidth(IntTy) << 3);
4318 case BuiltinType::Long:
4319 case BuiltinType::ULong:
4320 return 5 + (getIntWidth(LongTy) << 3);
4321 case BuiltinType::LongLong:
4322 case BuiltinType::ULongLong:
4323 return 6 + (getIntWidth(LongLongTy) << 3);
4324 case BuiltinType::Int128:
4325 case BuiltinType::UInt128:
4326 return 7 + (getIntWidth(Int128Ty) << 3);
4330 /// \brief Whether this is a promotable bitfield reference according
4331 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4333 /// \returns the type this bit-field will promote to, or NULL if no
4334 /// promotion occurs.
4335 QualType ASTContext::isPromotableBitField(Expr *E) const {
4336 if (E->isTypeDependent() || E->isValueDependent())
4339 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4343 QualType FT = Field->getType();
4345 uint64_t BitWidth = Field->getBitWidthValue(*this);
4346 uint64_t IntSize = getTypeSize(IntTy);
4347 // GCC extension compatibility: if the bit-field size is less than or equal
4348 // to the size of int, it gets promoted no matter what its type is.
4349 // For instance, unsigned long bf : 4 gets promoted to signed int.
4350 if (BitWidth < IntSize)
4353 if (BitWidth == IntSize)
4354 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4356 // Types bigger than int are not subject to promotions, and therefore act
4357 // like the base type.
4358 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4363 /// getPromotedIntegerType - Returns the type that Promotable will
4364 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4366 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4367 assert(!Promotable.isNull());
4368 assert(Promotable->isPromotableIntegerType());
4369 if (const EnumType *ET = Promotable->getAs<EnumType>())
4370 return ET->getDecl()->getPromotionType();
4372 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4373 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4374 // (3.9.1) can be converted to a prvalue of the first of the following
4375 // types that can represent all the values of its underlying type:
4376 // int, unsigned int, long int, unsigned long int, long long int, or
4377 // unsigned long long int [...]
4378 // FIXME: Is there some better way to compute this?
4379 if (BT->getKind() == BuiltinType::WChar_S ||
4380 BT->getKind() == BuiltinType::WChar_U ||
4381 BT->getKind() == BuiltinType::Char16 ||
4382 BT->getKind() == BuiltinType::Char32) {
4383 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4384 uint64_t FromSize = getTypeSize(BT);
4385 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4386 LongLongTy, UnsignedLongLongTy };
4387 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4388 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4389 if (FromSize < ToSize ||
4390 (FromSize == ToSize &&
4391 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4392 return PromoteTypes[Idx];
4394 llvm_unreachable("char type should fit into long long");
4398 // At this point, we should have a signed or unsigned integer type.
4399 if (Promotable->isSignedIntegerType())
4401 uint64_t PromotableSize = getIntWidth(Promotable);
4402 uint64_t IntSize = getIntWidth(IntTy);
4403 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4404 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4407 /// \brief Recurses in pointer/array types until it finds an objc retainable
4408 /// type and returns its ownership.
4409 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4410 while (!T.isNull()) {
4411 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4412 return T.getObjCLifetime();
4413 if (T->isArrayType())
4414 T = getBaseElementType(T);
4415 else if (const PointerType *PT = T->getAs<PointerType>())
4416 T = PT->getPointeeType();
4417 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4418 T = RT->getPointeeType();
4423 return Qualifiers::OCL_None;
4426 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4427 // Incomplete enum types are not treated as integer types.
4428 // FIXME: In C++, enum types are never integer types.
4429 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4430 return ET->getDecl()->getIntegerType().getTypePtr();
4434 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4435 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4436 /// LHS < RHS, return -1.
4437 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4438 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4439 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4441 // Unwrap enums to their underlying type.
4442 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4443 LHSC = getIntegerTypeForEnum(ET);
4444 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4445 RHSC = getIntegerTypeForEnum(ET);
4447 if (LHSC == RHSC) return 0;
4449 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4450 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4452 unsigned LHSRank = getIntegerRank(LHSC);
4453 unsigned RHSRank = getIntegerRank(RHSC);
4455 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4456 if (LHSRank == RHSRank) return 0;
4457 return LHSRank > RHSRank ? 1 : -1;
4460 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4462 // If the unsigned [LHS] type is larger, return it.
4463 if (LHSRank >= RHSRank)
4466 // If the signed type can represent all values of the unsigned type, it
4467 // wins. Because we are dealing with 2's complement and types that are
4468 // powers of two larger than each other, this is always safe.
4472 // If the unsigned [RHS] type is larger, return it.
4473 if (RHSRank >= LHSRank)
4476 // If the signed type can represent all values of the unsigned type, it
4477 // wins. Because we are dealing with 2's complement and types that are
4478 // powers of two larger than each other, this is always safe.
4483 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4484 DeclContext *DC, IdentifierInfo *Id) {
4486 if (Ctx.getLangOpts().CPlusPlus)
4487 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4489 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4492 // getCFConstantStringType - Return the type used for constant CFStrings.
4493 QualType ASTContext::getCFConstantStringType() const {
4494 if (!CFConstantStringTypeDecl) {
4495 CFConstantStringTypeDecl =
4496 CreateRecordDecl(*this, TTK_Struct, TUDecl,
4497 &Idents.get("NSConstantString"));
4498 CFConstantStringTypeDecl->startDefinition();
4500 QualType FieldTypes[4];
4503 FieldTypes[0] = getPointerType(IntTy.withConst());
4505 FieldTypes[1] = IntTy;
4507 FieldTypes[2] = getPointerType(CharTy.withConst());
4509 FieldTypes[3] = LongTy;
4512 for (unsigned i = 0; i < 4; ++i) {
4513 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4515 SourceLocation(), 0,
4516 FieldTypes[i], /*TInfo=*/0,
4520 Field->setAccess(AS_public);
4521 CFConstantStringTypeDecl->addDecl(Field);
4524 CFConstantStringTypeDecl->completeDefinition();
4527 return getTagDeclType(CFConstantStringTypeDecl);
4530 QualType ASTContext::getObjCSuperType() const {
4531 if (ObjCSuperType.isNull()) {
4532 RecordDecl *ObjCSuperTypeDecl =
4533 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4534 TUDecl->addDecl(ObjCSuperTypeDecl);
4535 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4537 return ObjCSuperType;
4540 void ASTContext::setCFConstantStringType(QualType T) {
4541 const RecordType *Rec = T->getAs<RecordType>();
4542 assert(Rec && "Invalid CFConstantStringType");
4543 CFConstantStringTypeDecl = Rec->getDecl();
4546 QualType ASTContext::getBlockDescriptorType() const {
4547 if (BlockDescriptorType)
4548 return getTagDeclType(BlockDescriptorType);
4551 // FIXME: Needs the FlagAppleBlock bit.
4552 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4553 &Idents.get("__block_descriptor"));
4554 T->startDefinition();
4556 QualType FieldTypes[] = {
4561 static const char *const FieldNames[] = {
4566 for (size_t i = 0; i < 2; ++i) {
4567 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4569 &Idents.get(FieldNames[i]),
4570 FieldTypes[i], /*TInfo=*/0,
4574 Field->setAccess(AS_public);
4578 T->completeDefinition();
4580 BlockDescriptorType = T;
4582 return getTagDeclType(BlockDescriptorType);
4585 QualType ASTContext::getBlockDescriptorExtendedType() const {
4586 if (BlockDescriptorExtendedType)
4587 return getTagDeclType(BlockDescriptorExtendedType);
4590 // FIXME: Needs the FlagAppleBlock bit.
4591 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4592 &Idents.get("__block_descriptor_withcopydispose"));
4593 T->startDefinition();
4595 QualType FieldTypes[] = {
4598 getPointerType(VoidPtrTy),
4599 getPointerType(VoidPtrTy)
4602 static const char *const FieldNames[] = {
4609 for (size_t i = 0; i < 4; ++i) {
4610 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4612 &Idents.get(FieldNames[i]),
4613 FieldTypes[i], /*TInfo=*/0,
4617 Field->setAccess(AS_public);
4621 T->completeDefinition();
4623 BlockDescriptorExtendedType = T;
4625 return getTagDeclType(BlockDescriptorExtendedType);
4628 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4629 /// requires copy/dispose. Note that this must match the logic
4630 /// in buildByrefHelpers.
4631 bool ASTContext::BlockRequiresCopying(QualType Ty,
4633 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4634 const Expr *copyExpr = getBlockVarCopyInits(D);
4635 if (!copyExpr && record->hasTrivialDestructor()) return false;
4640 if (!Ty->isObjCRetainableType()) return false;
4642 Qualifiers qs = Ty.getQualifiers();
4644 // If we have lifetime, that dominates.
4645 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4646 assert(getLangOpts().ObjCAutoRefCount);
4649 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4651 // These are just bits as far as the runtime is concerned.
4652 case Qualifiers::OCL_ExplicitNone:
4653 case Qualifiers::OCL_Autoreleasing:
4656 // Tell the runtime that this is ARC __weak, called by the
4658 case Qualifiers::OCL_Weak:
4659 // ARC __strong __block variables need to be retained.
4660 case Qualifiers::OCL_Strong:
4663 llvm_unreachable("fell out of lifetime switch!");
4665 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4666 Ty->isObjCObjectPointerType());
4669 bool ASTContext::getByrefLifetime(QualType Ty,
4670 Qualifiers::ObjCLifetime &LifeTime,
4671 bool &HasByrefExtendedLayout) const {
4673 if (!getLangOpts().ObjC1 ||
4674 getLangOpts().getGC() != LangOptions::NonGC)
4677 HasByrefExtendedLayout = false;
4678 if (Ty->isRecordType()) {
4679 HasByrefExtendedLayout = true;
4680 LifeTime = Qualifiers::OCL_None;
4682 else if (getLangOpts().ObjCAutoRefCount)
4683 LifeTime = Ty.getObjCLifetime();
4685 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4686 LifeTime = Qualifiers::OCL_ExplicitNone;
4688 LifeTime = Qualifiers::OCL_None;
4692 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4693 if (!ObjCInstanceTypeDecl)
4694 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4695 getTranslationUnitDecl(),
4698 &Idents.get("instancetype"),
4699 getTrivialTypeSourceInfo(getObjCIdType()));
4700 return ObjCInstanceTypeDecl;
4703 // This returns true if a type has been typedefed to BOOL:
4704 // typedef <type> BOOL;
4705 static bool isTypeTypedefedAsBOOL(QualType T) {
4706 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4707 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4708 return II->isStr("BOOL");
4713 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4715 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4716 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4717 return CharUnits::Zero();
4719 CharUnits sz = getTypeSizeInChars(type);
4721 // Make all integer and enum types at least as large as an int
4722 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4723 sz = std::max(sz, getTypeSizeInChars(IntTy));
4724 // Treat arrays as pointers, since that's how they're passed in.
4725 else if (type->isArrayType())
4726 sz = getTypeSizeInChars(VoidPtrTy);
4731 std::string charUnitsToString(const CharUnits &CU) {
4732 return llvm::itostr(CU.getQuantity());
4735 /// getObjCEncodingForBlock - Return the encoded type for this block
4737 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4740 const BlockDecl *Decl = Expr->getBlockDecl();
4742 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4743 // Encode result type.
4744 if (getLangOpts().EncodeExtendedBlockSig)
4745 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4746 BlockTy->getAs<FunctionType>()->getResultType(),
4747 S, true /*Extended*/);
4749 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4751 // Compute size of all parameters.
4752 // Start with computing size of a pointer in number of bytes.
4753 // FIXME: There might(should) be a better way of doing this computation!
4755 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4756 CharUnits ParmOffset = PtrSize;
4757 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4758 E = Decl->param_end(); PI != E; ++PI) {
4759 QualType PType = (*PI)->getType();
4760 CharUnits sz = getObjCEncodingTypeSize(PType);
4763 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4766 // Size of the argument frame
4767 S += charUnitsToString(ParmOffset);
4768 // Block pointer and offset.
4772 ParmOffset = PtrSize;
4773 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4774 Decl->param_end(); PI != E; ++PI) {
4775 ParmVarDecl *PVDecl = *PI;
4776 QualType PType = PVDecl->getOriginalType();
4777 if (const ArrayType *AT =
4778 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4779 // Use array's original type only if it has known number of
4781 if (!isa<ConstantArrayType>(AT))
4782 PType = PVDecl->getType();
4783 } else if (PType->isFunctionType())
4784 PType = PVDecl->getType();
4785 if (getLangOpts().EncodeExtendedBlockSig)
4786 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4787 S, true /*Extended*/);
4789 getObjCEncodingForType(PType, S);
4790 S += charUnitsToString(ParmOffset);
4791 ParmOffset += getObjCEncodingTypeSize(PType);
4797 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4799 // Encode result type.
4800 getObjCEncodingForType(Decl->getResultType(), S);
4801 CharUnits ParmOffset;
4802 // Compute size of all parameters.
4803 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4804 E = Decl->param_end(); PI != E; ++PI) {
4805 QualType PType = (*PI)->getType();
4806 CharUnits sz = getObjCEncodingTypeSize(PType);
4810 assert (sz.isPositive() &&
4811 "getObjCEncodingForFunctionDecl - Incomplete param type");
4814 S += charUnitsToString(ParmOffset);
4815 ParmOffset = CharUnits::Zero();
4818 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4819 E = Decl->param_end(); PI != E; ++PI) {
4820 ParmVarDecl *PVDecl = *PI;
4821 QualType PType = PVDecl->getOriginalType();
4822 if (const ArrayType *AT =
4823 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4824 // Use array's original type only if it has known number of
4826 if (!isa<ConstantArrayType>(AT))
4827 PType = PVDecl->getType();
4828 } else if (PType->isFunctionType())
4829 PType = PVDecl->getType();
4830 getObjCEncodingForType(PType, S);
4831 S += charUnitsToString(ParmOffset);
4832 ParmOffset += getObjCEncodingTypeSize(PType);
4838 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4839 /// method parameter or return type. If Extended, include class names and
4840 /// block object types.
4841 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4842 QualType T, std::string& S,
4843 bool Extended) const {
4844 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4845 getObjCEncodingForTypeQualifier(QT, S);
4846 // Encode parameter type.
4847 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4848 true /*OutermostType*/,
4849 false /*EncodingProperty*/,
4850 false /*StructField*/,
4851 Extended /*EncodeBlockParameters*/,
4852 Extended /*EncodeClassNames*/);
4855 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4857 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4859 bool Extended) const {
4860 // FIXME: This is not very efficient.
4861 // Encode return type.
4862 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4863 Decl->getResultType(), S, Extended);
4864 // Compute size of all parameters.
4865 // Start with computing size of a pointer in number of bytes.
4866 // FIXME: There might(should) be a better way of doing this computation!
4868 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4869 // The first two arguments (self and _cmd) are pointers; account for
4871 CharUnits ParmOffset = 2 * PtrSize;
4872 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4873 E = Decl->sel_param_end(); PI != E; ++PI) {
4874 QualType PType = (*PI)->getType();
4875 CharUnits sz = getObjCEncodingTypeSize(PType);
4879 assert (sz.isPositive() &&
4880 "getObjCEncodingForMethodDecl - Incomplete param type");
4883 S += charUnitsToString(ParmOffset);
4885 S += charUnitsToString(PtrSize);
4888 ParmOffset = 2 * PtrSize;
4889 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4890 E = Decl->sel_param_end(); PI != E; ++PI) {
4891 const ParmVarDecl *PVDecl = *PI;
4892 QualType PType = PVDecl->getOriginalType();
4893 if (const ArrayType *AT =
4894 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4895 // Use array's original type only if it has known number of
4897 if (!isa<ConstantArrayType>(AT))
4898 PType = PVDecl->getType();
4899 } else if (PType->isFunctionType())
4900 PType = PVDecl->getType();
4901 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4902 PType, S, Extended);
4903 S += charUnitsToString(ParmOffset);
4904 ParmOffset += getObjCEncodingTypeSize(PType);
4910 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4911 /// property declaration. If non-NULL, Container must be either an
4912 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4913 /// NULL when getting encodings for protocol properties.
4914 /// Property attributes are stored as a comma-delimited C string. The simple
4915 /// attributes readonly and bycopy are encoded as single characters. The
4916 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4917 /// encoded as single characters, followed by an identifier. Property types
4918 /// are also encoded as a parametrized attribute. The characters used to encode
4919 /// these attributes are defined by the following enumeration:
4921 /// enum PropertyAttributes {
4922 /// kPropertyReadOnly = 'R', // property is read-only.
4923 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4924 /// kPropertyByref = '&', // property is a reference to the value last assigned
4925 /// kPropertyDynamic = 'D', // property is dynamic
4926 /// kPropertyGetter = 'G', // followed by getter selector name
4927 /// kPropertySetter = 'S', // followed by setter selector name
4928 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4929 /// kPropertyType = 'T' // followed by old-style type encoding.
4930 /// kPropertyWeak = 'W' // 'weak' property
4931 /// kPropertyStrong = 'P' // property GC'able
4932 /// kPropertyNonAtomic = 'N' // property non-atomic
4935 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4936 const Decl *Container,
4937 std::string& S) const {
4938 // Collect information from the property implementation decl(s).
4939 bool Dynamic = false;
4940 ObjCPropertyImplDecl *SynthesizePID = 0;
4942 // FIXME: Duplicated code due to poor abstraction.
4944 if (const ObjCCategoryImplDecl *CID =
4945 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4946 for (ObjCCategoryImplDecl::propimpl_iterator
4947 i = CID->propimpl_begin(), e = CID->propimpl_end();
4949 ObjCPropertyImplDecl *PID = *i;
4950 if (PID->getPropertyDecl() == PD) {
4951 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4954 SynthesizePID = PID;
4959 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4960 for (ObjCCategoryImplDecl::propimpl_iterator
4961 i = OID->propimpl_begin(), e = OID->propimpl_end();
4963 ObjCPropertyImplDecl *PID = *i;
4964 if (PID->getPropertyDecl() == PD) {
4965 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4968 SynthesizePID = PID;
4975 // FIXME: This is not very efficient.
4978 // Encode result type.
4979 // GCC has some special rules regarding encoding of properties which
4980 // closely resembles encoding of ivars.
4981 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4982 true /* outermost type */,
4983 true /* encoding for property */);
4985 if (PD->isReadOnly()) {
4987 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4989 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4992 switch (PD->getSetterKind()) {
4993 case ObjCPropertyDecl::Assign: break;
4994 case ObjCPropertyDecl::Copy: S += ",C"; break;
4995 case ObjCPropertyDecl::Retain: S += ",&"; break;
4996 case ObjCPropertyDecl::Weak: S += ",W"; break;
5000 // It really isn't clear at all what this means, since properties
5001 // are "dynamic by default".
5005 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5008 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5010 S += PD->getGetterName().getAsString();
5013 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5015 S += PD->getSetterName().getAsString();
5018 if (SynthesizePID) {
5019 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5021 S += OID->getNameAsString();
5024 // FIXME: OBJCGC: weak & strong
5027 /// getLegacyIntegralTypeEncoding -
5028 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5029 /// 'l' or 'L' , but not always. For typedefs, we need to use
5030 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5032 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5033 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5034 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5035 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5036 PointeeTy = UnsignedIntTy;
5038 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5044 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5045 const FieldDecl *Field) const {
5046 // We follow the behavior of gcc, expanding structures which are
5047 // directly pointed to, and expanding embedded structures. Note that
5048 // these rules are sufficient to prevent recursive encoding of the
5050 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5051 true /* outermost type */);
5054 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5055 BuiltinType::Kind kind) {
5057 case BuiltinType::Void: return 'v';
5058 case BuiltinType::Bool: return 'B';
5059 case BuiltinType::Char_U:
5060 case BuiltinType::UChar: return 'C';
5061 case BuiltinType::Char16:
5062 case BuiltinType::UShort: return 'S';
5063 case BuiltinType::Char32:
5064 case BuiltinType::UInt: return 'I';
5065 case BuiltinType::ULong:
5066 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5067 case BuiltinType::UInt128: return 'T';
5068 case BuiltinType::ULongLong: return 'Q';
5069 case BuiltinType::Char_S:
5070 case BuiltinType::SChar: return 'c';
5071 case BuiltinType::Short: return 's';
5072 case BuiltinType::WChar_S:
5073 case BuiltinType::WChar_U:
5074 case BuiltinType::Int: return 'i';
5075 case BuiltinType::Long:
5076 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5077 case BuiltinType::LongLong: return 'q';
5078 case BuiltinType::Int128: return 't';
5079 case BuiltinType::Float: return 'f';
5080 case BuiltinType::Double: return 'd';
5081 case BuiltinType::LongDouble: return 'D';
5082 case BuiltinType::NullPtr: return '*'; // like char*
5084 case BuiltinType::Half:
5085 // FIXME: potentially need @encodes for these!
5088 case BuiltinType::ObjCId:
5089 case BuiltinType::ObjCClass:
5090 case BuiltinType::ObjCSel:
5091 llvm_unreachable("@encoding ObjC primitive type");
5093 // OpenCL and placeholder types don't need @encodings.
5094 case BuiltinType::OCLImage1d:
5095 case BuiltinType::OCLImage1dArray:
5096 case BuiltinType::OCLImage1dBuffer:
5097 case BuiltinType::OCLImage2d:
5098 case BuiltinType::OCLImage2dArray:
5099 case BuiltinType::OCLImage3d:
5100 case BuiltinType::OCLEvent:
5101 case BuiltinType::OCLSampler:
5102 case BuiltinType::Dependent:
5103 #define BUILTIN_TYPE(KIND, ID)
5104 #define PLACEHOLDER_TYPE(KIND, ID) \
5105 case BuiltinType::KIND:
5106 #include "clang/AST/BuiltinTypes.def"
5107 llvm_unreachable("invalid builtin type for @encode");
5109 llvm_unreachable("invalid BuiltinType::Kind value");
5112 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5113 EnumDecl *Enum = ET->getDecl();
5115 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5116 if (!Enum->isFixed())
5119 // The encoding of a fixed enum type matches its fixed underlying type.
5120 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5121 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5124 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5125 QualType T, const FieldDecl *FD) {
5126 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5128 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5129 // The GNU runtime requires more information; bitfields are encoded as b,
5130 // then the offset (in bits) of the first element, then the type of the
5131 // bitfield, then the size in bits. For example, in this structure:
5138 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5139 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5140 // information is not especially sensible, but we're stuck with it for
5141 // compatibility with GCC, although providing it breaks anything that
5142 // actually uses runtime introspection and wants to work on both runtimes...
5143 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5144 const RecordDecl *RD = FD->getParent();
5145 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5146 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5147 if (const EnumType *ET = T->getAs<EnumType>())
5148 S += ObjCEncodingForEnumType(Ctx, ET);
5150 const BuiltinType *BT = T->castAs<BuiltinType>();
5151 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5154 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5157 // FIXME: Use SmallString for accumulating string.
5158 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5159 bool ExpandPointedToStructures,
5160 bool ExpandStructures,
5161 const FieldDecl *FD,
5163 bool EncodingProperty,
5165 bool EncodeBlockParameters,
5166 bool EncodeClassNames,
5167 bool EncodePointerToObjCTypedef) const {
5168 CanQualType CT = getCanonicalType(T);
5169 switch (CT->getTypeClass()) {
5172 if (FD && FD->isBitField())
5173 return EncodeBitField(this, S, T, FD);
5174 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5175 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5177 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5180 case Type::Complex: {
5181 const ComplexType *CT = T->castAs<ComplexType>();
5183 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
5188 case Type::Atomic: {
5189 const AtomicType *AT = T->castAs<AtomicType>();
5191 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5196 // encoding for pointer or reference types.
5198 case Type::LValueReference:
5199 case Type::RValueReference: {
5201 if (isa<PointerType>(CT)) {
5202 const PointerType *PT = T->castAs<PointerType>();
5203 if (PT->isObjCSelType()) {
5207 PointeeTy = PT->getPointeeType();
5209 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5212 bool isReadOnly = false;
5213 // For historical/compatibility reasons, the read-only qualifier of the
5214 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5215 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5216 // Also, do not emit the 'r' for anything but the outermost type!
5217 if (isa<TypedefType>(T.getTypePtr())) {
5218 if (OutermostType && T.isConstQualified()) {
5222 } else if (OutermostType) {
5223 QualType P = PointeeTy;
5224 while (P->getAs<PointerType>())
5225 P = P->getAs<PointerType>()->getPointeeType();
5226 if (P.isConstQualified()) {
5232 // Another legacy compatibility encoding. Some ObjC qualifier and type
5233 // combinations need to be rearranged.
5234 // Rewrite "in const" from "nr" to "rn"
5235 if (StringRef(S).endswith("nr"))
5236 S.replace(S.end()-2, S.end(), "rn");
5239 if (PointeeTy->isCharType()) {
5240 // char pointer types should be encoded as '*' unless it is a
5241 // type that has been typedef'd to 'BOOL'.
5242 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5246 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5247 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5248 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5252 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5253 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5260 getLegacyIntegralTypeEncoding(PointeeTy);
5262 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5267 case Type::ConstantArray:
5268 case Type::IncompleteArray:
5269 case Type::VariableArray: {
5270 const ArrayType *AT = cast<ArrayType>(CT);
5272 if (isa<IncompleteArrayType>(AT) && !StructField) {
5273 // Incomplete arrays are encoded as a pointer to the array element.
5276 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5277 false, ExpandStructures, FD);
5281 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5282 S += llvm::utostr(CAT->getSize().getZExtValue());
5284 //Variable length arrays are encoded as a regular array with 0 elements.
5285 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5286 "Unknown array type!");
5290 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5291 false, ExpandStructures, FD);
5297 case Type::FunctionNoProto:
5298 case Type::FunctionProto:
5302 case Type::Record: {
5303 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5304 S += RDecl->isUnion() ? '(' : '{';
5305 // Anonymous structures print as '?'
5306 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5308 if (ClassTemplateSpecializationDecl *Spec
5309 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5310 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5311 llvm::raw_string_ostream OS(S);
5312 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5313 TemplateArgs.data(),
5314 TemplateArgs.size(),
5315 (*this).getPrintingPolicy());
5320 if (ExpandStructures) {
5322 if (!RDecl->isUnion()) {
5323 getObjCEncodingForStructureImpl(RDecl, S, FD);
5325 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5326 FieldEnd = RDecl->field_end();
5327 Field != FieldEnd; ++Field) {
5330 S += Field->getNameAsString();
5334 // Special case bit-fields.
5335 if (Field->isBitField()) {
5336 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5339 QualType qt = Field->getType();
5340 getLegacyIntegralTypeEncoding(qt);
5341 getObjCEncodingForTypeImpl(qt, S, false, true,
5342 FD, /*OutermostType*/false,
5343 /*EncodingProperty*/false,
5344 /*StructField*/true);
5349 S += RDecl->isUnion() ? ')' : '}';
5353 case Type::BlockPointer: {
5354 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5355 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5356 if (EncodeBlockParameters) {
5357 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5360 // Block return type
5361 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5362 ExpandPointedToStructures, ExpandStructures,
5364 false /* OutermostType */,
5366 false /* StructField */,
5367 EncodeBlockParameters,
5372 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5373 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5374 E = FPT->arg_type_end(); I && (I != E); ++I) {
5375 getObjCEncodingForTypeImpl(*I, S,
5376 ExpandPointedToStructures,
5379 false /* OutermostType */,
5381 false /* StructField */,
5382 EncodeBlockParameters,
5391 case Type::ObjCObject:
5392 case Type::ObjCInterface: {
5393 // Ignore protocol qualifiers when mangling at this level.
5394 T = T->castAs<ObjCObjectType>()->getBaseType();
5396 // The assumption seems to be that this assert will succeed
5397 // because nested levels will have filtered out 'id' and 'Class'.
5398 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5399 // @encode(class_name)
5400 ObjCInterfaceDecl *OI = OIT->getDecl();
5402 const IdentifierInfo *II = OI->getIdentifier();
5405 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5406 DeepCollectObjCIvars(OI, true, Ivars);
5407 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5408 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5409 if (Field->isBitField())
5410 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5412 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5413 false, false, false, false, false,
5414 EncodePointerToObjCTypedef);
5420 case Type::ObjCObjectPointer: {
5421 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5422 if (OPT->isObjCIdType()) {
5427 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5428 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5429 // Since this is a binary compatibility issue, need to consult with runtime
5430 // folks. Fortunately, this is a *very* obsure construct.
5435 if (OPT->isObjCQualifiedIdType()) {
5436 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5437 ExpandPointedToStructures,
5438 ExpandStructures, FD);
5439 if (FD || EncodingProperty || EncodeClassNames) {
5440 // Note that we do extended encoding of protocol qualifer list
5441 // Only when doing ivar or property encoding.
5443 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5444 E = OPT->qual_end(); I != E; ++I) {
5446 S += (*I)->getNameAsString();
5454 QualType PointeeTy = OPT->getPointeeType();
5455 if (!EncodingProperty &&
5456 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5457 !EncodePointerToObjCTypedef) {
5458 // Another historical/compatibility reason.
5459 // We encode the underlying type which comes out as
5462 if (FD && OPT->getInterfaceDecl()) {
5463 // Prevent recursive encoding of fields in some rare cases.
5464 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5465 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5466 DeepCollectObjCIvars(OI, true, Ivars);
5467 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5468 if (cast<FieldDecl>(Ivars[i]) == FD) {
5470 S += OI->getIdentifier()->getName();
5476 getObjCEncodingForTypeImpl(PointeeTy, S,
5477 false, ExpandPointedToStructures,
5479 false, false, false, false, false,
5480 /*EncodePointerToObjCTypedef*/true);
5485 if (OPT->getInterfaceDecl() &&
5486 (FD || EncodingProperty || EncodeClassNames)) {
5488 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5489 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5490 E = OPT->qual_end(); I != E; ++I) {
5492 S += (*I)->getNameAsString();
5500 // gcc just blithely ignores member pointers.
5501 // FIXME: we shoul do better than that. 'M' is available.
5502 case Type::MemberPointer:
5506 case Type::ExtVector:
5507 // This matches gcc's encoding, even though technically it is
5509 // FIXME. We should do a better job than gcc.
5513 // We could see an undeduced auto type here during error recovery.
5517 #define ABSTRACT_TYPE(KIND, BASE)
5518 #define TYPE(KIND, BASE)
5519 #define DEPENDENT_TYPE(KIND, BASE) \
5521 #define NON_CANONICAL_TYPE(KIND, BASE) \
5523 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5525 #include "clang/AST/TypeNodes.def"
5526 llvm_unreachable("@encode for dependent type!");
5528 llvm_unreachable("bad type kind!");
5531 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5533 const FieldDecl *FD,
5534 bool includeVBases) const {
5535 assert(RDecl && "Expected non-null RecordDecl");
5536 assert(!RDecl->isUnion() && "Should not be called for unions");
5537 if (!RDecl->getDefinition())
5540 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5541 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5542 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5545 for (CXXRecordDecl::base_class_iterator
5546 BI = CXXRec->bases_begin(),
5547 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5548 if (!BI->isVirtual()) {
5549 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5550 if (base->isEmpty())
5552 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5553 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5554 std::make_pair(offs, base));
5560 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5561 FieldEnd = RDecl->field_end();
5562 Field != FieldEnd; ++Field, ++i) {
5563 uint64_t offs = layout.getFieldOffset(i);
5564 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5565 std::make_pair(offs, *Field));
5568 if (CXXRec && includeVBases) {
5569 for (CXXRecordDecl::base_class_iterator
5570 BI = CXXRec->vbases_begin(),
5571 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5572 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5573 if (base->isEmpty())
5575 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5576 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5577 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5578 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5579 std::make_pair(offs, base));
5585 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5587 size = layout.getSize();
5590 uint64_t CurOffs = 0;
5591 std::multimap<uint64_t, NamedDecl *>::iterator
5592 CurLayObj = FieldOrBaseOffsets.begin();
5594 if (CXXRec && CXXRec->isDynamicClass() &&
5595 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5598 std::string recname = CXXRec->getNameAsString();
5599 if (recname.empty()) recname = "?";
5604 CurOffs += getTypeSize(VoidPtrTy);
5607 if (!RDecl->hasFlexibleArrayMember()) {
5608 // Mark the end of the structure.
5609 uint64_t offs = toBits(size);
5610 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5611 std::make_pair(offs, (NamedDecl*)0));
5614 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5615 assert(CurOffs <= CurLayObj->first);
5617 if (CurOffs < CurLayObj->first) {
5618 uint64_t padding = CurLayObj->first - CurOffs;
5619 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5620 // packing/alignment of members is different that normal, in which case
5621 // the encoding will be out-of-sync with the real layout.
5622 // If the runtime switches to just consider the size of types without
5623 // taking into account alignment, we could make padding explicit in the
5624 // encoding (e.g. using arrays of chars). The encoding strings would be
5625 // longer then though.
5629 NamedDecl *dcl = CurLayObj->second;
5631 break; // reached end of structure.
5633 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5634 // We expand the bases without their virtual bases since those are going
5635 // in the initial structure. Note that this differs from gcc which
5636 // expands virtual bases each time one is encountered in the hierarchy,
5637 // making the encoding type bigger than it really is.
5638 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5639 assert(!base->isEmpty());
5640 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5642 FieldDecl *field = cast<FieldDecl>(dcl);
5645 S += field->getNameAsString();
5649 if (field->isBitField()) {
5650 EncodeBitField(this, S, field->getType(), field);
5651 CurOffs += field->getBitWidthValue(*this);
5653 QualType qt = field->getType();
5654 getLegacyIntegralTypeEncoding(qt);
5655 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5656 /*OutermostType*/false,
5657 /*EncodingProperty*/false,
5658 /*StructField*/true);
5659 CurOffs += getTypeSize(field->getType());
5665 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5666 std::string& S) const {
5667 if (QT & Decl::OBJC_TQ_In)
5669 if (QT & Decl::OBJC_TQ_Inout)
5671 if (QT & Decl::OBJC_TQ_Out)
5673 if (QT & Decl::OBJC_TQ_Bycopy)
5675 if (QT & Decl::OBJC_TQ_Byref)
5677 if (QT & Decl::OBJC_TQ_Oneway)
5681 TypedefDecl *ASTContext::getObjCIdDecl() const {
5683 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5684 T = getObjCObjectPointerType(T);
5685 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5686 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5687 getTranslationUnitDecl(),
5688 SourceLocation(), SourceLocation(),
5689 &Idents.get("id"), IdInfo);
5695 TypedefDecl *ASTContext::getObjCSelDecl() const {
5697 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5698 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5699 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5700 getTranslationUnitDecl(),
5701 SourceLocation(), SourceLocation(),
5702 &Idents.get("SEL"), SelInfo);
5707 TypedefDecl *ASTContext::getObjCClassDecl() const {
5708 if (!ObjCClassDecl) {
5709 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5710 T = getObjCObjectPointerType(T);
5711 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5712 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5713 getTranslationUnitDecl(),
5714 SourceLocation(), SourceLocation(),
5715 &Idents.get("Class"), ClassInfo);
5718 return ObjCClassDecl;
5721 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5722 if (!ObjCProtocolClassDecl) {
5723 ObjCProtocolClassDecl
5724 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5726 &Idents.get("Protocol"),
5728 SourceLocation(), true);
5731 return ObjCProtocolClassDecl;
5734 //===----------------------------------------------------------------------===//
5735 // __builtin_va_list Construction Functions
5736 //===----------------------------------------------------------------------===//
5738 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5739 // typedef char* __builtin_va_list;
5740 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5741 TypeSourceInfo *TInfo
5742 = Context->getTrivialTypeSourceInfo(CharPtrType);
5744 TypedefDecl *VaListTypeDecl
5745 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5746 Context->getTranslationUnitDecl(),
5747 SourceLocation(), SourceLocation(),
5748 &Context->Idents.get("__builtin_va_list"),
5750 return VaListTypeDecl;
5753 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5754 // typedef void* __builtin_va_list;
5755 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5756 TypeSourceInfo *TInfo
5757 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5759 TypedefDecl *VaListTypeDecl
5760 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5761 Context->getTranslationUnitDecl(),
5762 SourceLocation(), SourceLocation(),
5763 &Context->Idents.get("__builtin_va_list"),
5765 return VaListTypeDecl;
5768 static TypedefDecl *
5769 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5770 RecordDecl *VaListTagDecl;
5771 if (Context->getLangOpts().CPlusPlus) {
5772 // namespace std { struct __va_list {
5774 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5775 Context->getTranslationUnitDecl(),
5776 /*Inline*/false, SourceLocation(),
5777 SourceLocation(), &Context->Idents.get("std"),
5780 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5781 Context->getTranslationUnitDecl(),
5782 SourceLocation(), SourceLocation(),
5783 &Context->Idents.get("__va_list"));
5784 VaListTagDecl->setDeclContext(NS);
5787 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5788 Context->getTranslationUnitDecl(),
5789 &Context->Idents.get("__va_list"));
5792 VaListTagDecl->startDefinition();
5794 const size_t NumFields = 5;
5795 QualType FieldTypes[NumFields];
5796 const char *FieldNames[NumFields];
5799 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[0] = "__stack";
5803 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[1] = "__gr_top";
5807 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5808 FieldNames[2] = "__vr_top";
5811 FieldTypes[3] = Context->IntTy;
5812 FieldNames[3] = "__gr_offs";
5815 FieldTypes[4] = Context->IntTy;
5816 FieldNames[4] = "__vr_offs";
5819 for (unsigned i = 0; i < NumFields; ++i) {
5820 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5824 &Context->Idents.get(FieldNames[i]),
5825 FieldTypes[i], /*TInfo=*/0,
5829 Field->setAccess(AS_public);
5830 VaListTagDecl->addDecl(Field);
5832 VaListTagDecl->completeDefinition();
5833 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5834 Context->VaListTagTy = VaListTagType;
5836 // } __builtin_va_list;
5837 TypedefDecl *VaListTypedefDecl
5838 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5839 Context->getTranslationUnitDecl(),
5840 SourceLocation(), SourceLocation(),
5841 &Context->Idents.get("__builtin_va_list"),
5842 Context->getTrivialTypeSourceInfo(VaListTagType));
5844 return VaListTypedefDecl;
5847 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5848 // typedef struct __va_list_tag {
5849 RecordDecl *VaListTagDecl;
5851 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5852 Context->getTranslationUnitDecl(),
5853 &Context->Idents.get("__va_list_tag"));
5854 VaListTagDecl->startDefinition();
5856 const size_t NumFields = 5;
5857 QualType FieldTypes[NumFields];
5858 const char *FieldNames[NumFields];
5860 // unsigned char gpr;
5861 FieldTypes[0] = Context->UnsignedCharTy;
5862 FieldNames[0] = "gpr";
5864 // unsigned char fpr;
5865 FieldTypes[1] = Context->UnsignedCharTy;
5866 FieldNames[1] = "fpr";
5868 // unsigned short reserved;
5869 FieldTypes[2] = Context->UnsignedShortTy;
5870 FieldNames[2] = "reserved";
5872 // void* overflow_arg_area;
5873 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5874 FieldNames[3] = "overflow_arg_area";
5876 // void* reg_save_area;
5877 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5878 FieldNames[4] = "reg_save_area";
5881 for (unsigned i = 0; i < NumFields; ++i) {
5882 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5885 &Context->Idents.get(FieldNames[i]),
5886 FieldTypes[i], /*TInfo=*/0,
5890 Field->setAccess(AS_public);
5891 VaListTagDecl->addDecl(Field);
5893 VaListTagDecl->completeDefinition();
5894 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5895 Context->VaListTagTy = VaListTagType;
5898 TypedefDecl *VaListTagTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__va_list_tag"),
5903 Context->getTrivialTypeSourceInfo(VaListTagType));
5904 QualType VaListTagTypedefType =
5905 Context->getTypedefType(VaListTagTypedefDecl);
5907 // typedef __va_list_tag __builtin_va_list[1];
5908 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5909 QualType VaListTagArrayType
5910 = Context->getConstantArrayType(VaListTagTypedefType,
5911 Size, ArrayType::Normal, 0);
5912 TypeSourceInfo *TInfo
5913 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5914 TypedefDecl *VaListTypedefDecl
5915 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 SourceLocation(), SourceLocation(),
5918 &Context->Idents.get("__builtin_va_list"),
5921 return VaListTypedefDecl;
5924 static TypedefDecl *
5925 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5926 // typedef struct __va_list_tag {
5927 RecordDecl *VaListTagDecl;
5928 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5929 Context->getTranslationUnitDecl(),
5930 &Context->Idents.get("__va_list_tag"));
5931 VaListTagDecl->startDefinition();
5933 const size_t NumFields = 4;
5934 QualType FieldTypes[NumFields];
5935 const char *FieldNames[NumFields];
5937 // unsigned gp_offset;
5938 FieldTypes[0] = Context->UnsignedIntTy;
5939 FieldNames[0] = "gp_offset";
5941 // unsigned fp_offset;
5942 FieldTypes[1] = Context->UnsignedIntTy;
5943 FieldNames[1] = "fp_offset";
5945 // void* overflow_arg_area;
5946 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5947 FieldNames[2] = "overflow_arg_area";
5949 // void* reg_save_area;
5950 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5951 FieldNames[3] = "reg_save_area";
5954 for (unsigned i = 0; i < NumFields; ++i) {
5955 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5959 &Context->Idents.get(FieldNames[i]),
5960 FieldTypes[i], /*TInfo=*/0,
5964 Field->setAccess(AS_public);
5965 VaListTagDecl->addDecl(Field);
5967 VaListTagDecl->completeDefinition();
5968 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5969 Context->VaListTagTy = VaListTagType;
5972 TypedefDecl *VaListTagTypedefDecl
5973 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5974 Context->getTranslationUnitDecl(),
5975 SourceLocation(), SourceLocation(),
5976 &Context->Idents.get("__va_list_tag"),
5977 Context->getTrivialTypeSourceInfo(VaListTagType));
5978 QualType VaListTagTypedefType =
5979 Context->getTypedefType(VaListTagTypedefDecl);
5981 // typedef __va_list_tag __builtin_va_list[1];
5982 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5983 QualType VaListTagArrayType
5984 = Context->getConstantArrayType(VaListTagTypedefType,
5985 Size, ArrayType::Normal,0);
5986 TypeSourceInfo *TInfo
5987 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5988 TypedefDecl *VaListTypedefDecl
5989 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5990 Context->getTranslationUnitDecl(),
5991 SourceLocation(), SourceLocation(),
5992 &Context->Idents.get("__builtin_va_list"),
5995 return VaListTypedefDecl;
5998 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5999 // typedef int __builtin_va_list[4];
6000 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6001 QualType IntArrayType
6002 = Context->getConstantArrayType(Context->IntTy,
6003 Size, ArrayType::Normal, 0);
6004 TypedefDecl *VaListTypedefDecl
6005 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6006 Context->getTranslationUnitDecl(),
6007 SourceLocation(), SourceLocation(),
6008 &Context->Idents.get("__builtin_va_list"),
6009 Context->getTrivialTypeSourceInfo(IntArrayType));
6011 return VaListTypedefDecl;
6014 static TypedefDecl *
6015 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6016 RecordDecl *VaListDecl;
6017 if (Context->getLangOpts().CPlusPlus) {
6018 // namespace std { struct __va_list {
6020 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6021 Context->getTranslationUnitDecl(),
6022 /*Inline*/false, SourceLocation(),
6023 SourceLocation(), &Context->Idents.get("std"),
6026 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6027 Context->getTranslationUnitDecl(),
6028 SourceLocation(), SourceLocation(),
6029 &Context->Idents.get("__va_list"));
6031 VaListDecl->setDeclContext(NS);
6034 // struct __va_list {
6035 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6036 Context->getTranslationUnitDecl(),
6037 &Context->Idents.get("__va_list"));
6040 VaListDecl->startDefinition();
6043 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6047 &Context->Idents.get("__ap"),
6048 Context->getPointerType(Context->VoidTy),
6053 Field->setAccess(AS_public);
6054 VaListDecl->addDecl(Field);
6057 VaListDecl->completeDefinition();
6059 // typedef struct __va_list __builtin_va_list;
6060 TypeSourceInfo *TInfo
6061 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6063 TypedefDecl *VaListTypeDecl
6064 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6065 Context->getTranslationUnitDecl(),
6066 SourceLocation(), SourceLocation(),
6067 &Context->Idents.get("__builtin_va_list"),
6070 return VaListTypeDecl;
6073 static TypedefDecl *
6074 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6075 // typedef struct __va_list_tag {
6076 RecordDecl *VaListTagDecl;
6077 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6078 Context->getTranslationUnitDecl(),
6079 &Context->Idents.get("__va_list_tag"));
6080 VaListTagDecl->startDefinition();
6082 const size_t NumFields = 4;
6083 QualType FieldTypes[NumFields];
6084 const char *FieldNames[NumFields];
6087 FieldTypes[0] = Context->LongTy;
6088 FieldNames[0] = "__gpr";
6091 FieldTypes[1] = Context->LongTy;
6092 FieldNames[1] = "__fpr";
6094 // void *__overflow_arg_area;
6095 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6096 FieldNames[2] = "__overflow_arg_area";
6098 // void *__reg_save_area;
6099 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6100 FieldNames[3] = "__reg_save_area";
6103 for (unsigned i = 0; i < NumFields; ++i) {
6104 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6108 &Context->Idents.get(FieldNames[i]),
6109 FieldTypes[i], /*TInfo=*/0,
6113 Field->setAccess(AS_public);
6114 VaListTagDecl->addDecl(Field);
6116 VaListTagDecl->completeDefinition();
6117 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6118 Context->VaListTagTy = VaListTagType;
6121 TypedefDecl *VaListTagTypedefDecl
6122 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6123 Context->getTranslationUnitDecl(),
6124 SourceLocation(), SourceLocation(),
6125 &Context->Idents.get("__va_list_tag"),
6126 Context->getTrivialTypeSourceInfo(VaListTagType));
6127 QualType VaListTagTypedefType =
6128 Context->getTypedefType(VaListTagTypedefDecl);
6130 // typedef __va_list_tag __builtin_va_list[1];
6131 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6132 QualType VaListTagArrayType
6133 = Context->getConstantArrayType(VaListTagTypedefType,
6134 Size, ArrayType::Normal,0);
6135 TypeSourceInfo *TInfo
6136 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6137 TypedefDecl *VaListTypedefDecl
6138 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6139 Context->getTranslationUnitDecl(),
6140 SourceLocation(), SourceLocation(),
6141 &Context->Idents.get("__builtin_va_list"),
6144 return VaListTypedefDecl;
6147 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6148 TargetInfo::BuiltinVaListKind Kind) {
6150 case TargetInfo::CharPtrBuiltinVaList:
6151 return CreateCharPtrBuiltinVaListDecl(Context);
6152 case TargetInfo::VoidPtrBuiltinVaList:
6153 return CreateVoidPtrBuiltinVaListDecl(Context);
6154 case TargetInfo::AArch64ABIBuiltinVaList:
6155 return CreateAArch64ABIBuiltinVaListDecl(Context);
6156 case TargetInfo::PowerABIBuiltinVaList:
6157 return CreatePowerABIBuiltinVaListDecl(Context);
6158 case TargetInfo::X86_64ABIBuiltinVaList:
6159 return CreateX86_64ABIBuiltinVaListDecl(Context);
6160 case TargetInfo::PNaClABIBuiltinVaList:
6161 return CreatePNaClABIBuiltinVaListDecl(Context);
6162 case TargetInfo::AAPCSABIBuiltinVaList:
6163 return CreateAAPCSABIBuiltinVaListDecl(Context);
6164 case TargetInfo::SystemZBuiltinVaList:
6165 return CreateSystemZBuiltinVaListDecl(Context);
6168 llvm_unreachable("Unhandled __builtin_va_list type kind");
6171 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6172 if (!BuiltinVaListDecl)
6173 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6175 return BuiltinVaListDecl;
6178 QualType ASTContext::getVaListTagType() const {
6179 // Force the creation of VaListTagTy by building the __builtin_va_list
6181 if (VaListTagTy.isNull())
6182 (void) getBuiltinVaListDecl();
6187 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6188 assert(ObjCConstantStringType.isNull() &&
6189 "'NSConstantString' type already set!");
6191 ObjCConstantStringType = getObjCInterfaceType(Decl);
6194 /// \brief Retrieve the template name that corresponds to a non-empty
6197 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6198 UnresolvedSetIterator End) const {
6199 unsigned size = End - Begin;
6200 assert(size > 1 && "set is not overloaded!");
6202 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6203 size * sizeof(FunctionTemplateDecl*));
6204 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6206 NamedDecl **Storage = OT->getStorage();
6207 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6209 assert(isa<FunctionTemplateDecl>(D) ||
6210 (isa<UsingShadowDecl>(D) &&
6211 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6215 return TemplateName(OT);
6218 /// \brief Retrieve the template name that represents a qualified
6219 /// template name such as \c std::vector.
6221 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6222 bool TemplateKeyword,
6223 TemplateDecl *Template) const {
6224 assert(NNS && "Missing nested-name-specifier in qualified template name");
6226 // FIXME: Canonicalization?
6227 llvm::FoldingSetNodeID ID;
6228 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6230 void *InsertPos = 0;
6231 QualifiedTemplateName *QTN =
6232 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6234 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6235 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6236 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6239 return TemplateName(QTN);
6242 /// \brief Retrieve the template name that represents a dependent
6243 /// template name such as \c MetaFun::template apply.
6245 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6246 const IdentifierInfo *Name) const {
6247 assert((!NNS || NNS->isDependent()) &&
6248 "Nested name specifier must be dependent");
6250 llvm::FoldingSetNodeID ID;
6251 DependentTemplateName::Profile(ID, NNS, Name);
6253 void *InsertPos = 0;
6254 DependentTemplateName *QTN =
6255 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6258 return TemplateName(QTN);
6260 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6261 if (CanonNNS == NNS) {
6262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Name);
6265 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6266 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6267 DependentTemplateName(NNS, Name, Canon);
6268 DependentTemplateName *CheckQTN =
6269 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6270 assert(!CheckQTN && "Dependent type name canonicalization broken");
6274 DependentTemplateNames.InsertNode(QTN, InsertPos);
6275 return TemplateName(QTN);
6278 /// \brief Retrieve the template name that represents a dependent
6279 /// template name such as \c MetaFun::template operator+.
6281 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6282 OverloadedOperatorKind Operator) const {
6283 assert((!NNS || NNS->isDependent()) &&
6284 "Nested name specifier must be dependent");
6286 llvm::FoldingSetNodeID ID;
6287 DependentTemplateName::Profile(ID, NNS, Operator);
6289 void *InsertPos = 0;
6290 DependentTemplateName *QTN
6291 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6294 return TemplateName(QTN);
6296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6297 if (CanonNNS == NNS) {
6298 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6299 DependentTemplateName(NNS, Operator);
6301 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6302 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6303 DependentTemplateName(NNS, Operator, Canon);
6305 DependentTemplateName *CheckQTN
6306 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6307 assert(!CheckQTN && "Dependent template name canonicalization broken");
6311 DependentTemplateNames.InsertNode(QTN, InsertPos);
6312 return TemplateName(QTN);
6316 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6317 TemplateName replacement) const {
6318 llvm::FoldingSetNodeID ID;
6319 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6321 void *insertPos = 0;
6322 SubstTemplateTemplateParmStorage *subst
6323 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6326 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6327 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6330 return TemplateName(subst);
6334 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6335 const TemplateArgument &ArgPack) const {
6336 ASTContext &Self = const_cast<ASTContext &>(*this);
6337 llvm::FoldingSetNodeID ID;
6338 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6340 void *InsertPos = 0;
6341 SubstTemplateTemplateParmPackStorage *Subst
6342 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6345 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6346 ArgPack.pack_size(),
6347 ArgPack.pack_begin());
6348 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6351 return TemplateName(Subst);
6354 /// getFromTargetType - Given one of the integer types provided by
6355 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6356 /// is actually a value of type @c TargetInfo::IntType.
6357 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6359 case TargetInfo::NoInt: return CanQualType();
6360 case TargetInfo::SignedChar: return SignedCharTy;
6361 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6362 case TargetInfo::SignedShort: return ShortTy;
6363 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6364 case TargetInfo::SignedInt: return IntTy;
6365 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6366 case TargetInfo::SignedLong: return LongTy;
6367 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6368 case TargetInfo::SignedLongLong: return LongLongTy;
6369 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6372 llvm_unreachable("Unhandled TargetInfo::IntType value");
6375 //===----------------------------------------------------------------------===//
6377 //===----------------------------------------------------------------------===//
6379 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6380 /// garbage collection attribute.
6382 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6383 if (getLangOpts().getGC() == LangOptions::NonGC)
6384 return Qualifiers::GCNone;
6386 assert(getLangOpts().ObjC1);
6387 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6389 // Default behaviour under objective-C's gc is for ObjC pointers
6390 // (or pointers to them) be treated as though they were declared
6392 if (GCAttrs == Qualifiers::GCNone) {
6393 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6394 return Qualifiers::Strong;
6395 else if (Ty->isPointerType())
6396 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6398 // It's not valid to set GC attributes on anything that isn't a
6401 QualType CT = Ty->getCanonicalTypeInternal();
6402 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6403 CT = AT->getElementType();
6404 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6410 //===----------------------------------------------------------------------===//
6411 // Type Compatibility Testing
6412 //===----------------------------------------------------------------------===//
6414 /// areCompatVectorTypes - Return true if the two specified vector types are
6416 static bool areCompatVectorTypes(const VectorType *LHS,
6417 const VectorType *RHS) {
6418 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6419 return LHS->getElementType() == RHS->getElementType() &&
6420 LHS->getNumElements() == RHS->getNumElements();
6423 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6424 QualType SecondVec) {
6425 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6426 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6428 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6431 // Treat Neon vector types and most AltiVec vector types as if they are the
6432 // equivalent GCC vector types.
6433 const VectorType *First = FirstVec->getAs<VectorType>();
6434 const VectorType *Second = SecondVec->getAs<VectorType>();
6435 if (First->getNumElements() == Second->getNumElements() &&
6436 hasSameType(First->getElementType(), Second->getElementType()) &&
6437 First->getVectorKind() != VectorType::AltiVecPixel &&
6438 First->getVectorKind() != VectorType::AltiVecBool &&
6439 Second->getVectorKind() != VectorType::AltiVecPixel &&
6440 Second->getVectorKind() != VectorType::AltiVecBool)
6446 //===----------------------------------------------------------------------===//
6447 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6448 //===----------------------------------------------------------------------===//
6450 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6451 /// inheritance hierarchy of 'rProto'.
6453 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6454 ObjCProtocolDecl *rProto) const {
6455 if (declaresSameEntity(lProto, rProto))
6457 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6458 E = rProto->protocol_end(); PI != E; ++PI)
6459 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6464 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6465 /// Class<pr1, ...>.
6466 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6468 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6469 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6470 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6472 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6473 E = lhsQID->qual_end(); I != E; ++I) {
6475 ObjCProtocolDecl *lhsProto = *I;
6476 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6477 E = rhsOPT->qual_end(); J != E; ++J) {
6478 ObjCProtocolDecl *rhsProto = *J;
6479 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6490 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6491 /// ObjCQualifiedIDType.
6492 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6494 // Allow id<P..> and an 'id' or void* type in all cases.
6495 if (lhs->isVoidPointerType() ||
6496 lhs->isObjCIdType() || lhs->isObjCClassType())
6498 else if (rhs->isVoidPointerType() ||
6499 rhs->isObjCIdType() || rhs->isObjCClassType())
6502 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6503 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6505 if (!rhsOPT) return false;
6507 if (rhsOPT->qual_empty()) {
6508 // If the RHS is a unqualified interface pointer "NSString*",
6509 // make sure we check the class hierarchy.
6510 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6511 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6512 E = lhsQID->qual_end(); I != E; ++I) {
6513 // when comparing an id<P> on lhs with a static type on rhs,
6514 // see if static class implements all of id's protocols, directly or
6515 // through its super class and categories.
6516 if (!rhsID->ClassImplementsProtocol(*I, true))
6520 // If there are no qualifiers and no interface, we have an 'id'.
6523 // Both the right and left sides have qualifiers.
6524 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6525 E = lhsQID->qual_end(); I != E; ++I) {
6526 ObjCProtocolDecl *lhsProto = *I;
6529 // when comparing an id<P> on lhs with a static type on rhs,
6530 // see if static class implements all of id's protocols, directly or
6531 // through its super class and categories.
6532 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6533 E = rhsOPT->qual_end(); J != E; ++J) {
6534 ObjCProtocolDecl *rhsProto = *J;
6535 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6536 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6541 // If the RHS is a qualified interface pointer "NSString<P>*",
6542 // make sure we check the class hierarchy.
6543 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6544 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6545 E = lhsQID->qual_end(); I != E; ++I) {
6546 // when comparing an id<P> on lhs with a static type on rhs,
6547 // see if static class implements all of id's protocols, directly or
6548 // through its super class and categories.
6549 if (rhsID->ClassImplementsProtocol(*I, true)) {
6562 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6563 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6565 if (const ObjCObjectPointerType *lhsOPT =
6566 lhs->getAsObjCInterfacePointerType()) {
6567 // If both the right and left sides have qualifiers.
6568 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6569 E = lhsOPT->qual_end(); I != E; ++I) {
6570 ObjCProtocolDecl *lhsProto = *I;
6573 // when comparing an id<P> on rhs with a static type on lhs,
6574 // see if static class implements all of id's protocols, directly or
6575 // through its super class and categories.
6576 // First, lhs protocols in the qualifier list must be found, direct
6577 // or indirect in rhs's qualifier list or it is a mismatch.
6578 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6579 E = rhsQID->qual_end(); J != E; ++J) {
6580 ObjCProtocolDecl *rhsProto = *J;
6581 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6582 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6591 // Static class's protocols, or its super class or category protocols
6592 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6593 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6594 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6595 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6596 // This is rather dubious but matches gcc's behavior. If lhs has
6597 // no type qualifier and its class has no static protocol(s)
6598 // assume that it is mismatch.
6599 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6601 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6602 LHSInheritedProtocols.begin(),
6603 E = LHSInheritedProtocols.end(); I != E; ++I) {
6605 ObjCProtocolDecl *lhsProto = (*I);
6606 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6607 E = rhsQID->qual_end(); J != E; ++J) {
6608 ObjCProtocolDecl *rhsProto = *J;
6609 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6610 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6624 /// canAssignObjCInterfaces - Return true if the two interface types are
6625 /// compatible for assignment from RHS to LHS. This handles validation of any
6626 /// protocol qualifiers on the LHS or RHS.
6628 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6629 const ObjCObjectPointerType *RHSOPT) {
6630 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6631 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6633 // If either type represents the built-in 'id' or 'Class' types, return true.
6634 if (LHS->isObjCUnqualifiedIdOrClass() ||
6635 RHS->isObjCUnqualifiedIdOrClass())
6638 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6639 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6643 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6644 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6645 QualType(RHSOPT,0));
6647 // If we have 2 user-defined types, fall into that path.
6648 if (LHS->getInterface() && RHS->getInterface())
6649 return canAssignObjCInterfaces(LHS, RHS);
6654 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6655 /// for providing type-safety for objective-c pointers used to pass/return
6656 /// arguments in block literals. When passed as arguments, passing 'A*' where
6657 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6658 /// not OK. For the return type, the opposite is not OK.
6659 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6660 const ObjCObjectPointerType *LHSOPT,
6661 const ObjCObjectPointerType *RHSOPT,
6662 bool BlockReturnType) {
6663 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6666 if (LHSOPT->isObjCBuiltinType()) {
6667 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6670 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6671 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6675 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6676 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6677 if (LHS && RHS) { // We have 2 user-defined types.
6679 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6680 return BlockReturnType;
6681 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6682 return !BlockReturnType;
6690 /// getIntersectionOfProtocols - This routine finds the intersection of set
6691 /// of protocols inherited from two distinct objective-c pointer objects.
6692 /// It is used to build composite qualifier list of the composite type of
6693 /// the conditional expression involving two objective-c pointer objects.
6695 void getIntersectionOfProtocols(ASTContext &Context,
6696 const ObjCObjectPointerType *LHSOPT,
6697 const ObjCObjectPointerType *RHSOPT,
6698 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6700 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6701 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6702 assert(LHS->getInterface() && "LHS must have an interface base");
6703 assert(RHS->getInterface() && "RHS must have an interface base");
6705 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6706 unsigned LHSNumProtocols = LHS->getNumProtocols();
6707 if (LHSNumProtocols > 0)
6708 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6710 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6711 Context.CollectInheritedProtocols(LHS->getInterface(),
6712 LHSInheritedProtocols);
6713 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6714 LHSInheritedProtocols.end());
6717 unsigned RHSNumProtocols = RHS->getNumProtocols();
6718 if (RHSNumProtocols > 0) {
6719 ObjCProtocolDecl **RHSProtocols =
6720 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6721 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6722 if (InheritedProtocolSet.count(RHSProtocols[i]))
6723 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6725 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6726 Context.CollectInheritedProtocols(RHS->getInterface(),
6727 RHSInheritedProtocols);
6728 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6729 RHSInheritedProtocols.begin(),
6730 E = RHSInheritedProtocols.end(); I != E; ++I)
6731 if (InheritedProtocolSet.count((*I)))
6732 IntersectionOfProtocols.push_back((*I));
6736 /// areCommonBaseCompatible - Returns common base class of the two classes if
6737 /// one found. Note that this is O'2 algorithm. But it will be called as the
6738 /// last type comparison in a ?-exp of ObjC pointer types before a
6739 /// warning is issued. So, its invokation is extremely rare.
6740 QualType ASTContext::areCommonBaseCompatible(
6741 const ObjCObjectPointerType *Lptr,
6742 const ObjCObjectPointerType *Rptr) {
6743 const ObjCObjectType *LHS = Lptr->getObjectType();
6744 const ObjCObjectType *RHS = Rptr->getObjectType();
6745 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6746 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6747 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6751 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6752 if (canAssignObjCInterfaces(LHS, RHS)) {
6753 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6754 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6756 QualType Result = QualType(LHS, 0);
6757 if (!Protocols.empty())
6758 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6759 Result = getObjCObjectPointerType(Result);
6762 } while ((LDecl = LDecl->getSuperClass()));
6767 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6768 const ObjCObjectType *RHS) {
6769 assert(LHS->getInterface() && "LHS is not an interface type");
6770 assert(RHS->getInterface() && "RHS is not an interface type");
6772 // Verify that the base decls are compatible: the RHS must be a subclass of
6774 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6777 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6778 // protocol qualified at all, then we are good.
6779 if (LHS->getNumProtocols() == 0)
6782 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6783 // more detailed analysis is required.
6784 if (RHS->getNumProtocols() == 0) {
6785 // OK, if LHS is a superclass of RHS *and*
6786 // this superclass is assignment compatible with LHS.
6789 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6791 // OK if conversion of LHS to SuperClass results in narrowing of types
6792 // ; i.e., SuperClass may implement at least one of the protocols
6793 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6794 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6795 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6796 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6797 // If super class has no protocols, it is not a match.
6798 if (SuperClassInheritedProtocols.empty())
6801 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6802 LHSPE = LHS->qual_end();
6803 LHSPI != LHSPE; LHSPI++) {
6804 bool SuperImplementsProtocol = false;
6805 ObjCProtocolDecl *LHSProto = (*LHSPI);
6807 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6808 SuperClassInheritedProtocols.begin(),
6809 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6810 ObjCProtocolDecl *SuperClassProto = (*I);
6811 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6812 SuperImplementsProtocol = true;
6816 if (!SuperImplementsProtocol)
6824 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6825 LHSPE = LHS->qual_end();
6826 LHSPI != LHSPE; LHSPI++) {
6827 bool RHSImplementsProtocol = false;
6829 // If the RHS doesn't implement the protocol on the left, the types
6830 // are incompatible.
6831 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6832 RHSPE = RHS->qual_end();
6833 RHSPI != RHSPE; RHSPI++) {
6834 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
6835 RHSImplementsProtocol = true;
6839 // FIXME: For better diagnostics, consider passing back the protocol name.
6840 if (!RHSImplementsProtocol)
6843 // The RHS implements all protocols listed on the LHS.
6847 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6848 // get the "pointed to" types
6849 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6850 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6852 if (!LHSOPT || !RHSOPT)
6855 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6856 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6859 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6860 return canAssignObjCInterfaces(
6861 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6862 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6865 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6866 /// both shall have the identically qualified version of a compatible type.
6867 /// C99 6.2.7p1: Two types have compatible types if their types are the
6868 /// same. See 6.7.[2,3,5] for additional rules.
6869 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6870 bool CompareUnqualified) {
6871 if (getLangOpts().CPlusPlus)
6872 return hasSameType(LHS, RHS);
6874 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6877 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6878 return typesAreCompatible(LHS, RHS);
6881 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6882 return !mergeTypes(LHS, RHS, true).isNull();
6885 /// mergeTransparentUnionType - if T is a transparent union type and a member
6886 /// of T is compatible with SubType, return the merged type, else return
6888 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6889 bool OfBlockPointer,
6891 if (const RecordType *UT = T->getAsUnionType()) {
6892 RecordDecl *UD = UT->getDecl();
6893 if (UD->hasAttr<TransparentUnionAttr>()) {
6894 for (RecordDecl::field_iterator it = UD->field_begin(),
6895 itend = UD->field_end(); it != itend; ++it) {
6896 QualType ET = it->getType().getUnqualifiedType();
6897 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6907 /// mergeFunctionArgumentTypes - merge two types which appear as function
6909 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6910 bool OfBlockPointer,
6912 // GNU extension: two types are compatible if they appear as a function
6913 // argument, one of the types is a transparent union type and the other
6914 // type is compatible with a union member
6915 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6917 if (!lmerge.isNull())
6920 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6922 if (!rmerge.isNull())
6925 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6928 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6929 bool OfBlockPointer,
6931 const FunctionType *lbase = lhs->getAs<FunctionType>();
6932 const FunctionType *rbase = rhs->getAs<FunctionType>();
6933 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6934 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6935 bool allLTypes = true;
6936 bool allRTypes = true;
6938 // Check return type
6940 if (OfBlockPointer) {
6941 QualType RHS = rbase->getResultType();
6942 QualType LHS = lbase->getResultType();
6943 bool UnqualifiedResult = Unqualified;
6944 if (!UnqualifiedResult)
6945 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6946 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6949 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6951 if (retType.isNull()) return QualType();
6954 retType = retType.getUnqualifiedType();
6956 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6957 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6959 LRetType = LRetType.getUnqualifiedType();
6960 RRetType = RRetType.getUnqualifiedType();
6963 if (getCanonicalType(retType) != LRetType)
6965 if (getCanonicalType(retType) != RRetType)
6968 // FIXME: double check this
6969 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6970 // rbase->getRegParmAttr() != 0 &&
6971 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6972 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6973 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6975 // Compatible functions must have compatible calling conventions
6976 if (lbaseInfo.getCC() != rbaseInfo.getCC())
6979 // Regparm is part of the calling convention.
6980 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6982 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6985 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6988 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6989 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6991 if (lbaseInfo.getNoReturn() != NoReturn)
6993 if (rbaseInfo.getNoReturn() != NoReturn)
6996 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6998 if (lproto && rproto) { // two C99 style function prototypes
6999 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7000 "C++ shouldn't be here");
7001 unsigned lproto_nargs = lproto->getNumArgs();
7002 unsigned rproto_nargs = rproto->getNumArgs();
7004 // Compatible functions must have the same number of arguments
7005 if (lproto_nargs != rproto_nargs)
7008 // Variadic and non-variadic functions aren't compatible
7009 if (lproto->isVariadic() != rproto->isVariadic())
7012 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7015 if (LangOpts.ObjCAutoRefCount &&
7016 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7019 // Check argument compatibility
7020 SmallVector<QualType, 10> types;
7021 for (unsigned i = 0; i < lproto_nargs; i++) {
7022 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7023 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
7024 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7027 if (argtype.isNull()) return QualType();
7030 argtype = argtype.getUnqualifiedType();
7032 types.push_back(argtype);
7034 largtype = largtype.getUnqualifiedType();
7035 rargtype = rargtype.getUnqualifiedType();
7038 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7040 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7044 if (allLTypes) return lhs;
7045 if (allRTypes) return rhs;
7047 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7048 EPI.ExtInfo = einfo;
7049 return getFunctionType(retType, types, EPI);
7052 if (lproto) allRTypes = false;
7053 if (rproto) allLTypes = false;
7055 const FunctionProtoType *proto = lproto ? lproto : rproto;
7057 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7058 if (proto->isVariadic()) return QualType();
7059 // Check that the types are compatible with the types that
7060 // would result from default argument promotions (C99 6.7.5.3p15).
7061 // The only types actually affected are promotable integer
7062 // types and floats, which would be passed as a different
7063 // type depending on whether the prototype is visible.
7064 unsigned proto_nargs = proto->getNumArgs();
7065 for (unsigned i = 0; i < proto_nargs; ++i) {
7066 QualType argTy = proto->getArgType(i);
7068 // Look at the converted type of enum types, since that is the type used
7069 // to pass enum values.
7070 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7071 argTy = Enum->getDecl()->getIntegerType();
7076 if (argTy->isPromotableIntegerType() ||
7077 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7081 if (allLTypes) return lhs;
7082 if (allRTypes) return rhs;
7084 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7085 EPI.ExtInfo = einfo;
7086 return getFunctionType(retType, proto->getArgTypes(), EPI);
7089 if (allLTypes) return lhs;
7090 if (allRTypes) return rhs;
7091 return getFunctionNoProtoType(retType, einfo);
7094 /// Given that we have an enum type and a non-enum type, try to merge them.
7095 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7096 QualType other, bool isBlockReturnType) {
7097 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7098 // a signed integer type, or an unsigned integer type.
7099 // Compatibility is based on the underlying type, not the promotion
7101 QualType underlyingType = ET->getDecl()->getIntegerType();
7102 if (underlyingType.isNull()) return QualType();
7103 if (Context.hasSameType(underlyingType, other))
7106 // In block return types, we're more permissive and accept any
7107 // integral type of the same size.
7108 if (isBlockReturnType && other->isIntegerType() &&
7109 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7115 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7116 bool OfBlockPointer,
7117 bool Unqualified, bool BlockReturnType) {
7118 // C++ [expr]: If an expression initially has the type "reference to T", the
7119 // type is adjusted to "T" prior to any further analysis, the expression
7120 // designates the object or function denoted by the reference, and the
7121 // expression is an lvalue unless the reference is an rvalue reference and
7122 // the expression is a function call (possibly inside parentheses).
7123 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7124 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7127 LHS = LHS.getUnqualifiedType();
7128 RHS = RHS.getUnqualifiedType();
7131 QualType LHSCan = getCanonicalType(LHS),
7132 RHSCan = getCanonicalType(RHS);
7134 // If two types are identical, they are compatible.
7135 if (LHSCan == RHSCan)
7138 // If the qualifiers are different, the types aren't compatible... mostly.
7139 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7140 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7141 if (LQuals != RQuals) {
7142 // If any of these qualifiers are different, we have a type
7144 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7145 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7146 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7149 // Exactly one GC qualifier difference is allowed: __strong is
7150 // okay if the other type has no GC qualifier but is an Objective
7151 // C object pointer (i.e. implicitly strong by default). We fix
7152 // this by pretending that the unqualified type was actually
7153 // qualified __strong.
7154 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7155 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7156 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7158 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7161 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7162 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7164 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7165 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7170 // Okay, qualifiers are equal.
7172 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7173 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7175 // We want to consider the two function types to be the same for these
7176 // comparisons, just force one to the other.
7177 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7178 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7180 // Same as above for arrays
7181 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7182 LHSClass = Type::ConstantArray;
7183 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7184 RHSClass = Type::ConstantArray;
7186 // ObjCInterfaces are just specialized ObjCObjects.
7187 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7188 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7190 // Canonicalize ExtVector -> Vector.
7191 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7192 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7194 // If the canonical type classes don't match.
7195 if (LHSClass != RHSClass) {
7196 // Note that we only have special rules for turning block enum
7197 // returns into block int returns, not vice-versa.
7198 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7199 return mergeEnumWithInteger(*this, ETy, RHS, false);
7201 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7202 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7204 // allow block pointer type to match an 'id' type.
7205 if (OfBlockPointer && !BlockReturnType) {
7206 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7208 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7215 // The canonical type classes match.
7217 #define TYPE(Class, Base)
7218 #define ABSTRACT_TYPE(Class, Base)
7219 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7220 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7221 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7222 #include "clang/AST/TypeNodes.def"
7223 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7226 case Type::LValueReference:
7227 case Type::RValueReference:
7228 case Type::MemberPointer:
7229 llvm_unreachable("C++ should never be in mergeTypes");
7231 case Type::ObjCInterface:
7232 case Type::IncompleteArray:
7233 case Type::VariableArray:
7234 case Type::FunctionProto:
7235 case Type::ExtVector:
7236 llvm_unreachable("Types are eliminated above");
7240 // Merge two pointer types, while trying to preserve typedef info
7241 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7242 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7244 LHSPointee = LHSPointee.getUnqualifiedType();
7245 RHSPointee = RHSPointee.getUnqualifiedType();
7247 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7249 if (ResultType.isNull()) return QualType();
7250 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7252 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7254 return getPointerType(ResultType);
7256 case Type::BlockPointer:
7258 // Merge two block pointer types, while trying to preserve typedef info
7259 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7260 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7262 LHSPointee = LHSPointee.getUnqualifiedType();
7263 RHSPointee = RHSPointee.getUnqualifiedType();
7265 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7267 if (ResultType.isNull()) return QualType();
7268 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7270 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7272 return getBlockPointerType(ResultType);
7276 // Merge two pointer types, while trying to preserve typedef info
7277 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7278 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7280 LHSValue = LHSValue.getUnqualifiedType();
7281 RHSValue = RHSValue.getUnqualifiedType();
7283 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7285 if (ResultType.isNull()) return QualType();
7286 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7288 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7290 return getAtomicType(ResultType);
7292 case Type::ConstantArray:
7294 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7295 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7296 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7299 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7300 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7302 LHSElem = LHSElem.getUnqualifiedType();
7303 RHSElem = RHSElem.getUnqualifiedType();
7306 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7307 if (ResultType.isNull()) return QualType();
7308 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7310 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7312 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7313 ArrayType::ArraySizeModifier(), 0);
7314 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7315 ArrayType::ArraySizeModifier(), 0);
7316 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7317 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7318 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7320 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7323 // FIXME: This isn't correct! But tricky to implement because
7324 // the array's size has to be the size of LHS, but the type
7325 // has to be different.
7329 // FIXME: This isn't correct! But tricky to implement because
7330 // the array's size has to be the size of RHS, but the type
7331 // has to be different.
7334 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7335 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7336 return getIncompleteArrayType(ResultType,
7337 ArrayType::ArraySizeModifier(), 0);
7339 case Type::FunctionNoProto:
7340 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7345 // Only exactly equal builtin types are compatible, which is tested above.
7348 // Distinct complex types are incompatible.
7351 // FIXME: The merged type should be an ExtVector!
7352 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7353 RHSCan->getAs<VectorType>()))
7356 case Type::ObjCObject: {
7357 // Check if the types are assignment compatible.
7358 // FIXME: This should be type compatibility, e.g. whether
7359 // "LHS x; RHS x;" at global scope is legal.
7360 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7361 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7362 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7367 case Type::ObjCObjectPointer: {
7368 if (OfBlockPointer) {
7369 if (canAssignObjCInterfacesInBlockPointer(
7370 LHS->getAs<ObjCObjectPointerType>(),
7371 RHS->getAs<ObjCObjectPointerType>(),
7376 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7377 RHS->getAs<ObjCObjectPointerType>()))
7384 llvm_unreachable("Invalid Type::Class!");
7387 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7388 const FunctionProtoType *FromFunctionType,
7389 const FunctionProtoType *ToFunctionType) {
7390 if (FromFunctionType->hasAnyConsumedArgs() !=
7391 ToFunctionType->hasAnyConsumedArgs())
7393 FunctionProtoType::ExtProtoInfo FromEPI =
7394 FromFunctionType->getExtProtoInfo();
7395 FunctionProtoType::ExtProtoInfo ToEPI =
7396 ToFunctionType->getExtProtoInfo();
7397 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7398 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7399 ArgIdx != NumArgs; ++ArgIdx) {
7400 if (FromEPI.ConsumedArguments[ArgIdx] !=
7401 ToEPI.ConsumedArguments[ArgIdx])
7407 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7408 /// 'RHS' attributes and returns the merged version; including for function
7410 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7411 QualType LHSCan = getCanonicalType(LHS),
7412 RHSCan = getCanonicalType(RHS);
7413 // If two types are identical, they are compatible.
7414 if (LHSCan == RHSCan)
7416 if (RHSCan->isFunctionType()) {
7417 if (!LHSCan->isFunctionType())
7419 QualType OldReturnType =
7420 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7421 QualType NewReturnType =
7422 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7423 QualType ResReturnType =
7424 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7425 if (ResReturnType.isNull())
7427 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7428 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7429 // In either case, use OldReturnType to build the new function type.
7430 const FunctionType *F = LHS->getAs<FunctionType>();
7431 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7432 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7433 EPI.ExtInfo = getFunctionExtInfo(LHS);
7434 QualType ResultType =
7435 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
7442 // If the qualifiers are different, the types can still be merged.
7443 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7444 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7445 if (LQuals != RQuals) {
7446 // If any of these qualifiers are different, we have a type mismatch.
7447 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7448 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7451 // Exactly one GC qualifier difference is allowed: __strong is
7452 // okay if the other type has no GC qualifier but is an Objective
7453 // C object pointer (i.e. implicitly strong by default). We fix
7454 // this by pretending that the unqualified type was actually
7455 // qualified __strong.
7456 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7457 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7458 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7460 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7463 if (GC_L == Qualifiers::Strong)
7465 if (GC_R == Qualifiers::Strong)
7470 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7471 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7472 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7473 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7474 if (ResQT == LHSBaseQT)
7476 if (ResQT == RHSBaseQT)
7482 //===----------------------------------------------------------------------===//
7483 // Integer Predicates
7484 //===----------------------------------------------------------------------===//
7486 unsigned ASTContext::getIntWidth(QualType T) const {
7487 if (const EnumType *ET = T->getAs<EnumType>())
7488 T = ET->getDecl()->getIntegerType();
7489 if (T->isBooleanType())
7491 // For builtin types, just use the standard type sizing method
7492 return (unsigned)getTypeSize(T);
7495 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7496 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7498 // Turn <4 x signed int> -> <4 x unsigned int>
7499 if (const VectorType *VTy = T->getAs<VectorType>())
7500 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7501 VTy->getNumElements(), VTy->getVectorKind());
7503 // For enums, we return the unsigned version of the base type.
7504 if (const EnumType *ETy = T->getAs<EnumType>())
7505 T = ETy->getDecl()->getIntegerType();
7507 const BuiltinType *BTy = T->getAs<BuiltinType>();
7508 assert(BTy && "Unexpected signed integer type");
7509 switch (BTy->getKind()) {
7510 case BuiltinType::Char_S:
7511 case BuiltinType::SChar:
7512 return UnsignedCharTy;
7513 case BuiltinType::Short:
7514 return UnsignedShortTy;
7515 case BuiltinType::Int:
7516 return UnsignedIntTy;
7517 case BuiltinType::Long:
7518 return UnsignedLongTy;
7519 case BuiltinType::LongLong:
7520 return UnsignedLongLongTy;
7521 case BuiltinType::Int128:
7522 return UnsignedInt128Ty;
7524 llvm_unreachable("Unexpected signed integer type");
7528 ASTMutationListener::~ASTMutationListener() { }
7530 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7531 QualType ReturnType) {}
7533 //===----------------------------------------------------------------------===//
7534 // Builtin Type Computation
7535 //===----------------------------------------------------------------------===//
7537 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7538 /// pointer over the consumed characters. This returns the resultant type. If
7539 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7540 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7541 /// a vector of "i*".
7543 /// RequiresICE is filled in on return to indicate whether the value is required
7544 /// to be an Integer Constant Expression.
7545 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7546 ASTContext::GetBuiltinTypeError &Error,
7548 bool AllowTypeModifiers) {
7551 bool Signed = false, Unsigned = false;
7552 RequiresICE = false;
7554 // Read the prefixed modifiers first.
7558 default: Done = true; --Str; break;
7563 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7564 assert(!Signed && "Can't use 'S' modifier multiple times!");
7568 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7569 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7573 assert(HowLong <= 2 && "Can't have LLLL modifier");
7581 // Read the base type.
7583 default: llvm_unreachable("Unknown builtin type letter!");
7585 assert(HowLong == 0 && !Signed && !Unsigned &&
7586 "Bad modifiers used with 'v'!");
7587 Type = Context.VoidTy;
7590 assert(HowLong == 0 && !Signed && !Unsigned &&
7591 "Bad modifiers used with 'f'!");
7592 Type = Context.HalfTy;
7595 assert(HowLong == 0 && !Signed && !Unsigned &&
7596 "Bad modifiers used with 'f'!");
7597 Type = Context.FloatTy;
7600 assert(HowLong < 2 && !Signed && !Unsigned &&
7601 "Bad modifiers used with 'd'!");
7603 Type = Context.LongDoubleTy;
7605 Type = Context.DoubleTy;
7608 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7610 Type = Context.UnsignedShortTy;
7612 Type = Context.ShortTy;
7616 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7617 else if (HowLong == 2)
7618 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7619 else if (HowLong == 1)
7620 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7622 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7625 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7627 Type = Context.SignedCharTy;
7629 Type = Context.UnsignedCharTy;
7631 Type = Context.CharTy;
7633 case 'b': // boolean
7634 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7635 Type = Context.BoolTy;
7637 case 'z': // size_t.
7638 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7639 Type = Context.getSizeType();
7642 Type = Context.getCFConstantStringType();
7645 Type = Context.getObjCIdType();
7648 Type = Context.getObjCSelType();
7651 Type = Context.getObjCSuperType();
7654 Type = Context.getBuiltinVaListType();
7655 assert(!Type.isNull() && "builtin va list type not initialized!");
7658 // This is a "reference" to a va_list; however, what exactly
7659 // this means depends on how va_list is defined. There are two
7660 // different kinds of va_list: ones passed by value, and ones
7661 // passed by reference. An example of a by-value va_list is
7662 // x86, where va_list is a char*. An example of by-ref va_list
7663 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7664 // we want this argument to be a char*&; for x86-64, we want
7665 // it to be a __va_list_tag*.
7666 Type = Context.getBuiltinVaListType();
7667 assert(!Type.isNull() && "builtin va list type not initialized!");
7668 if (Type->isArrayType())
7669 Type = Context.getArrayDecayedType(Type);
7671 Type = Context.getLValueReferenceType(Type);
7675 unsigned NumElements = strtoul(Str, &End, 10);
7676 assert(End != Str && "Missing vector size");
7679 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7680 RequiresICE, false);
7681 assert(!RequiresICE && "Can't require vector ICE");
7683 // TODO: No way to make AltiVec vectors in builtins yet.
7684 Type = Context.getVectorType(ElementType, NumElements,
7685 VectorType::GenericVector);
7691 unsigned NumElements = strtoul(Str, &End, 10);
7692 assert(End != Str && "Missing vector size");
7696 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7698 Type = Context.getExtVectorType(ElementType, NumElements);
7702 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7704 assert(!RequiresICE && "Can't require complex ICE");
7705 Type = Context.getComplexType(ElementType);
7709 Type = Context.getPointerDiffType();
7713 Type = Context.getFILEType();
7714 if (Type.isNull()) {
7715 Error = ASTContext::GE_Missing_stdio;
7721 Type = Context.getsigjmp_bufType();
7723 Type = Context.getjmp_bufType();
7725 if (Type.isNull()) {
7726 Error = ASTContext::GE_Missing_setjmp;
7731 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7732 Type = Context.getucontext_tType();
7734 if (Type.isNull()) {
7735 Error = ASTContext::GE_Missing_ucontext;
7740 Type = Context.getProcessIDType();
7744 // If there are modifiers and if we're allowed to parse them, go for it.
7745 Done = !AllowTypeModifiers;
7747 switch (char c = *Str++) {
7748 default: Done = true; --Str; break;
7751 // Both pointers and references can have their pointee types
7752 // qualified with an address space.
7754 unsigned AddrSpace = strtoul(Str, &End, 10);
7755 if (End != Str && AddrSpace != 0) {
7756 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7760 Type = Context.getPointerType(Type);
7762 Type = Context.getLValueReferenceType(Type);
7765 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7767 Type = Type.withConst();
7770 Type = Context.getVolatileType(Type);
7773 Type = Type.withRestrict();
7778 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7779 "Integer constant 'I' type must be an integer");
7784 /// GetBuiltinType - Return the type for the specified builtin.
7785 QualType ASTContext::GetBuiltinType(unsigned Id,
7786 GetBuiltinTypeError &Error,
7787 unsigned *IntegerConstantArgs) const {
7788 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7790 SmallVector<QualType, 8> ArgTypes;
7792 bool RequiresICE = false;
7794 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7796 if (Error != GE_None)
7799 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7801 while (TypeStr[0] && TypeStr[0] != '.') {
7802 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7803 if (Error != GE_None)
7806 // If this argument is required to be an IntegerConstantExpression and the
7807 // caller cares, fill in the bitmask we return.
7808 if (RequiresICE && IntegerConstantArgs)
7809 *IntegerConstantArgs |= 1 << ArgTypes.size();
7811 // Do array -> pointer decay. The builtin should use the decayed type.
7812 if (Ty->isArrayType())
7813 Ty = getArrayDecayedType(Ty);
7815 ArgTypes.push_back(Ty);
7818 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7819 "'.' should only occur at end of builtin type list!");
7821 FunctionType::ExtInfo EI(CC_C);
7822 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7824 bool Variadic = (TypeStr[0] == '.');
7826 // We really shouldn't be making a no-proto type here, especially in C++.
7827 if (ArgTypes.empty() && Variadic)
7828 return getFunctionNoProtoType(ResType, EI);
7830 FunctionProtoType::ExtProtoInfo EPI;
7832 EPI.Variadic = Variadic;
7834 return getFunctionType(ResType, ArgTypes, EPI);
7837 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7838 if (!FD->isExternallyVisible())
7839 return GVA_Internal;
7841 GVALinkage External = GVA_StrongExternal;
7842 switch (FD->getTemplateSpecializationKind()) {
7843 case TSK_Undeclared:
7844 case TSK_ExplicitSpecialization:
7845 External = GVA_StrongExternal;
7848 case TSK_ExplicitInstantiationDefinition:
7849 return GVA_ExplicitTemplateInstantiation;
7851 case TSK_ExplicitInstantiationDeclaration:
7852 case TSK_ImplicitInstantiation:
7853 External = GVA_TemplateInstantiation;
7857 if (!FD->isInlined())
7860 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7861 FD->hasAttr<GNUInlineAttr>()) {
7862 // GNU or C99 inline semantics. Determine whether this symbol should be
7863 // externally visible.
7864 if (FD->isInlineDefinitionExternallyVisible())
7867 // C99 inline semantics, where the symbol is not externally visible.
7868 return GVA_C99Inline;
7871 // C++0x [temp.explicit]p9:
7872 // [ Note: The intent is that an inline function that is the subject of
7873 // an explicit instantiation declaration will still be implicitly
7874 // instantiated when used so that the body can be considered for
7875 // inlining, but that no out-of-line copy of the inline function would be
7876 // generated in the translation unit. -- end note ]
7877 if (FD->getTemplateSpecializationKind()
7878 == TSK_ExplicitInstantiationDeclaration)
7879 return GVA_C99Inline;
7881 return GVA_CXXInline;
7884 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7885 if (!VD->isExternallyVisible())
7886 return GVA_Internal;
7888 switch (VD->getTemplateSpecializationKind()) {
7889 case TSK_Undeclared:
7890 case TSK_ExplicitSpecialization:
7891 return GVA_StrongExternal;
7893 case TSK_ExplicitInstantiationDeclaration:
7894 llvm_unreachable("Variable should not be instantiated");
7895 // Fall through to treat this like any other instantiation.
7897 case TSK_ExplicitInstantiationDefinition:
7898 return GVA_ExplicitTemplateInstantiation;
7900 case TSK_ImplicitInstantiation:
7901 return GVA_TemplateInstantiation;
7904 llvm_unreachable("Invalid Linkage!");
7907 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7908 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7909 if (!VD->isFileVarDecl())
7911 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7912 // We never need to emit an uninstantiated function template.
7913 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7918 // If this is a member of a class template, we do not need to emit it.
7919 if (D->getDeclContext()->isDependentContext())
7922 // Weak references don't produce any output by themselves.
7923 if (D->hasAttr<WeakRefAttr>())
7926 // Aliases and used decls are required.
7927 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7930 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7931 // Forward declarations aren't required.
7932 if (!FD->doesThisDeclarationHaveABody())
7933 return FD->doesDeclarationForceExternallyVisibleDefinition();
7935 // Constructors and destructors are required.
7936 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7939 // The key function for a class is required. This rule only comes
7940 // into play when inline functions can be key functions, though.
7941 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7942 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7943 const CXXRecordDecl *RD = MD->getParent();
7944 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7945 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7946 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7952 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7954 // static, static inline, always_inline, and extern inline functions can
7955 // always be deferred. Normal inline functions can be deferred in C99/C++.
7956 // Implicit template instantiations can also be deferred in C++.
7957 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
7958 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7963 const VarDecl *VD = cast<VarDecl>(D);
7964 assert(VD->isFileVarDecl() && "Expected file scoped var");
7966 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7969 // Variables that can be needed in other TUs are required.
7970 GVALinkage L = GetGVALinkageForVariable(VD);
7971 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7974 // Variables that have destruction with side-effects are required.
7975 if (VD->getType().isDestructedType())
7978 // Variables that have initialization with side-effects are required.
7979 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7985 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7986 bool IsCXXMethod) const {
7987 // Pass through to the C++ ABI object
7989 return ABI->getDefaultMethodCallConv(IsVariadic);
7991 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
7994 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7995 // Pass through to the C++ ABI object
7996 return ABI->isNearlyEmpty(RD);
7999 MangleContext *ASTContext::createMangleContext() {
8000 switch (Target->getCXXABI().getKind()) {
8001 case TargetCXXABI::GenericAArch64:
8002 case TargetCXXABI::GenericItanium:
8003 case TargetCXXABI::GenericARM:
8004 case TargetCXXABI::iOS:
8005 return ItaniumMangleContext::create(*this, getDiagnostics());
8006 case TargetCXXABI::Microsoft:
8007 return MicrosoftMangleContext::create(*this, getDiagnostics());
8009 llvm_unreachable("Unsupported ABI");
8012 CXXABI::~CXXABI() {}
8014 size_t ASTContext::getSideTableAllocatedMemory() const {
8015 return ASTRecordLayouts.getMemorySize() +
8016 llvm::capacity_in_bytes(ObjCLayouts) +
8017 llvm::capacity_in_bytes(KeyFunctions) +
8018 llvm::capacity_in_bytes(ObjCImpls) +
8019 llvm::capacity_in_bytes(BlockVarCopyInits) +
8020 llvm::capacity_in_bytes(DeclAttrs) +
8021 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8022 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8023 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8024 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8025 llvm::capacity_in_bytes(OverriddenMethods) +
8026 llvm::capacity_in_bytes(Types) +
8027 llvm::capacity_in_bytes(VariableArrayTypes) +
8028 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8031 /// getIntTypeForBitwidth -
8032 /// sets integer QualTy according to specified details:
8033 /// bitwidth, signed/unsigned.
8034 /// Returns empty type if there is no appropriate target types.
8035 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8036 unsigned Signed) const {
8037 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8038 CanQualType QualTy = getFromTargetType(Ty);
8039 if (!QualTy && DestWidth == 128)
8040 return Signed ? Int128Ty : UnsignedInt128Ty;
8044 /// getRealTypeForBitwidth -
8045 /// sets floating point QualTy according to specified bitwidth.
8046 /// Returns empty type if there is no appropriate target types.
8047 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8048 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8050 case TargetInfo::Float:
8052 case TargetInfo::Double:
8054 case TargetInfo::LongDouble:
8055 return LongDoubleTy;
8056 case TargetInfo::NoFloat:
8060 llvm_unreachable("Unhandled TargetInfo::RealType value");
8063 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8065 MangleNumbers[ND] = Number;
8068 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8069 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8070 MangleNumbers.find(ND);
8071 return I != MangleNumbers.end() ? I->second : 1;
8074 MangleNumberingContext &
8075 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8076 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8077 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8079 MCtx = createMangleNumberingContext();
8083 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8084 return ABI->createMangleNumberingContext();
8087 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8088 ParamIndices[D] = index;
8091 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8092 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8093 assert(I != ParamIndices.end() &&
8094 "ParmIndices lacks entry set by ParmVarDecl");
8099 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8101 assert(E && E->getStorageDuration() == SD_Static &&
8102 "don't need to cache the computed value for this temporary");
8104 return &MaterializedTemporaryValues[E];
8106 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8107 MaterializedTemporaryValues.find(E);
8108 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8111 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8112 const llvm::Triple &T = getTargetInfo().getTriple();
8113 if (!T.isOSDarwin())
8116 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8117 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8120 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8121 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8122 uint64_t Size = sizeChars.getQuantity();
8123 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8124 unsigned Align = alignChars.getQuantity();
8125 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8126 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8131 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8132 /// parents as defined by the \c RecursiveASTVisitor.
8134 /// Note that the relationship described here is purely in terms of AST
8135 /// traversal - there are other relationships (for example declaration context)
8136 /// in the AST that are better modeled by special matchers.
8138 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8139 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8142 /// \brief Builds and returns the translation unit's parent map.
8144 /// The caller takes ownership of the returned \c ParentMap.
8145 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8146 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8147 Visitor.TraverseDecl(&TU);
8148 return Visitor.Parents;
8152 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8154 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8157 bool shouldVisitTemplateInstantiations() const {
8160 bool shouldVisitImplicitCode() const {
8163 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8164 // are not triggered during data recursion.
8165 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8169 template <typename T>
8170 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8173 if (ParentStack.size() > 0)
8174 // FIXME: Currently we add the same parent multiple times, for example
8175 // when we visit all subexpressions of template instantiations; this is
8176 // suboptimal, bug benign: the only way to visit those is with
8177 // hasAncestor / hasParent, and those do not create new matches.
8178 // The plan is to enable DynTypedNode to be storable in a map or hash
8179 // map. The main problem there is to implement hash functions /
8180 // comparison operators for all types that DynTypedNode supports that
8181 // do not have pointer identity.
8182 (*Parents)[Node].push_back(ParentStack.back());
8183 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8184 bool Result = (this ->* traverse) (Node);
8185 ParentStack.pop_back();
8189 bool TraverseDecl(Decl *DeclNode) {
8190 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8193 bool TraverseStmt(Stmt *StmtNode) {
8194 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8197 ASTContext::ParentMap *Parents;
8198 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8200 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8205 ASTContext::ParentVector
8206 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8207 assert(Node.getMemoizationData() &&
8208 "Invariant broken: only nodes that support memoization may be "
8209 "used in the parent map.");
8211 // We always need to run over the whole translation unit, as
8212 // hasAncestor can escape any subtree.
8214 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8216 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8217 if (I == AllParents->end()) {
8218 return ParentVector();
8224 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8225 const ObjCMethodDecl *MethodImpl) {
8226 // No point trying to match an unavailable/deprecated mothod.
8227 if (MethodDecl->hasAttr<UnavailableAttr>()
8228 || MethodDecl->hasAttr<DeprecatedAttr>())
8230 if (MethodDecl->getObjCDeclQualifier() !=
8231 MethodImpl->getObjCDeclQualifier())
8233 if (!hasSameType(MethodDecl->getResultType(),
8234 MethodImpl->getResultType()))
8237 if (MethodDecl->param_size() != MethodImpl->param_size())
8240 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8241 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8242 EF = MethodDecl->param_end();
8243 IM != EM && IF != EF; ++IM, ++IF) {
8244 const ParmVarDecl *DeclVar = (*IF);
8245 const ParmVarDecl *ImplVar = (*IM);
8246 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8248 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8251 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());