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"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTMutationListener.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/Capacity.h"
37 using namespace clang;
39 unsigned ASTContext::NumImplicitDefaultConstructors;
40 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
41 unsigned ASTContext::NumImplicitCopyConstructors;
42 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
43 unsigned ASTContext::NumImplicitMoveConstructors;
44 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
45 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
47 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
49 unsigned ASTContext::NumImplicitDestructors;
50 unsigned ASTContext::NumImplicitDestructorsDeclared;
53 HalfRank, FloatRank, DoubleRank, LongDoubleRank
57 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
61 ID.AddBoolean(Parm->isParameterPack());
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
70 ID.AddBoolean(TTP->isParameterPack());
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
76 ID.AddBoolean(NTTP->isParameterPack());
77 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
78 if (NTTP->isExpandedParameterPack()) {
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
94 TemplateTemplateParmDecl *
95 ASTContext::getCanonicalTemplateTemplateParmDecl(
96 TemplateTemplateParmDecl *TTP) const {
97 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
104 return Canonical->getParam();
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
108 SmallVector<NamedDecl *, 4> CanonParams;
109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
139 NTTP->getPosition(), 0,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
150 NTTP->getPosition(), 0,
152 NTTP->isParameterPack(),
155 CanonParams.push_back(Param);
158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
166 TTP->isParameterPack(),
168 TemplateParameterList::Create(*this, SourceLocation(),
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
185 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
186 if (!LangOpts.CPlusPlus) return 0;
188 switch (T.getCXXABI()) {
190 return CreateARMCXXABI(*this);
192 return CreateItaniumCXXABI(*this);
193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
199 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
209 return &FakeAddrSpaceMap;
211 return &T.getAddressSpaceMap();
215 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
217 IdentifierTable &idents, SelectorTable &sels,
218 Builtin::Context &builtins,
219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
234 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
238 ExternalSource(0), Listener(0),
240 UniqueBlockByRefTypeID(0)
242 if (size_reserve > 0) Types.reserve(size_reserve);
243 TUDecl = TranslationUnitDecl::Create(*this);
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
251 ASTContext::~ASTContext() {
252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
264 OM->second.Destroy();
266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
285 A->second->~AttrVec();
288 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
293 ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
297 void ASTContext::PrintStats() const {
298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
301 unsigned counts[] = {
302 #define TYPE(Name, Parent) 0,
303 #define ABSTRACT_TYPE(Name, Parent)
304 #include "clang/AST/TypeNodes.def"
308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
310 counts[(unsigned)T->getTypeClass()]++;
314 unsigned TotalBytes = 0;
315 #define TYPE(Name, Parent) \
317 llvm::errs() << " " << counts[Idx] << " " << #Name \
319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
321 #define ABSTRACT_TYPE(Name, Parent)
322 #include "clang/AST/TypeNodes.def"
324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
326 // Implicit special member functions.
327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
333 if (getLangOptions().CPlusPlus)
334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
340 if (getLangOptions().CPlusPlus)
341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
348 if (ExternalSource.get()) {
349 llvm::errs() << "\n";
350 ExternalSource->PrintStats();
353 BumpAlloc.PrintStats();
356 TypedefDecl *ASTContext::getInt128Decl() const {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
363 &Idents.get("__int128_t"),
370 TypedefDecl *ASTContext::getUInt128Decl() const {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
377 &Idents.get("__uint128_t"),
384 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
390 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
393 assert(VoidTy.isNull() && "Context reinitialized?");
395 this->Target = &Target;
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401 InitBuiltinType(VoidTy, BuiltinType::Void);
404 InitBuiltinType(BoolTy, BuiltinType::Bool);
406 if (LangOpts.CharIsSigned)
407 InitBuiltinType(CharTy, BuiltinType::Char_S);
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
439 WCharTy = getFromTargetType(Target.getWCharType());
441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
444 Char16Ty = getFromTargetType(Target.getChar16Type());
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
449 Char32Ty = getFromTargetType(Target.getChar32Type());
451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
464 // "any" type; useful for debugger-like clients.
465 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
468 FloatComplexTy = getComplexType(FloatTy);
469 DoubleComplexTy = getComplexType(DoubleTy);
470 LongDoubleComplexTy = getComplexType(LongDoubleTy);
472 BuiltinVaListType = QualType();
474 // Builtin types for 'id', 'Class', and 'SEL'.
475 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
476 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
477 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
479 ObjCConstantStringType = QualType();
482 VoidPtrTy = getPointerType(VoidTy);
484 // nullptr type (C++0x 2.14.7)
485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
487 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
488 InitBuiltinType(HalfTy, BuiltinType::Half);
491 DiagnosticsEngine &ASTContext::getDiagnostics() const {
492 return SourceMgr.getDiagnostics();
495 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
496 AttrVec *&Result = DeclAttrs[D];
498 void *Mem = Allocate(sizeof(AttrVec));
499 Result = new (Mem) AttrVec;
505 /// \brief Erase the attributes corresponding to the given declaration.
506 void ASTContext::eraseDeclAttrs(const Decl *D) {
507 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
508 if (Pos != DeclAttrs.end()) {
509 Pos->second->~AttrVec();
510 DeclAttrs.erase(Pos);
514 MemberSpecializationInfo *
515 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
516 assert(Var->isStaticDataMember() && "Not a static data member");
517 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
518 = InstantiatedFromStaticDataMember.find(Var);
519 if (Pos == InstantiatedFromStaticDataMember.end())
526 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
527 TemplateSpecializationKind TSK,
528 SourceLocation PointOfInstantiation) {
529 assert(Inst->isStaticDataMember() && "Not a static data member");
530 assert(Tmpl->isStaticDataMember() && "Not a static data member");
531 assert(!InstantiatedFromStaticDataMember[Inst] &&
532 "Already noted what static data member was instantiated from");
533 InstantiatedFromStaticDataMember[Inst]
534 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
537 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
538 const FunctionDecl *FD){
539 assert(FD && "Specialization is 0");
540 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
541 = ClassScopeSpecializationPattern.find(FD);
542 if (Pos == ClassScopeSpecializationPattern.end())
548 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
549 FunctionDecl *Pattern) {
550 assert(FD && "Specialization is 0");
551 assert(Pattern && "Class scope specialization pattern is 0");
552 ClassScopeSpecializationPattern[FD] = Pattern;
556 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
557 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
558 = InstantiatedFromUsingDecl.find(UUD);
559 if (Pos == InstantiatedFromUsingDecl.end())
566 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
567 assert((isa<UsingDecl>(Pattern) ||
568 isa<UnresolvedUsingValueDecl>(Pattern) ||
569 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
570 "pattern decl is not a using decl");
571 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
572 InstantiatedFromUsingDecl[Inst] = Pattern;
576 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
577 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
578 = InstantiatedFromUsingShadowDecl.find(Inst);
579 if (Pos == InstantiatedFromUsingShadowDecl.end())
586 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
587 UsingShadowDecl *Pattern) {
588 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
589 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
592 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
593 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
594 = InstantiatedFromUnnamedFieldDecl.find(Field);
595 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
601 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
603 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
604 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
605 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
606 "Already noted what unnamed field was instantiated from");
608 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
611 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
612 const FieldDecl *LastFD) const {
613 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
614 FD->getBitWidthValue(*this) == 0);
617 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
618 const FieldDecl *LastFD) const {
619 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
620 FD->getBitWidthValue(*this) == 0 &&
621 LastFD->getBitWidthValue(*this) != 0);
624 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
627 FD->getBitWidthValue(*this) &&
628 LastFD->getBitWidthValue(*this));
631 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
632 const FieldDecl *LastFD) const {
633 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
634 LastFD->getBitWidthValue(*this));
637 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
638 const FieldDecl *LastFD) const {
639 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
640 FD->getBitWidthValue(*this));
643 ASTContext::overridden_cxx_method_iterator
644 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
645 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
646 = OverriddenMethods.find(Method);
647 if (Pos == OverriddenMethods.end())
650 return Pos->second.begin();
653 ASTContext::overridden_cxx_method_iterator
654 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
655 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
656 = OverriddenMethods.find(Method);
657 if (Pos == OverriddenMethods.end())
660 return Pos->second.end();
664 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
665 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
666 = OverriddenMethods.find(Method);
667 if (Pos == OverriddenMethods.end())
670 return Pos->second.size();
673 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
674 const CXXMethodDecl *Overridden) {
675 OverriddenMethods[Method].push_back(Overridden);
678 //===----------------------------------------------------------------------===//
679 // Type Sizing and Analysis
680 //===----------------------------------------------------------------------===//
682 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
683 /// scalar floating point type.
684 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
685 const BuiltinType *BT = T->getAs<BuiltinType>();
686 assert(BT && "Not a floating point type!");
687 switch (BT->getKind()) {
688 default: llvm_unreachable("Not a floating point type!");
689 case BuiltinType::Half: return Target->getHalfFormat();
690 case BuiltinType::Float: return Target->getFloatFormat();
691 case BuiltinType::Double: return Target->getDoubleFormat();
692 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
696 /// getDeclAlign - Return a conservative estimate of the alignment of the
697 /// specified decl. Note that bitfields do not have a valid alignment, so
698 /// this method will assert on them.
699 /// If @p RefAsPointee, references are treated like their underlying type
700 /// (for alignof), else they're treated like pointers (for CodeGen).
701 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
702 unsigned Align = Target->getCharWidth();
704 bool UseAlignAttrOnly = false;
705 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
706 Align = AlignFromAttr;
708 // __attribute__((aligned)) can increase or decrease alignment
709 // *except* on a struct or struct member, where it only increases
710 // alignment unless 'packed' is also specified.
712 // It is an error for alignas to decrease alignment, so we can
713 // ignore that possibility; Sema should diagnose it.
714 if (isa<FieldDecl>(D)) {
715 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
716 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
718 UseAlignAttrOnly = true;
721 else if (isa<FieldDecl>(D))
723 D->hasAttr<PackedAttr>() ||
724 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
726 // If we're using the align attribute only, just ignore everything
727 // else about the declaration and its type.
728 if (UseAlignAttrOnly) {
731 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
732 QualType T = VD->getType();
733 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
735 T = RT->getPointeeType();
737 T = getPointerType(RT->getPointeeType());
739 if (!T->isIncompleteType() && !T->isFunctionType()) {
740 // Adjust alignments of declarations with array type by the
741 // large-array alignment on the target.
742 unsigned MinWidth = Target->getLargeArrayMinWidth();
743 const ArrayType *arrayType;
744 if (MinWidth && (arrayType = getAsArrayType(T))) {
745 if (isa<VariableArrayType>(arrayType))
746 Align = std::max(Align, Target->getLargeArrayAlign());
747 else if (isa<ConstantArrayType>(arrayType) &&
748 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
749 Align = std::max(Align, Target->getLargeArrayAlign());
751 // Walk through any array types while we're at it.
752 T = getBaseElementType(arrayType);
754 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
757 // Fields can be subject to extra alignment constraints, like if
758 // the field is packed, the struct is packed, or the struct has a
759 // a max-field-alignment constraint (#pragma pack). So calculate
760 // the actual alignment of the field within the struct, and then
761 // (as we're expected to) constrain that by the alignment of the type.
762 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
763 // So calculate the alignment of the field.
764 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
766 // Start with the record's overall alignment.
767 unsigned fieldAlign = toBits(layout.getAlignment());
769 // Use the GCD of that and the offset within the record.
770 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
772 // Alignment is always a power of 2, so the GCD will be a power of 2,
773 // which means we get to do this crazy thing instead of Euclid's.
774 uint64_t lowBitOfOffset = offset & (~offset + 1);
775 if (lowBitOfOffset < fieldAlign)
776 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
779 Align = std::min(Align, fieldAlign);
783 return toCharUnitsFromBits(Align);
786 std::pair<CharUnits, CharUnits>
787 ASTContext::getTypeInfoInChars(const Type *T) const {
788 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
789 return std::make_pair(toCharUnitsFromBits(Info.first),
790 toCharUnitsFromBits(Info.second));
793 std::pair<CharUnits, CharUnits>
794 ASTContext::getTypeInfoInChars(QualType T) const {
795 return getTypeInfoInChars(T.getTypePtr());
798 /// getTypeSize - Return the size of the specified type, in bits. This method
799 /// does not work on incomplete types.
801 /// FIXME: Pointers into different addr spaces could have different sizes and
802 /// alignment requirements: getPointerInfo should take an AddrSpace, this
803 /// should take a QualType, &c.
804 std::pair<uint64_t, unsigned>
805 ASTContext::getTypeInfo(const Type *T) const {
808 switch (T->getTypeClass()) {
809 #define TYPE(Class, Base)
810 #define ABSTRACT_TYPE(Class, Base)
811 #define NON_CANONICAL_TYPE(Class, Base)
812 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
813 #include "clang/AST/TypeNodes.def"
814 llvm_unreachable("Should not see dependent types");
817 case Type::FunctionNoProto:
818 case Type::FunctionProto:
819 // GCC extension: alignof(function) = 32 bits
824 case Type::IncompleteArray:
825 case Type::VariableArray:
827 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
830 case Type::ConstantArray: {
831 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
833 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
834 Width = EltInfo.first*CAT->getSize().getZExtValue();
835 Align = EltInfo.second;
836 Width = llvm::RoundUpToAlignment(Width, Align);
839 case Type::ExtVector:
841 const VectorType *VT = cast<VectorType>(T);
842 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
843 Width = EltInfo.first*VT->getNumElements();
845 // If the alignment is not a power of 2, round up to the next power of 2.
846 // This happens for non-power-of-2 length vectors.
847 if (Align & (Align-1)) {
848 Align = llvm::NextPowerOf2(Align);
849 Width = llvm::RoundUpToAlignment(Width, Align);
855 switch (cast<BuiltinType>(T)->getKind()) {
856 default: llvm_unreachable("Unknown builtin type!");
857 case BuiltinType::Void:
858 // GCC extension: alignof(void) = 8 bits.
863 case BuiltinType::Bool:
864 Width = Target->getBoolWidth();
865 Align = Target->getBoolAlign();
867 case BuiltinType::Char_S:
868 case BuiltinType::Char_U:
869 case BuiltinType::UChar:
870 case BuiltinType::SChar:
871 Width = Target->getCharWidth();
872 Align = Target->getCharAlign();
874 case BuiltinType::WChar_S:
875 case BuiltinType::WChar_U:
876 Width = Target->getWCharWidth();
877 Align = Target->getWCharAlign();
879 case BuiltinType::Char16:
880 Width = Target->getChar16Width();
881 Align = Target->getChar16Align();
883 case BuiltinType::Char32:
884 Width = Target->getChar32Width();
885 Align = Target->getChar32Align();
887 case BuiltinType::UShort:
888 case BuiltinType::Short:
889 Width = Target->getShortWidth();
890 Align = Target->getShortAlign();
892 case BuiltinType::UInt:
893 case BuiltinType::Int:
894 Width = Target->getIntWidth();
895 Align = Target->getIntAlign();
897 case BuiltinType::ULong:
898 case BuiltinType::Long:
899 Width = Target->getLongWidth();
900 Align = Target->getLongAlign();
902 case BuiltinType::ULongLong:
903 case BuiltinType::LongLong:
904 Width = Target->getLongLongWidth();
905 Align = Target->getLongLongAlign();
907 case BuiltinType::Int128:
908 case BuiltinType::UInt128:
910 Align = 128; // int128_t is 128-bit aligned on all targets.
912 case BuiltinType::Half:
913 Width = Target->getHalfWidth();
914 Align = Target->getHalfAlign();
916 case BuiltinType::Float:
917 Width = Target->getFloatWidth();
918 Align = Target->getFloatAlign();
920 case BuiltinType::Double:
921 Width = Target->getDoubleWidth();
922 Align = Target->getDoubleAlign();
924 case BuiltinType::LongDouble:
925 Width = Target->getLongDoubleWidth();
926 Align = Target->getLongDoubleAlign();
928 case BuiltinType::NullPtr:
929 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
930 Align = Target->getPointerAlign(0); // == sizeof(void*)
932 case BuiltinType::ObjCId:
933 case BuiltinType::ObjCClass:
934 case BuiltinType::ObjCSel:
935 Width = Target->getPointerWidth(0);
936 Align = Target->getPointerAlign(0);
940 case Type::ObjCObjectPointer:
941 Width = Target->getPointerWidth(0);
942 Align = Target->getPointerAlign(0);
944 case Type::BlockPointer: {
945 unsigned AS = getTargetAddressSpace(
946 cast<BlockPointerType>(T)->getPointeeType());
947 Width = Target->getPointerWidth(AS);
948 Align = Target->getPointerAlign(AS);
951 case Type::LValueReference:
952 case Type::RValueReference: {
953 // alignof and sizeof should never enter this code path here, so we go
954 // the pointer route.
955 unsigned AS = getTargetAddressSpace(
956 cast<ReferenceType>(T)->getPointeeType());
957 Width = Target->getPointerWidth(AS);
958 Align = Target->getPointerAlign(AS);
961 case Type::Pointer: {
962 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
963 Width = Target->getPointerWidth(AS);
964 Align = Target->getPointerAlign(AS);
967 case Type::MemberPointer: {
968 const MemberPointerType *MPT = cast<MemberPointerType>(T);
969 std::pair<uint64_t, unsigned> PtrDiffInfo =
970 getTypeInfo(getPointerDiffType());
971 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
972 Align = PtrDiffInfo.second;
975 case Type::Complex: {
976 // Complex types have the same alignment as their elements, but twice the
978 std::pair<uint64_t, unsigned> EltInfo =
979 getTypeInfo(cast<ComplexType>(T)->getElementType());
980 Width = EltInfo.first*2;
981 Align = EltInfo.second;
984 case Type::ObjCObject:
985 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
986 case Type::ObjCInterface: {
987 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
988 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
989 Width = toBits(Layout.getSize());
990 Align = toBits(Layout.getAlignment());
995 const TagType *TT = cast<TagType>(T);
997 if (TT->getDecl()->isInvalidDecl()) {
1003 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1004 return getTypeInfo(ET->getDecl()->getIntegerType());
1006 const RecordType *RT = cast<RecordType>(TT);
1007 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1008 Width = toBits(Layout.getSize());
1009 Align = toBits(Layout.getAlignment());
1013 case Type::SubstTemplateTypeParm:
1014 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1015 getReplacementType().getTypePtr());
1018 const AutoType *A = cast<AutoType>(T);
1019 assert(A->isDeduced() && "Cannot request the size of a dependent type");
1020 return getTypeInfo(A->getDeducedType().getTypePtr());
1024 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1026 case Type::Typedef: {
1027 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1028 std::pair<uint64_t, unsigned> Info
1029 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1030 // If the typedef has an aligned attribute on it, it overrides any computed
1031 // alignment we have. This violates the GCC documentation (which says that
1032 // attribute(aligned) can only round up) but matches its implementation.
1033 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1036 Align = Info.second;
1041 case Type::TypeOfExpr:
1042 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1046 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1048 case Type::Decltype:
1049 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1052 case Type::UnaryTransform:
1053 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1055 case Type::Elaborated:
1056 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1058 case Type::Attributed:
1060 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1062 case Type::TemplateSpecialization: {
1063 assert(getCanonicalType(T) != T &&
1064 "Cannot request the size of a dependent type");
1065 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1066 // A type alias template specialization may refer to a typedef with the
1067 // aligned attribute on it.
1068 if (TST->isTypeAlias())
1069 return getTypeInfo(TST->getAliasedType().getTypePtr());
1071 return getTypeInfo(getCanonicalType(T));
1074 case Type::Atomic: {
1075 std::pair<uint64_t, unsigned> Info
1076 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1078 Align = Info.second;
1079 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1080 llvm::isPowerOf2_64(Width)) {
1081 // We can potentially perform lock-free atomic operations for this
1082 // type; promote the alignment appropriately.
1083 // FIXME: We could potentially promote the width here as well...
1084 // is that worthwhile? (Non-struct atomic types generally have
1085 // power-of-two size anyway, but structs might not. Requires a bit
1086 // of implementation work to make sure we zero out the extra bits.)
1087 Align = static_cast<unsigned>(Width);
1093 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1094 return std::make_pair(Width, Align);
1097 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1098 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1099 return CharUnits::fromQuantity(BitSize / getCharWidth());
1102 /// toBits - Convert a size in characters to a size in characters.
1103 int64_t ASTContext::toBits(CharUnits CharSize) const {
1104 return CharSize.getQuantity() * getCharWidth();
1107 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1108 /// This method does not work on incomplete types.
1109 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1110 return toCharUnitsFromBits(getTypeSize(T));
1112 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1113 return toCharUnitsFromBits(getTypeSize(T));
1116 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1117 /// characters. This method does not work on incomplete types.
1118 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1119 return toCharUnitsFromBits(getTypeAlign(T));
1121 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1122 return toCharUnitsFromBits(getTypeAlign(T));
1125 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1126 /// type for the current target in bits. This can be different than the ABI
1127 /// alignment in cases where it is beneficial for performance to overalign
1129 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1130 unsigned ABIAlign = getTypeAlign(T);
1132 // Double and long long should be naturally aligned if possible.
1133 if (const ComplexType* CT = T->getAs<ComplexType>())
1134 T = CT->getElementType().getTypePtr();
1135 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1136 T->isSpecificBuiltinType(BuiltinType::LongLong))
1137 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1142 /// DeepCollectObjCIvars -
1143 /// This routine first collects all declared, but not synthesized, ivars in
1144 /// super class and then collects all ivars, including those synthesized for
1145 /// current class. This routine is used for implementation of current class
1146 /// when all ivars, declared and synthesized are known.
1148 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1150 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1151 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1152 DeepCollectObjCIvars(SuperClass, false, Ivars);
1154 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1155 E = OI->ivar_end(); I != E; ++I)
1156 Ivars.push_back(*I);
1158 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1159 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1160 Iv= Iv->getNextIvar())
1161 Ivars.push_back(Iv);
1165 /// CollectInheritedProtocols - Collect all protocols in current class and
1166 /// those inherited by it.
1167 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1168 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1169 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1170 // We can use protocol_iterator here instead of
1171 // all_referenced_protocol_iterator since we are walking all categories.
1172 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1173 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1174 ObjCProtocolDecl *Proto = (*P);
1175 Protocols.insert(Proto);
1176 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1177 PE = Proto->protocol_end(); P != PE; ++P) {
1178 Protocols.insert(*P);
1179 CollectInheritedProtocols(*P, Protocols);
1183 // Categories of this Interface.
1184 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1185 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1186 CollectInheritedProtocols(CDeclChain, Protocols);
1187 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1189 CollectInheritedProtocols(SD, Protocols);
1190 SD = SD->getSuperClass();
1192 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1193 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1194 PE = OC->protocol_end(); P != PE; ++P) {
1195 ObjCProtocolDecl *Proto = (*P);
1196 Protocols.insert(Proto);
1197 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1198 PE = Proto->protocol_end(); P != PE; ++P)
1199 CollectInheritedProtocols(*P, Protocols);
1201 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1202 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1203 PE = OP->protocol_end(); P != PE; ++P) {
1204 ObjCProtocolDecl *Proto = (*P);
1205 Protocols.insert(Proto);
1206 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1207 PE = Proto->protocol_end(); P != PE; ++P)
1208 CollectInheritedProtocols(*P, Protocols);
1213 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1215 // Count ivars declared in class extension.
1216 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1217 CDecl = CDecl->getNextClassExtension())
1218 count += CDecl->ivar_size();
1220 // Count ivar defined in this class's implementation. This
1221 // includes synthesized ivars.
1222 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1223 count += ImplDecl->ivar_size();
1228 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1229 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1230 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1231 I = ObjCImpls.find(D);
1232 if (I != ObjCImpls.end())
1233 return cast<ObjCImplementationDecl>(I->second);
1236 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1237 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1238 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1239 I = ObjCImpls.find(D);
1240 if (I != ObjCImpls.end())
1241 return cast<ObjCCategoryImplDecl>(I->second);
1245 /// \brief Set the implementation of ObjCInterfaceDecl.
1246 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1247 ObjCImplementationDecl *ImplD) {
1248 assert(IFaceD && ImplD && "Passed null params");
1249 ObjCImpls[IFaceD] = ImplD;
1251 /// \brief Set the implementation of ObjCCategoryDecl.
1252 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1253 ObjCCategoryImplDecl *ImplD) {
1254 assert(CatD && ImplD && "Passed null params");
1255 ObjCImpls[CatD] = ImplD;
1258 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1260 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1261 assert(VD && "Passed null params");
1262 assert(VD->hasAttr<BlocksAttr>() &&
1263 "getBlockVarCopyInits - not __block var");
1264 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1265 I = BlockVarCopyInits.find(VD);
1266 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1269 /// \brief Set the copy inialization expression of a block var decl.
1270 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1271 assert(VD && Init && "Passed null params");
1272 assert(VD->hasAttr<BlocksAttr>() &&
1273 "setBlockVarCopyInits - not __block var");
1274 BlockVarCopyInits[VD] = Init;
1277 /// \brief Allocate an uninitialized TypeSourceInfo.
1279 /// The caller should initialize the memory held by TypeSourceInfo using
1280 /// the TypeLoc wrappers.
1282 /// \param T the type that will be the basis for type source info. This type
1283 /// should refer to how the declarator was written in source code, not to
1284 /// what type semantic analysis resolved the declarator to.
1285 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1286 unsigned DataSize) const {
1288 DataSize = TypeLoc::getFullDataSizeForType(T);
1290 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1291 "incorrect data size provided to CreateTypeSourceInfo!");
1293 TypeSourceInfo *TInfo =
1294 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1295 new (TInfo) TypeSourceInfo(T);
1299 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1300 SourceLocation L) const {
1301 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1302 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1306 const ASTRecordLayout &
1307 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1308 return getObjCLayout(D, 0);
1311 const ASTRecordLayout &
1312 ASTContext::getASTObjCImplementationLayout(
1313 const ObjCImplementationDecl *D) const {
1314 return getObjCLayout(D->getClassInterface(), D);
1317 //===----------------------------------------------------------------------===//
1318 // Type creation/memoization methods
1319 //===----------------------------------------------------------------------===//
1322 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1323 unsigned fastQuals = quals.getFastQualifiers();
1324 quals.removeFastQualifiers();
1326 // Check if we've already instantiated this type.
1327 llvm::FoldingSetNodeID ID;
1328 ExtQuals::Profile(ID, baseType, quals);
1329 void *insertPos = 0;
1330 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1331 assert(eq->getQualifiers() == quals);
1332 return QualType(eq, fastQuals);
1335 // If the base type is not canonical, make the appropriate canonical type.
1337 if (!baseType->isCanonicalUnqualified()) {
1338 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1339 canonSplit.second.addConsistentQualifiers(quals);
1340 canon = getExtQualType(canonSplit.first, canonSplit.second);
1342 // Re-find the insert position.
1343 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1346 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1347 ExtQualNodes.InsertNode(eq, insertPos);
1348 return QualType(eq, fastQuals);
1352 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1353 QualType CanT = getCanonicalType(T);
1354 if (CanT.getAddressSpace() == AddressSpace)
1357 // If we are composing extended qualifiers together, merge together
1358 // into one ExtQuals node.
1359 QualifierCollector Quals;
1360 const Type *TypeNode = Quals.strip(T);
1362 // If this type already has an address space specified, it cannot get
1364 assert(!Quals.hasAddressSpace() &&
1365 "Type cannot be in multiple addr spaces!");
1366 Quals.addAddressSpace(AddressSpace);
1368 return getExtQualType(TypeNode, Quals);
1371 QualType ASTContext::getObjCGCQualType(QualType T,
1372 Qualifiers::GC GCAttr) const {
1373 QualType CanT = getCanonicalType(T);
1374 if (CanT.getObjCGCAttr() == GCAttr)
1377 if (const PointerType *ptr = T->getAs<PointerType>()) {
1378 QualType Pointee = ptr->getPointeeType();
1379 if (Pointee->isAnyPointerType()) {
1380 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1381 return getPointerType(ResultType);
1385 // If we are composing extended qualifiers together, merge together
1386 // into one ExtQuals node.
1387 QualifierCollector Quals;
1388 const Type *TypeNode = Quals.strip(T);
1390 // If this type already has an ObjCGC specified, it cannot get
1392 assert(!Quals.hasObjCGCAttr() &&
1393 "Type cannot have multiple ObjCGCs!");
1394 Quals.addObjCGCAttr(GCAttr);
1396 return getExtQualType(TypeNode, Quals);
1399 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1400 FunctionType::ExtInfo Info) {
1401 if (T->getExtInfo() == Info)
1405 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1406 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1408 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1411 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1412 FPT->getNumArgs(), EPI);
1415 return cast<FunctionType>(Result.getTypePtr());
1418 /// getComplexType - Return the uniqued reference to the type for a complex
1419 /// number with the specified element type.
1420 QualType ASTContext::getComplexType(QualType T) const {
1421 // Unique pointers, to guarantee there is only one pointer of a particular
1423 llvm::FoldingSetNodeID ID;
1424 ComplexType::Profile(ID, T);
1426 void *InsertPos = 0;
1427 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1428 return QualType(CT, 0);
1430 // If the pointee type isn't canonical, this won't be a canonical type either,
1431 // so fill in the canonical type field.
1433 if (!T.isCanonical()) {
1434 Canonical = getComplexType(getCanonicalType(T));
1436 // Get the new insert position for the node we care about.
1437 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1438 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1440 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1441 Types.push_back(New);
1442 ComplexTypes.InsertNode(New, InsertPos);
1443 return QualType(New, 0);
1446 /// getPointerType - Return the uniqued reference to the type for a pointer to
1447 /// the specified type.
1448 QualType ASTContext::getPointerType(QualType T) const {
1449 // Unique pointers, to guarantee there is only one pointer of a particular
1451 llvm::FoldingSetNodeID ID;
1452 PointerType::Profile(ID, T);
1454 void *InsertPos = 0;
1455 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1456 return QualType(PT, 0);
1458 // If the pointee type isn't canonical, this won't be a canonical type either,
1459 // so fill in the canonical type field.
1461 if (!T.isCanonical()) {
1462 Canonical = getPointerType(getCanonicalType(T));
1464 // Get the new insert position for the node we care about.
1465 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1466 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1468 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1469 Types.push_back(New);
1470 PointerTypes.InsertNode(New, InsertPos);
1471 return QualType(New, 0);
1474 /// getBlockPointerType - Return the uniqued reference to the type for
1475 /// a pointer to the specified block.
1476 QualType ASTContext::getBlockPointerType(QualType T) const {
1477 assert(T->isFunctionType() && "block of function types only");
1478 // Unique pointers, to guarantee there is only one block of a particular
1480 llvm::FoldingSetNodeID ID;
1481 BlockPointerType::Profile(ID, T);
1483 void *InsertPos = 0;
1484 if (BlockPointerType *PT =
1485 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1486 return QualType(PT, 0);
1488 // If the block pointee type isn't canonical, this won't be a canonical
1489 // type either so fill in the canonical type field.
1491 if (!T.isCanonical()) {
1492 Canonical = getBlockPointerType(getCanonicalType(T));
1494 // Get the new insert position for the node we care about.
1495 BlockPointerType *NewIP =
1496 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1497 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1499 BlockPointerType *New
1500 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1501 Types.push_back(New);
1502 BlockPointerTypes.InsertNode(New, InsertPos);
1503 return QualType(New, 0);
1506 /// getLValueReferenceType - Return the uniqued reference to the type for an
1507 /// lvalue reference to the specified type.
1509 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1510 assert(getCanonicalType(T) != OverloadTy &&
1511 "Unresolved overloaded function type");
1513 // Unique pointers, to guarantee there is only one pointer of a particular
1515 llvm::FoldingSetNodeID ID;
1516 ReferenceType::Profile(ID, T, SpelledAsLValue);
1518 void *InsertPos = 0;
1519 if (LValueReferenceType *RT =
1520 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(RT, 0);
1523 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1525 // If the referencee type isn't canonical, this won't be a canonical type
1526 // either, so fill in the canonical type field.
1528 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1529 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1530 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1532 // Get the new insert position for the node we care about.
1533 LValueReferenceType *NewIP =
1534 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1535 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1538 LValueReferenceType *New
1539 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1541 Types.push_back(New);
1542 LValueReferenceTypes.InsertNode(New, InsertPos);
1544 return QualType(New, 0);
1547 /// getRValueReferenceType - Return the uniqued reference to the type for an
1548 /// rvalue reference to the specified type.
1549 QualType ASTContext::getRValueReferenceType(QualType T) const {
1550 // Unique pointers, to guarantee there is only one pointer of a particular
1552 llvm::FoldingSetNodeID ID;
1553 ReferenceType::Profile(ID, T, false);
1555 void *InsertPos = 0;
1556 if (RValueReferenceType *RT =
1557 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1558 return QualType(RT, 0);
1560 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1562 // If the referencee type isn't canonical, this won't be a canonical type
1563 // either, so fill in the canonical type field.
1565 if (InnerRef || !T.isCanonical()) {
1566 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1567 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1569 // Get the new insert position for the node we care about.
1570 RValueReferenceType *NewIP =
1571 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1572 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1575 RValueReferenceType *New
1576 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1577 Types.push_back(New);
1578 RValueReferenceTypes.InsertNode(New, InsertPos);
1579 return QualType(New, 0);
1582 /// getMemberPointerType - Return the uniqued reference to the type for a
1583 /// member pointer to the specified type, in the specified class.
1584 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1585 // Unique pointers, to guarantee there is only one pointer of a particular
1587 llvm::FoldingSetNodeID ID;
1588 MemberPointerType::Profile(ID, T, Cls);
1590 void *InsertPos = 0;
1591 if (MemberPointerType *PT =
1592 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1593 return QualType(PT, 0);
1595 // If the pointee or class type isn't canonical, this won't be a canonical
1596 // type either, so fill in the canonical type field.
1598 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1599 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1601 // Get the new insert position for the node we care about.
1602 MemberPointerType *NewIP =
1603 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1606 MemberPointerType *New
1607 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1608 Types.push_back(New);
1609 MemberPointerTypes.InsertNode(New, InsertPos);
1610 return QualType(New, 0);
1613 /// getConstantArrayType - Return the unique reference to the type for an
1614 /// array of the specified element type.
1615 QualType ASTContext::getConstantArrayType(QualType EltTy,
1616 const llvm::APInt &ArySizeIn,
1617 ArrayType::ArraySizeModifier ASM,
1618 unsigned IndexTypeQuals) const {
1619 assert((EltTy->isDependentType() ||
1620 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1621 "Constant array of VLAs is illegal!");
1623 // Convert the array size into a canonical width matching the pointer size for
1625 llvm::APInt ArySize(ArySizeIn);
1627 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
1629 llvm::FoldingSetNodeID ID;
1630 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1632 void *InsertPos = 0;
1633 if (ConstantArrayType *ATP =
1634 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1635 return QualType(ATP, 0);
1637 // If the element type isn't canonical or has qualifiers, this won't
1638 // be a canonical type either, so fill in the canonical type field.
1640 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1641 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1642 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
1643 ASM, IndexTypeQuals);
1644 Canon = getQualifiedType(Canon, canonSplit.second);
1646 // Get the new insert position for the node we care about.
1647 ConstantArrayType *NewIP =
1648 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1649 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1652 ConstantArrayType *New = new(*this,TypeAlignment)
1653 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1654 ConstantArrayTypes.InsertNode(New, InsertPos);
1655 Types.push_back(New);
1656 return QualType(New, 0);
1659 /// getVariableArrayDecayedType - Turns the given type, which may be
1660 /// variably-modified, into the corresponding type with all the known
1661 /// sizes replaced with [*].
1662 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1663 // Vastly most common case.
1664 if (!type->isVariablyModifiedType()) return type;
1668 SplitQualType split = type.getSplitDesugaredType();
1669 const Type *ty = split.first;
1670 switch (ty->getTypeClass()) {
1671 #define TYPE(Class, Base)
1672 #define ABSTRACT_TYPE(Class, Base)
1673 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1674 #include "clang/AST/TypeNodes.def"
1675 llvm_unreachable("didn't desugar past all non-canonical types?");
1677 // These types should never be variably-modified.
1681 case Type::ExtVector:
1682 case Type::DependentSizedExtVector:
1683 case Type::ObjCObject:
1684 case Type::ObjCInterface:
1685 case Type::ObjCObjectPointer:
1688 case Type::UnresolvedUsing:
1689 case Type::TypeOfExpr:
1691 case Type::Decltype:
1692 case Type::UnaryTransform:
1693 case Type::DependentName:
1694 case Type::InjectedClassName:
1695 case Type::TemplateSpecialization:
1696 case Type::DependentTemplateSpecialization:
1697 case Type::TemplateTypeParm:
1698 case Type::SubstTemplateTypeParmPack:
1700 case Type::PackExpansion:
1701 llvm_unreachable("type should never be variably-modified");
1703 // These types can be variably-modified but should never need to
1705 case Type::FunctionNoProto:
1706 case Type::FunctionProto:
1707 case Type::BlockPointer:
1708 case Type::MemberPointer:
1711 // These types can be variably-modified. All these modifications
1712 // preserve structure except as noted by comments.
1713 // TODO: if we ever care about optimizing VLAs, there are no-op
1714 // optimizations available here.
1716 result = getPointerType(getVariableArrayDecayedType(
1717 cast<PointerType>(ty)->getPointeeType()));
1720 case Type::LValueReference: {
1721 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1722 result = getLValueReferenceType(
1723 getVariableArrayDecayedType(lv->getPointeeType()),
1724 lv->isSpelledAsLValue());
1728 case Type::RValueReference: {
1729 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1730 result = getRValueReferenceType(
1731 getVariableArrayDecayedType(lv->getPointeeType()));
1735 case Type::Atomic: {
1736 const AtomicType *at = cast<AtomicType>(ty);
1737 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1741 case Type::ConstantArray: {
1742 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1743 result = getConstantArrayType(
1744 getVariableArrayDecayedType(cat->getElementType()),
1746 cat->getSizeModifier(),
1747 cat->getIndexTypeCVRQualifiers());
1751 case Type::DependentSizedArray: {
1752 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1753 result = getDependentSizedArrayType(
1754 getVariableArrayDecayedType(dat->getElementType()),
1756 dat->getSizeModifier(),
1757 dat->getIndexTypeCVRQualifiers(),
1758 dat->getBracketsRange());
1762 // Turn incomplete types into [*] types.
1763 case Type::IncompleteArray: {
1764 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1765 result = getVariableArrayType(
1766 getVariableArrayDecayedType(iat->getElementType()),
1769 iat->getIndexTypeCVRQualifiers(),
1774 // Turn VLA types into [*] types.
1775 case Type::VariableArray: {
1776 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1777 result = getVariableArrayType(
1778 getVariableArrayDecayedType(vat->getElementType()),
1781 vat->getIndexTypeCVRQualifiers(),
1782 vat->getBracketsRange());
1787 // Apply the top-level qualifiers from the original.
1788 return getQualifiedType(result, split.second);
1791 /// getVariableArrayType - Returns a non-unique reference to the type for a
1792 /// variable array of the specified element type.
1793 QualType ASTContext::getVariableArrayType(QualType EltTy,
1795 ArrayType::ArraySizeModifier ASM,
1796 unsigned IndexTypeQuals,
1797 SourceRange Brackets) const {
1798 // Since we don't unique expressions, it isn't possible to unique VLA's
1799 // that have an expression provided for their size.
1802 // Be sure to pull qualifiers off the element type.
1803 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1804 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1805 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
1806 IndexTypeQuals, Brackets);
1807 Canon = getQualifiedType(Canon, canonSplit.second);
1810 VariableArrayType *New = new(*this, TypeAlignment)
1811 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1813 VariableArrayTypes.push_back(New);
1814 Types.push_back(New);
1815 return QualType(New, 0);
1818 /// getDependentSizedArrayType - Returns a non-unique reference to
1819 /// the type for a dependently-sized array of the specified element
1821 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1823 ArrayType::ArraySizeModifier ASM,
1824 unsigned elementTypeQuals,
1825 SourceRange brackets) const {
1826 assert((!numElements || numElements->isTypeDependent() ||
1827 numElements->isValueDependent()) &&
1828 "Size must be type- or value-dependent!");
1830 // Dependently-sized array types that do not have a specified number
1831 // of elements will have their sizes deduced from a dependent
1832 // initializer. We do no canonicalization here at all, which is okay
1833 // because they can't be used in most locations.
1835 DependentSizedArrayType *newType
1836 = new (*this, TypeAlignment)
1837 DependentSizedArrayType(*this, elementType, QualType(),
1838 numElements, ASM, elementTypeQuals,
1840 Types.push_back(newType);
1841 return QualType(newType, 0);
1844 // Otherwise, we actually build a new type every time, but we
1845 // also build a canonical type.
1847 SplitQualType canonElementType = getCanonicalType(elementType).split();
1849 void *insertPos = 0;
1850 llvm::FoldingSetNodeID ID;
1851 DependentSizedArrayType::Profile(ID, *this,
1852 QualType(canonElementType.first, 0),
1853 ASM, elementTypeQuals, numElements);
1855 // Look for an existing type with these properties.
1856 DependentSizedArrayType *canonTy =
1857 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1859 // If we don't have one, build one.
1861 canonTy = new (*this, TypeAlignment)
1862 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1863 QualType(), numElements, ASM, elementTypeQuals,
1865 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1866 Types.push_back(canonTy);
1869 // Apply qualifiers from the element type to the array.
1870 QualType canon = getQualifiedType(QualType(canonTy,0),
1871 canonElementType.second);
1873 // If we didn't need extra canonicalization for the element type,
1874 // then just use that as our result.
1875 if (QualType(canonElementType.first, 0) == elementType)
1878 // Otherwise, we need to build a type which follows the spelling
1879 // of the element type.
1880 DependentSizedArrayType *sugaredType
1881 = new (*this, TypeAlignment)
1882 DependentSizedArrayType(*this, elementType, canon, numElements,
1883 ASM, elementTypeQuals, brackets);
1884 Types.push_back(sugaredType);
1885 return QualType(sugaredType, 0);
1888 QualType ASTContext::getIncompleteArrayType(QualType elementType,
1889 ArrayType::ArraySizeModifier ASM,
1890 unsigned elementTypeQuals) const {
1891 llvm::FoldingSetNodeID ID;
1892 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1894 void *insertPos = 0;
1895 if (IncompleteArrayType *iat =
1896 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1897 return QualType(iat, 0);
1899 // If the element type isn't canonical, this won't be a canonical type
1900 // either, so fill in the canonical type field. We also have to pull
1901 // qualifiers off the element type.
1904 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1905 SplitQualType canonSplit = getCanonicalType(elementType).split();
1906 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1907 ASM, elementTypeQuals);
1908 canon = getQualifiedType(canon, canonSplit.second);
1910 // Get the new insert position for the node we care about.
1911 IncompleteArrayType *existing =
1912 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1913 assert(!existing && "Shouldn't be in the map!"); (void) existing;
1916 IncompleteArrayType *newType = new (*this, TypeAlignment)
1917 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1919 IncompleteArrayTypes.InsertNode(newType, insertPos);
1920 Types.push_back(newType);
1921 return QualType(newType, 0);
1924 /// getVectorType - Return the unique reference to a vector type of
1925 /// the specified element type and size. VectorType must be a built-in type.
1926 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1927 VectorType::VectorKind VecKind) const {
1928 assert(vecType->isBuiltinType());
1930 // Check if we've already instantiated a vector of this type.
1931 llvm::FoldingSetNodeID ID;
1932 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1934 void *InsertPos = 0;
1935 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1936 return QualType(VTP, 0);
1938 // If the element type isn't canonical, this won't be a canonical type either,
1939 // so fill in the canonical type field.
1941 if (!vecType.isCanonical()) {
1942 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1944 // Get the new insert position for the node we care about.
1945 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1946 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1948 VectorType *New = new (*this, TypeAlignment)
1949 VectorType(vecType, NumElts, Canonical, VecKind);
1950 VectorTypes.InsertNode(New, InsertPos);
1951 Types.push_back(New);
1952 return QualType(New, 0);
1955 /// getExtVectorType - Return the unique reference to an extended vector type of
1956 /// the specified element type and size. VectorType must be a built-in type.
1958 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
1959 assert(vecType->isBuiltinType() || vecType->isDependentType());
1961 // Check if we've already instantiated a vector of this type.
1962 llvm::FoldingSetNodeID ID;
1963 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1964 VectorType::GenericVector);
1965 void *InsertPos = 0;
1966 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1967 return QualType(VTP, 0);
1969 // If the element type isn't canonical, this won't be a canonical type either,
1970 // so fill in the canonical type field.
1972 if (!vecType.isCanonical()) {
1973 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1975 // Get the new insert position for the node we care about.
1976 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1977 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1979 ExtVectorType *New = new (*this, TypeAlignment)
1980 ExtVectorType(vecType, NumElts, Canonical);
1981 VectorTypes.InsertNode(New, InsertPos);
1982 Types.push_back(New);
1983 return QualType(New, 0);
1987 ASTContext::getDependentSizedExtVectorType(QualType vecType,
1989 SourceLocation AttrLoc) const {
1990 llvm::FoldingSetNodeID ID;
1991 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1994 void *InsertPos = 0;
1995 DependentSizedExtVectorType *Canon
1996 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 DependentSizedExtVectorType *New;
1999 // We already have a canonical version of this array type; use it as
2000 // the canonical type for a newly-built type.
2001 New = new (*this, TypeAlignment)
2002 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2005 QualType CanonVecTy = getCanonicalType(vecType);
2006 if (CanonVecTy == vecType) {
2007 New = new (*this, TypeAlignment)
2008 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2011 DependentSizedExtVectorType *CanonCheck
2012 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2013 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2015 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2017 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2019 New = new (*this, TypeAlignment)
2020 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2024 Types.push_back(New);
2025 return QualType(New, 0);
2028 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2031 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2032 const FunctionType::ExtInfo &Info) const {
2033 const CallingConv DefaultCC = Info.getCC();
2034 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2035 CC_X86StdCall : DefaultCC;
2036 // Unique functions, to guarantee there is only one function of a particular
2038 llvm::FoldingSetNodeID ID;
2039 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2041 void *InsertPos = 0;
2042 if (FunctionNoProtoType *FT =
2043 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2044 return QualType(FT, 0);
2047 if (!ResultTy.isCanonical() ||
2048 getCanonicalCallConv(CallConv) != CallConv) {
2050 getFunctionNoProtoType(getCanonicalType(ResultTy),
2051 Info.withCallingConv(getCanonicalCallConv(CallConv)));
2053 // Get the new insert position for the node we care about.
2054 FunctionNoProtoType *NewIP =
2055 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2056 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2059 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2060 FunctionNoProtoType *New = new (*this, TypeAlignment)
2061 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2062 Types.push_back(New);
2063 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2064 return QualType(New, 0);
2067 /// getFunctionType - Return a normal function type with a typed argument
2068 /// list. isVariadic indicates whether the argument list includes '...'.
2070 ASTContext::getFunctionType(QualType ResultTy,
2071 const QualType *ArgArray, unsigned NumArgs,
2072 const FunctionProtoType::ExtProtoInfo &EPI) const {
2073 // Unique functions, to guarantee there is only one function of a particular
2075 llvm::FoldingSetNodeID ID;
2076 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2078 void *InsertPos = 0;
2079 if (FunctionProtoType *FTP =
2080 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2081 return QualType(FTP, 0);
2083 // Determine whether the type being created is already canonical or not.
2084 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
2085 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2086 if (!ArgArray[i].isCanonicalAsParam())
2087 isCanonical = false;
2089 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2090 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2091 CC_X86StdCall : DefaultCC;
2093 // If this type isn't canonical, get the canonical version of it.
2094 // The exception spec is not part of the canonical type.
2096 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2097 SmallVector<QualType, 16> CanonicalArgs;
2098 CanonicalArgs.reserve(NumArgs);
2099 for (unsigned i = 0; i != NumArgs; ++i)
2100 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2102 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2103 CanonicalEPI.ExceptionSpecType = EST_None;
2104 CanonicalEPI.NumExceptions = 0;
2105 CanonicalEPI.ExtInfo
2106 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2108 Canonical = getFunctionType(getCanonicalType(ResultTy),
2109 CanonicalArgs.data(), NumArgs,
2112 // Get the new insert position for the node we care about.
2113 FunctionProtoType *NewIP =
2114 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2115 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2118 // FunctionProtoType objects are allocated with extra bytes after
2119 // them for three variable size arrays at the end:
2120 // - parameter types
2121 // - exception types
2122 // - consumed-arguments flags
2123 // Instead of the exception types, there could be a noexcept
2125 size_t Size = sizeof(FunctionProtoType) +
2126 NumArgs * sizeof(QualType);
2127 if (EPI.ExceptionSpecType == EST_Dynamic)
2128 Size += EPI.NumExceptions * sizeof(QualType);
2129 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2130 Size += sizeof(Expr*);
2132 if (EPI.ConsumedArguments)
2133 Size += NumArgs * sizeof(bool);
2135 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2136 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2137 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2138 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2139 Types.push_back(FTP);
2140 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2141 return QualType(FTP, 0);
2145 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2146 if (!isa<CXXRecordDecl>(D)) return false;
2147 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2148 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2150 if (RD->getDescribedClassTemplate() &&
2151 !isa<ClassTemplateSpecializationDecl>(RD))
2157 /// getInjectedClassNameType - Return the unique reference to the
2158 /// injected class name type for the specified templated declaration.
2159 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2160 QualType TST) const {
2161 assert(NeedsInjectedClassNameType(Decl));
2162 if (Decl->TypeForDecl) {
2163 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2164 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
2165 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2166 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2167 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2170 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2171 Decl->TypeForDecl = newType;
2172 Types.push_back(newType);
2174 return QualType(Decl->TypeForDecl, 0);
2177 /// getTypeDeclType - Return the unique reference to the type for the
2178 /// specified type declaration.
2179 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2180 assert(Decl && "Passed null for Decl param");
2181 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2183 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2184 return getTypedefType(Typedef);
2186 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2187 "Template type parameter types are always available.");
2189 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2190 assert(!Record->getPreviousDeclaration() &&
2191 "struct/union has previous declaration");
2192 assert(!NeedsInjectedClassNameType(Record));
2193 return getRecordType(Record);
2194 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2195 assert(!Enum->getPreviousDeclaration() &&
2196 "enum has previous declaration");
2197 return getEnumType(Enum);
2198 } else if (const UnresolvedUsingTypenameDecl *Using =
2199 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2200 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2201 Decl->TypeForDecl = newType;
2202 Types.push_back(newType);
2204 llvm_unreachable("TypeDecl without a type?");
2206 return QualType(Decl->TypeForDecl, 0);
2209 /// getTypedefType - Return the unique reference to the type for the
2210 /// specified typedef name decl.
2212 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2213 QualType Canonical) const {
2214 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2216 if (Canonical.isNull())
2217 Canonical = getCanonicalType(Decl->getUnderlyingType());
2218 TypedefType *newType = new(*this, TypeAlignment)
2219 TypedefType(Type::Typedef, Decl, Canonical);
2220 Decl->TypeForDecl = newType;
2221 Types.push_back(newType);
2222 return QualType(newType, 0);
2225 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2226 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2228 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2229 if (PrevDecl->TypeForDecl)
2230 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2232 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2233 Decl->TypeForDecl = newType;
2234 Types.push_back(newType);
2235 return QualType(newType, 0);
2238 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2239 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2241 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2242 if (PrevDecl->TypeForDecl)
2243 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2245 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2246 Decl->TypeForDecl = newType;
2247 Types.push_back(newType);
2248 return QualType(newType, 0);
2251 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2252 QualType modifiedType,
2253 QualType equivalentType) {
2254 llvm::FoldingSetNodeID id;
2255 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2257 void *insertPos = 0;
2258 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2259 if (type) return QualType(type, 0);
2261 QualType canon = getCanonicalType(equivalentType);
2262 type = new (*this, TypeAlignment)
2263 AttributedType(canon, attrKind, modifiedType, equivalentType);
2265 Types.push_back(type);
2266 AttributedTypes.InsertNode(type, insertPos);
2268 return QualType(type, 0);
2272 /// \brief Retrieve a substitution-result type.
2274 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2275 QualType Replacement) const {
2276 assert(Replacement.isCanonical()
2277 && "replacement types must always be canonical");
2279 llvm::FoldingSetNodeID ID;
2280 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2281 void *InsertPos = 0;
2282 SubstTemplateTypeParmType *SubstParm
2283 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2286 SubstParm = new (*this, TypeAlignment)
2287 SubstTemplateTypeParmType(Parm, Replacement);
2288 Types.push_back(SubstParm);
2289 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2292 return QualType(SubstParm, 0);
2295 /// \brief Retrieve a
2296 QualType ASTContext::getSubstTemplateTypeParmPackType(
2297 const TemplateTypeParmType *Parm,
2298 const TemplateArgument &ArgPack) {
2300 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2301 PEnd = ArgPack.pack_end();
2303 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2304 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2308 llvm::FoldingSetNodeID ID;
2309 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2310 void *InsertPos = 0;
2311 if (SubstTemplateTypeParmPackType *SubstParm
2312 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2313 return QualType(SubstParm, 0);
2316 if (!Parm->isCanonicalUnqualified()) {
2317 Canon = getCanonicalType(QualType(Parm, 0));
2318 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2320 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2323 SubstTemplateTypeParmPackType *SubstParm
2324 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2326 Types.push_back(SubstParm);
2327 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2328 return QualType(SubstParm, 0);
2331 /// \brief Retrieve the template type parameter type for a template
2332 /// parameter or parameter pack with the given depth, index, and (optionally)
2334 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2336 TemplateTypeParmDecl *TTPDecl) const {
2337 llvm::FoldingSetNodeID ID;
2338 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2339 void *InsertPos = 0;
2340 TemplateTypeParmType *TypeParm
2341 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2344 return QualType(TypeParm, 0);
2347 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2348 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2350 TemplateTypeParmType *TypeCheck
2351 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2352 assert(!TypeCheck && "Template type parameter canonical type broken");
2355 TypeParm = new (*this, TypeAlignment)
2356 TemplateTypeParmType(Depth, Index, ParameterPack);
2358 Types.push_back(TypeParm);
2359 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2361 return QualType(TypeParm, 0);
2365 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2366 SourceLocation NameLoc,
2367 const TemplateArgumentListInfo &Args,
2368 QualType Underlying) const {
2369 assert(!Name.getAsDependentTemplateName() &&
2370 "No dependent template names here!");
2371 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2373 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2374 TemplateSpecializationTypeLoc TL
2375 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2376 TL.setTemplateNameLoc(NameLoc);
2377 TL.setLAngleLoc(Args.getLAngleLoc());
2378 TL.setRAngleLoc(Args.getRAngleLoc());
2379 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2380 TL.setArgLocInfo(i, Args[i].getLocInfo());
2385 ASTContext::getTemplateSpecializationType(TemplateName Template,
2386 const TemplateArgumentListInfo &Args,
2387 QualType Underlying) const {
2388 assert(!Template.getAsDependentTemplateName() &&
2389 "No dependent template names here!");
2391 unsigned NumArgs = Args.size();
2393 SmallVector<TemplateArgument, 4> ArgVec;
2394 ArgVec.reserve(NumArgs);
2395 for (unsigned i = 0; i != NumArgs; ++i)
2396 ArgVec.push_back(Args[i].getArgument());
2398 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2403 ASTContext::getTemplateSpecializationType(TemplateName Template,
2404 const TemplateArgument *Args,
2406 QualType Underlying) const {
2407 assert(!Template.getAsDependentTemplateName() &&
2408 "No dependent template names here!");
2409 // Look through qualified template names.
2410 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2411 Template = TemplateName(QTN->getTemplateDecl());
2414 Template.getAsTemplateDecl() &&
2415 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2418 if (!Underlying.isNull())
2419 CanonType = getCanonicalType(Underlying);
2421 assert(!isTypeAlias &&
2422 "Underlying type for template alias must be computed by caller");
2423 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2427 // Allocate the (non-canonical) template specialization type, but don't
2428 // try to unique it: these types typically have location information that
2429 // we don't unique and don't want to lose.
2430 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2431 sizeof(TemplateArgument) * NumArgs +
2432 (isTypeAlias ? sizeof(QualType) : 0),
2434 TemplateSpecializationType *Spec
2435 = new (Mem) TemplateSpecializationType(Template,
2438 isTypeAlias ? Underlying : QualType());
2440 Types.push_back(Spec);
2441 return QualType(Spec, 0);
2445 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2446 const TemplateArgument *Args,
2447 unsigned NumArgs) const {
2448 assert(!Template.getAsDependentTemplateName() &&
2449 "No dependent template names here!");
2450 assert((!Template.getAsTemplateDecl() ||
2451 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2452 "Underlying type for template alias must be computed by caller");
2454 // Look through qualified template names.
2455 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2456 Template = TemplateName(QTN->getTemplateDecl());
2458 // Build the canonical template specialization type.
2459 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2460 SmallVector<TemplateArgument, 4> CanonArgs;
2461 CanonArgs.reserve(NumArgs);
2462 for (unsigned I = 0; I != NumArgs; ++I)
2463 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2465 // Determine whether this canonical template specialization type already
2467 llvm::FoldingSetNodeID ID;
2468 TemplateSpecializationType::Profile(ID, CanonTemplate,
2469 CanonArgs.data(), NumArgs, *this);
2471 void *InsertPos = 0;
2472 TemplateSpecializationType *Spec
2473 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2476 // Allocate a new canonical template specialization type.
2477 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2478 sizeof(TemplateArgument) * NumArgs),
2480 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2481 CanonArgs.data(), NumArgs,
2482 QualType(), QualType());
2483 Types.push_back(Spec);
2484 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2487 assert(Spec->isDependentType() &&
2488 "Non-dependent template-id type must have a canonical type");
2489 return QualType(Spec, 0);
2493 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2494 NestedNameSpecifier *NNS,
2495 QualType NamedType) const {
2496 llvm::FoldingSetNodeID ID;
2497 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2499 void *InsertPos = 0;
2500 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2502 return QualType(T, 0);
2504 QualType Canon = NamedType;
2505 if (!Canon.isCanonical()) {
2506 Canon = getCanonicalType(NamedType);
2507 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2508 assert(!CheckT && "Elaborated canonical type broken");
2512 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2514 ElaboratedTypes.InsertNode(T, InsertPos);
2515 return QualType(T, 0);
2519 ASTContext::getParenType(QualType InnerType) const {
2520 llvm::FoldingSetNodeID ID;
2521 ParenType::Profile(ID, InnerType);
2523 void *InsertPos = 0;
2524 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2526 return QualType(T, 0);
2528 QualType Canon = InnerType;
2529 if (!Canon.isCanonical()) {
2530 Canon = getCanonicalType(InnerType);
2531 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 assert(!CheckT && "Paren canonical type broken");
2536 T = new (*this) ParenType(InnerType, Canon);
2538 ParenTypes.InsertNode(T, InsertPos);
2539 return QualType(T, 0);
2542 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2543 NestedNameSpecifier *NNS,
2544 const IdentifierInfo *Name,
2545 QualType Canon) const {
2546 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2548 if (Canon.isNull()) {
2549 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2550 ElaboratedTypeKeyword CanonKeyword = Keyword;
2551 if (Keyword == ETK_None)
2552 CanonKeyword = ETK_Typename;
2554 if (CanonNNS != NNS || CanonKeyword != Keyword)
2555 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2558 llvm::FoldingSetNodeID ID;
2559 DependentNameType::Profile(ID, Keyword, NNS, Name);
2561 void *InsertPos = 0;
2562 DependentNameType *T
2563 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2565 return QualType(T, 0);
2567 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2569 DependentNameTypes.InsertNode(T, InsertPos);
2570 return QualType(T, 0);
2574 ASTContext::getDependentTemplateSpecializationType(
2575 ElaboratedTypeKeyword Keyword,
2576 NestedNameSpecifier *NNS,
2577 const IdentifierInfo *Name,
2578 const TemplateArgumentListInfo &Args) const {
2579 // TODO: avoid this copy
2580 SmallVector<TemplateArgument, 16> ArgCopy;
2581 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2582 ArgCopy.push_back(Args[I].getArgument());
2583 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2589 ASTContext::getDependentTemplateSpecializationType(
2590 ElaboratedTypeKeyword Keyword,
2591 NestedNameSpecifier *NNS,
2592 const IdentifierInfo *Name,
2594 const TemplateArgument *Args) const {
2595 assert((!NNS || NNS->isDependent()) &&
2596 "nested-name-specifier must be dependent");
2598 llvm::FoldingSetNodeID ID;
2599 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2600 Name, NumArgs, Args);
2602 void *InsertPos = 0;
2603 DependentTemplateSpecializationType *T
2604 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 return QualType(T, 0);
2608 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2610 ElaboratedTypeKeyword CanonKeyword = Keyword;
2611 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2613 bool AnyNonCanonArgs = false;
2614 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2615 for (unsigned I = 0; I != NumArgs; ++I) {
2616 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2617 if (!CanonArgs[I].structurallyEquals(Args[I]))
2618 AnyNonCanonArgs = true;
2622 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2623 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2627 // Find the insert position again.
2628 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2631 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2632 sizeof(TemplateArgument) * NumArgs),
2634 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2635 Name, NumArgs, Args, Canon);
2637 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2638 return QualType(T, 0);
2641 QualType ASTContext::getPackExpansionType(QualType Pattern,
2642 llvm::Optional<unsigned> NumExpansions) {
2643 llvm::FoldingSetNodeID ID;
2644 PackExpansionType::Profile(ID, Pattern, NumExpansions);
2646 assert(Pattern->containsUnexpandedParameterPack() &&
2647 "Pack expansions must expand one or more parameter packs");
2648 void *InsertPos = 0;
2649 PackExpansionType *T
2650 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2652 return QualType(T, 0);
2655 if (!Pattern.isCanonical()) {
2656 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2658 // Find the insert position again.
2659 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2662 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2664 PackExpansionTypes.InsertNode(T, InsertPos);
2665 return QualType(T, 0);
2668 /// CmpProtocolNames - Comparison predicate for sorting protocols
2670 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2671 const ObjCProtocolDecl *RHS) {
2672 return LHS->getDeclName() < RHS->getDeclName();
2675 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2676 unsigned NumProtocols) {
2677 if (NumProtocols == 0) return true;
2679 for (unsigned i = 1; i != NumProtocols; ++i)
2680 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2685 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2686 unsigned &NumProtocols) {
2687 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2689 // Sort protocols, keyed by name.
2690 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2692 // Remove duplicates.
2693 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2694 NumProtocols = ProtocolsEnd-Protocols;
2697 QualType ASTContext::getObjCObjectType(QualType BaseType,
2698 ObjCProtocolDecl * const *Protocols,
2699 unsigned NumProtocols) const {
2700 // If the base type is an interface and there aren't any protocols
2701 // to add, then the interface type will do just fine.
2702 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2705 // Look in the folding set for an existing type.
2706 llvm::FoldingSetNodeID ID;
2707 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2708 void *InsertPos = 0;
2709 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2710 return QualType(QT, 0);
2712 // Build the canonical type, which has the canonical base type and
2713 // a sorted-and-uniqued list of protocols.
2715 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2716 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2717 if (!ProtocolsSorted) {
2718 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2719 Protocols + NumProtocols);
2720 unsigned UniqueCount = NumProtocols;
2722 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2723 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2724 &Sorted[0], UniqueCount);
2726 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2727 Protocols, NumProtocols);
2730 // Regenerate InsertPos.
2731 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2734 unsigned Size = sizeof(ObjCObjectTypeImpl);
2735 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2736 void *Mem = Allocate(Size, TypeAlignment);
2737 ObjCObjectTypeImpl *T =
2738 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2741 ObjCObjectTypes.InsertNode(T, InsertPos);
2742 return QualType(T, 0);
2745 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2746 /// the given object type.
2747 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2748 llvm::FoldingSetNodeID ID;
2749 ObjCObjectPointerType::Profile(ID, ObjectT);
2751 void *InsertPos = 0;
2752 if (ObjCObjectPointerType *QT =
2753 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2754 return QualType(QT, 0);
2756 // Find the canonical object type.
2758 if (!ObjectT.isCanonical()) {
2759 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2761 // Regenerate InsertPos.
2762 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2766 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2767 ObjCObjectPointerType *QType =
2768 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2770 Types.push_back(QType);
2771 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2772 return QualType(QType, 0);
2775 /// getObjCInterfaceType - Return the unique reference to the type for the
2776 /// specified ObjC interface decl. The list of protocols is optional.
2777 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
2778 if (Decl->TypeForDecl)
2779 return QualType(Decl->TypeForDecl, 0);
2781 // FIXME: redeclarations?
2782 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2783 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2784 Decl->TypeForDecl = T;
2786 return QualType(T, 0);
2789 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2790 /// TypeOfExprType AST's (since expression's are never shared). For example,
2791 /// multiple declarations that refer to "typeof(x)" all contain different
2792 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
2793 /// on canonical type's (which are always unique).
2794 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2795 TypeOfExprType *toe;
2796 if (tofExpr->isTypeDependent()) {
2797 llvm::FoldingSetNodeID ID;
2798 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2800 void *InsertPos = 0;
2801 DependentTypeOfExprType *Canon
2802 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2804 // We already have a "canonical" version of an identical, dependent
2805 // typeof(expr) type. Use that as our canonical type.
2806 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2807 QualType((TypeOfExprType*)Canon, 0));
2809 // Build a new, canonical typeof(expr) type.
2811 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2812 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2816 QualType Canonical = getCanonicalType(tofExpr->getType());
2817 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2819 Types.push_back(toe);
2820 return QualType(toe, 0);
2823 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2824 /// TypeOfType AST's. The only motivation to unique these nodes would be
2825 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2826 /// an issue. This doesn't effect the type checker, since it operates
2827 /// on canonical type's (which are always unique).
2828 QualType ASTContext::getTypeOfType(QualType tofType) const {
2829 QualType Canonical = getCanonicalType(tofType);
2830 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2831 Types.push_back(tot);
2832 return QualType(tot, 0);
2835 /// getDecltypeForExpr - Given an expr, will return the decltype for that
2836 /// expression, according to the rules in C++0x [dcl.type.simple]p4
2837 static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2838 if (e->isTypeDependent())
2839 return Context.DependentTy;
2841 // If e is an id expression or a class member access, decltype(e) is defined
2842 // as the type of the entity named by e.
2843 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2844 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2845 return VD->getType();
2847 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2848 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2849 return FD->getType();
2851 // If e is a function call or an invocation of an overloaded operator,
2852 // (parentheses around e are ignored), decltype(e) is defined as the
2853 // return type of that function.
2854 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2855 return CE->getCallReturnType();
2857 QualType T = e->getType();
2859 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2860 // defined as T&, otherwise decltype(e) is defined as T.
2862 T = Context.getLValueReferenceType(T);
2867 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2868 /// DecltypeType AST's. The only motivation to unique these nodes would be
2869 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2870 /// an issue. This doesn't effect the type checker, since it operates
2871 /// on canonical type's (which are always unique).
2872 QualType ASTContext::getDecltypeType(Expr *e) const {
2875 // C++0x [temp.type]p2:
2876 // If an expression e involves a template parameter, decltype(e) denotes a
2877 // unique dependent type. Two such decltype-specifiers refer to the same
2878 // type only if their expressions are equivalent (14.5.6.1).
2879 if (e->isInstantiationDependent()) {
2880 llvm::FoldingSetNodeID ID;
2881 DependentDecltypeType::Profile(ID, *this, e);
2883 void *InsertPos = 0;
2884 DependentDecltypeType *Canon
2885 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2887 // We already have a "canonical" version of an equivalent, dependent
2888 // decltype type. Use that as our canonical type.
2889 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2890 QualType((DecltypeType*)Canon, 0));
2892 // Build a new, canonical typeof(expr) type.
2893 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2894 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2898 QualType T = getDecltypeForExpr(e, *this);
2899 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2901 Types.push_back(dt);
2902 return QualType(dt, 0);
2905 /// getUnaryTransformationType - We don't unique these, since the memory
2906 /// savings are minimal and these are rare.
2907 QualType ASTContext::getUnaryTransformType(QualType BaseType,
2908 QualType UnderlyingType,
2909 UnaryTransformType::UTTKind Kind)
2911 UnaryTransformType *Ty =
2912 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2914 UnderlyingType->isDependentType() ?
2915 QualType() : UnderlyingType);
2916 Types.push_back(Ty);
2917 return QualType(Ty, 0);
2920 /// getAutoType - We only unique auto types after they've been deduced.
2921 QualType ASTContext::getAutoType(QualType DeducedType) const {
2922 void *InsertPos = 0;
2923 if (!DeducedType.isNull()) {
2924 // Look in the folding set for an existing type.
2925 llvm::FoldingSetNodeID ID;
2926 AutoType::Profile(ID, DeducedType);
2927 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2928 return QualType(AT, 0);
2931 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2932 Types.push_back(AT);
2934 AutoTypes.InsertNode(AT, InsertPos);
2935 return QualType(AT, 0);
2938 /// getAtomicType - Return the uniqued reference to the atomic type for
2939 /// the given value type.
2940 QualType ASTContext::getAtomicType(QualType T) const {
2941 // Unique pointers, to guarantee there is only one pointer of a particular
2943 llvm::FoldingSetNodeID ID;
2944 AtomicType::Profile(ID, T);
2946 void *InsertPos = 0;
2947 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2948 return QualType(AT, 0);
2950 // If the atomic value type isn't canonical, this won't be a canonical type
2951 // either, so fill in the canonical type field.
2953 if (!T.isCanonical()) {
2954 Canonical = getAtomicType(getCanonicalType(T));
2956 // Get the new insert position for the node we care about.
2957 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2958 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2960 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2961 Types.push_back(New);
2962 AtomicTypes.InsertNode(New, InsertPos);
2963 return QualType(New, 0);
2966 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
2967 QualType ASTContext::getAutoDeductType() const {
2968 if (AutoDeductTy.isNull())
2969 AutoDeductTy = getAutoType(QualType());
2970 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2971 return AutoDeductTy;
2974 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2975 QualType ASTContext::getAutoRRefDeductType() const {
2976 if (AutoRRefDeductTy.isNull())
2977 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2978 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2979 return AutoRRefDeductTy;
2982 /// getTagDeclType - Return the unique reference to the type for the
2983 /// specified TagDecl (struct/union/class/enum) decl.
2984 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
2986 // FIXME: What is the design on getTagDeclType when it requires casting
2987 // away const? mutable?
2988 return getTypeDeclType(const_cast<TagDecl*>(Decl));
2991 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2992 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2993 /// needs to agree with the definition in <stddef.h>.
2994 CanQualType ASTContext::getSizeType() const {
2995 return getFromTargetType(Target->getSizeType());
2998 /// getSignedWCharType - Return the type of "signed wchar_t".
2999 /// Used when in C++, as a GCC extension.
3000 QualType ASTContext::getSignedWCharType() const {
3001 // FIXME: derive from "Target" ?
3005 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3006 /// Used when in C++, as a GCC extension.
3007 QualType ASTContext::getUnsignedWCharType() const {
3008 // FIXME: derive from "Target" ?
3009 return UnsignedIntTy;
3012 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
3013 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3014 QualType ASTContext::getPointerDiffType() const {
3015 return getFromTargetType(Target->getPtrDiffType(0));
3018 //===----------------------------------------------------------------------===//
3020 //===----------------------------------------------------------------------===//
3022 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3023 // Push qualifiers into arrays, and then discard any remaining
3025 T = getCanonicalType(T);
3026 T = getVariableArrayDecayedType(T);
3027 const Type *Ty = T.getTypePtr();
3029 if (isa<ArrayType>(Ty)) {
3030 Result = getArrayDecayedType(QualType(Ty,0));
3031 } else if (isa<FunctionType>(Ty)) {
3032 Result = getPointerType(QualType(Ty, 0));
3034 Result = QualType(Ty, 0);
3037 return CanQualType::CreateUnsafe(Result);
3040 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3041 Qualifiers &quals) {
3042 SplitQualType splitType = type.getSplitUnqualifiedType();
3044 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3045 // the unqualified desugared type and then drops it on the floor.
3046 // We then have to strip that sugar back off with
3047 // getUnqualifiedDesugaredType(), which is silly.
3048 const ArrayType *AT =
3049 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3051 // If we don't have an array, just use the results in splitType.
3053 quals = splitType.second;
3054 return QualType(splitType.first, 0);
3057 // Otherwise, recurse on the array's element type.
3058 QualType elementType = AT->getElementType();
3059 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3061 // If that didn't change the element type, AT has no qualifiers, so we
3062 // can just use the results in splitType.
3063 if (elementType == unqualElementType) {
3064 assert(quals.empty()); // from the recursive call
3065 quals = splitType.second;
3066 return QualType(splitType.first, 0);
3069 // Otherwise, add in the qualifiers from the outermost type, then
3070 // build the type back up.
3071 quals.addConsistentQualifiers(splitType.second);
3073 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3074 return getConstantArrayType(unqualElementType, CAT->getSize(),
3075 CAT->getSizeModifier(), 0);
3078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3079 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3082 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3083 return getVariableArrayType(unqualElementType,
3085 VAT->getSizeModifier(),
3086 VAT->getIndexTypeCVRQualifiers(),
3087 VAT->getBracketsRange());
3090 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3091 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3092 DSAT->getSizeModifier(), 0,
3096 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3097 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3098 /// they point to and return true. If T1 and T2 aren't pointer types
3099 /// or pointer-to-member types, or if they are not similar at this
3100 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3101 /// qualifiers on T1 and T2 are ignored. This function will typically
3102 /// be called in a loop that successively "unwraps" pointer and
3103 /// pointer-to-member types to compare them at each level.
3104 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3105 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3106 *T2PtrType = T2->getAs<PointerType>();
3107 if (T1PtrType && T2PtrType) {
3108 T1 = T1PtrType->getPointeeType();
3109 T2 = T2PtrType->getPointeeType();
3113 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3114 *T2MPType = T2->getAs<MemberPointerType>();
3115 if (T1MPType && T2MPType &&
3116 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3117 QualType(T2MPType->getClass(), 0))) {
3118 T1 = T1MPType->getPointeeType();
3119 T2 = T2MPType->getPointeeType();
3123 if (getLangOptions().ObjC1) {
3124 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3125 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3126 if (T1OPType && T2OPType) {
3127 T1 = T1OPType->getPointeeType();
3128 T2 = T2OPType->getPointeeType();
3133 // FIXME: Block pointers, too?
3139 ASTContext::getNameForTemplate(TemplateName Name,
3140 SourceLocation NameLoc) const {
3141 switch (Name.getKind()) {
3142 case TemplateName::QualifiedTemplate:
3143 case TemplateName::Template:
3144 // DNInfo work in progress: CHECKME: what about DNLoc?
3145 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3148 case TemplateName::OverloadedTemplate: {
3149 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3150 // DNInfo work in progress: CHECKME: what about DNLoc?
3151 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3154 case TemplateName::DependentTemplate: {
3155 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3156 DeclarationName DName;
3157 if (DTN->isIdentifier()) {
3158 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3159 return DeclarationNameInfo(DName, NameLoc);
3161 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3162 // DNInfo work in progress: FIXME: source locations?
3163 DeclarationNameLoc DNLoc;
3164 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3165 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3166 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3170 case TemplateName::SubstTemplateTemplateParm: {
3171 SubstTemplateTemplateParmStorage *subst
3172 = Name.getAsSubstTemplateTemplateParm();
3173 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3177 case TemplateName::SubstTemplateTemplateParmPack: {
3178 SubstTemplateTemplateParmPackStorage *subst
3179 = Name.getAsSubstTemplateTemplateParmPack();
3180 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3185 llvm_unreachable("bad template name kind!");
3188 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3189 switch (Name.getKind()) {
3190 case TemplateName::QualifiedTemplate:
3191 case TemplateName::Template: {
3192 TemplateDecl *Template = Name.getAsTemplateDecl();
3193 if (TemplateTemplateParmDecl *TTP
3194 = dyn_cast<TemplateTemplateParmDecl>(Template))
3195 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3197 // The canonical template name is the canonical template declaration.
3198 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3201 case TemplateName::OverloadedTemplate:
3202 llvm_unreachable("cannot canonicalize overloaded template");
3204 case TemplateName::DependentTemplate: {
3205 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3206 assert(DTN && "Non-dependent template names must refer to template decls.");
3207 return DTN->CanonicalTemplateName;
3210 case TemplateName::SubstTemplateTemplateParm: {
3211 SubstTemplateTemplateParmStorage *subst
3212 = Name.getAsSubstTemplateTemplateParm();
3213 return getCanonicalTemplateName(subst->getReplacement());
3216 case TemplateName::SubstTemplateTemplateParmPack: {
3217 SubstTemplateTemplateParmPackStorage *subst
3218 = Name.getAsSubstTemplateTemplateParmPack();
3219 TemplateTemplateParmDecl *canonParameter
3220 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3221 TemplateArgument canonArgPack
3222 = getCanonicalTemplateArgument(subst->getArgumentPack());
3223 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3227 llvm_unreachable("bad template name!");
3230 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3231 X = getCanonicalTemplateName(X);
3232 Y = getCanonicalTemplateName(Y);
3233 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3237 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3238 switch (Arg.getKind()) {
3239 case TemplateArgument::Null:
3242 case TemplateArgument::Expression:
3245 case TemplateArgument::Declaration:
3246 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3248 case TemplateArgument::Template:
3249 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3251 case TemplateArgument::TemplateExpansion:
3252 return TemplateArgument(getCanonicalTemplateName(
3253 Arg.getAsTemplateOrTemplatePattern()),
3254 Arg.getNumTemplateExpansions());
3256 case TemplateArgument::Integral:
3257 return TemplateArgument(*Arg.getAsIntegral(),
3258 getCanonicalType(Arg.getIntegralType()));
3260 case TemplateArgument::Type:
3261 return TemplateArgument(getCanonicalType(Arg.getAsType()));
3263 case TemplateArgument::Pack: {
3264 if (Arg.pack_size() == 0)
3267 TemplateArgument *CanonArgs
3268 = new (*this) TemplateArgument[Arg.pack_size()];
3270 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3271 AEnd = Arg.pack_end();
3272 A != AEnd; (void)++A, ++Idx)
3273 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3275 return TemplateArgument(CanonArgs, Arg.pack_size());
3279 // Silence GCC warning
3280 llvm_unreachable("Unhandled template argument kind");
3283 NestedNameSpecifier *
3284 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3288 switch (NNS->getKind()) {
3289 case NestedNameSpecifier::Identifier:
3290 // Canonicalize the prefix but keep the identifier the same.
3291 return NestedNameSpecifier::Create(*this,
3292 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3293 NNS->getAsIdentifier());
3295 case NestedNameSpecifier::Namespace:
3296 // A namespace is canonical; build a nested-name-specifier with
3297 // this namespace and no prefix.
3298 return NestedNameSpecifier::Create(*this, 0,
3299 NNS->getAsNamespace()->getOriginalNamespace());
3301 case NestedNameSpecifier::NamespaceAlias:
3302 // A namespace is canonical; build a nested-name-specifier with
3303 // this namespace and no prefix.
3304 return NestedNameSpecifier::Create(*this, 0,
3305 NNS->getAsNamespaceAlias()->getNamespace()
3306 ->getOriginalNamespace());
3308 case NestedNameSpecifier::TypeSpec:
3309 case NestedNameSpecifier::TypeSpecWithTemplate: {
3310 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3312 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3313 // break it apart into its prefix and identifier, then reconsititute those
3314 // as the canonical nested-name-specifier. This is required to canonicalize
3315 // a dependent nested-name-specifier involving typedefs of dependent-name
3317 // typedef typename T::type T1;
3318 // typedef typename T1::type T2;
3319 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3320 NestedNameSpecifier *Prefix
3321 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3322 return NestedNameSpecifier::Create(*this, Prefix,
3323 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3326 // Do the same thing as above, but with dependent-named specializations.
3327 if (const DependentTemplateSpecializationType *DTST
3328 = T->getAs<DependentTemplateSpecializationType>()) {
3329 NestedNameSpecifier *Prefix
3330 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3332 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3333 Prefix, DTST->getIdentifier(),
3336 T = getCanonicalType(T);
3339 return NestedNameSpecifier::Create(*this, 0, false,
3340 const_cast<Type*>(T.getTypePtr()));
3343 case NestedNameSpecifier::Global:
3344 // The global specifier is canonical and unique.
3348 // Required to silence a GCC warning
3353 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3354 // Handle the non-qualified case efficiently.
3355 if (!T.hasLocalQualifiers()) {
3356 // Handle the common positive case fast.
3357 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3361 // Handle the common negative case fast.
3362 if (!isa<ArrayType>(T.getCanonicalType()))
3365 // Apply any qualifiers from the array type to the element type. This
3366 // implements C99 6.7.3p8: "If the specification of an array type includes
3367 // any type qualifiers, the element type is so qualified, not the array type."
3369 // If we get here, we either have type qualifiers on the type, or we have
3370 // sugar such as a typedef in the way. If we have type qualifiers on the type
3371 // we must propagate them down into the element type.
3373 SplitQualType split = T.getSplitDesugaredType();
3374 Qualifiers qs = split.second;
3376 // If we have a simple case, just return now.
3377 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3378 if (ATy == 0 || qs.empty())
3381 // Otherwise, we have an array and we have qualifiers on it. Push the
3382 // qualifiers into the array element type and return a new array type.
3383 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3385 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3386 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3387 CAT->getSizeModifier(),
3388 CAT->getIndexTypeCVRQualifiers()));
3389 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3390 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3391 IAT->getSizeModifier(),
3392 IAT->getIndexTypeCVRQualifiers()));
3394 if (const DependentSizedArrayType *DSAT
3395 = dyn_cast<DependentSizedArrayType>(ATy))
3396 return cast<ArrayType>(
3397 getDependentSizedArrayType(NewEltTy,
3398 DSAT->getSizeExpr(),
3399 DSAT->getSizeModifier(),
3400 DSAT->getIndexTypeCVRQualifiers(),
3401 DSAT->getBracketsRange()));
3403 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3404 return cast<ArrayType>(getVariableArrayType(NewEltTy,
3406 VAT->getSizeModifier(),
3407 VAT->getIndexTypeCVRQualifiers(),
3408 VAT->getBracketsRange()));
3411 QualType ASTContext::getAdjustedParameterType(QualType T) {
3413 // A declaration of a parameter as "array of type" shall be
3414 // adjusted to "qualified pointer to type", where the type
3415 // qualifiers (if any) are those specified within the [ and ] of
3416 // the array type derivation.
3417 if (T->isArrayType())
3418 return getArrayDecayedType(T);
3421 // A declaration of a parameter as "function returning type"
3422 // shall be adjusted to "pointer to function returning type", as
3424 if (T->isFunctionType())
3425 return getPointerType(T);
3430 QualType ASTContext::getSignatureParameterType(QualType T) {
3431 T = getVariableArrayDecayedType(T);
3432 T = getAdjustedParameterType(T);
3433 return T.getUnqualifiedType();
3436 /// getArrayDecayedType - Return the properly qualified result of decaying the
3437 /// specified array type to a pointer. This operation is non-trivial when
3438 /// handling typedefs etc. The canonical type of "T" must be an array type,
3439 /// this returns a pointer to a properly qualified element of the array.
3441 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3442 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3443 // Get the element type with 'getAsArrayType' so that we don't lose any
3444 // typedefs in the element type of the array. This also handles propagation
3445 // of type qualifiers from the array type into the element type if present
3447 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3448 assert(PrettyArrayType && "Not an array type!");
3450 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3452 // int x[restrict 4] -> int *restrict
3453 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3456 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3457 return getBaseElementType(array->getElementType());
3460 QualType ASTContext::getBaseElementType(QualType type) const {
3463 SplitQualType split = type.getSplitDesugaredType();
3464 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3467 type = array->getElementType();
3468 qs.addConsistentQualifiers(split.second);
3471 return getQualifiedType(type, qs);
3474 /// getConstantArrayElementCount - Returns number of constant array elements.
3476 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3477 uint64_t ElementCount = 1;
3479 ElementCount *= CA->getSize().getZExtValue();
3480 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3482 return ElementCount;
3485 /// getFloatingRank - Return a relative rank for floating point types.
3486 /// This routine will assert if passed a built-in type that isn't a float.
3487 static FloatingRank getFloatingRank(QualType T) {
3488 if (const ComplexType *CT = T->getAs<ComplexType>())
3489 return getFloatingRank(CT->getElementType());
3491 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3492 switch (T->getAs<BuiltinType>()->getKind()) {
3493 default: llvm_unreachable("getFloatingRank(): not a floating type");
3494 case BuiltinType::Half: return HalfRank;
3495 case BuiltinType::Float: return FloatRank;
3496 case BuiltinType::Double: return DoubleRank;
3497 case BuiltinType::LongDouble: return LongDoubleRank;
3501 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3502 /// point or a complex type (based on typeDomain/typeSize).
3503 /// 'typeDomain' is a real floating point or complex type.
3504 /// 'typeSize' is a real floating point or complex type.
3505 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3506 QualType Domain) const {
3507 FloatingRank EltRank = getFloatingRank(Size);
3508 if (Domain->isComplexType()) {
3510 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
3511 case FloatRank: return FloatComplexTy;
3512 case DoubleRank: return DoubleComplexTy;
3513 case LongDoubleRank: return LongDoubleComplexTy;
3517 assert(Domain->isRealFloatingType() && "Unknown domain!");
3519 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
3520 case FloatRank: return FloatTy;
3521 case DoubleRank: return DoubleTy;
3522 case LongDoubleRank: return LongDoubleTy;
3526 /// getFloatingTypeOrder - Compare the rank of the two specified floating
3527 /// point types, ignoring the domain of the type (i.e. 'double' ==
3528 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
3529 /// LHS < RHS, return -1.
3530 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3531 FloatingRank LHSR = getFloatingRank(LHS);
3532 FloatingRank RHSR = getFloatingRank(RHS);
3541 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3542 /// routine will assert if passed a built-in type that isn't an integer or enum,
3543 /// or if it is not canonicalized.
3544 unsigned ASTContext::getIntegerRank(const Type *T) const {
3545 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3546 if (const EnumType* ET = dyn_cast<EnumType>(T))
3547 T = ET->getDecl()->getPromotionType().getTypePtr();
3549 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3550 T->isSpecificBuiltinType(BuiltinType::WChar_U))
3551 T = getFromTargetType(Target->getWCharType()).getTypePtr();
3553 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3554 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
3556 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3557 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
3559 switch (cast<BuiltinType>(T)->getKind()) {
3560 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3561 case BuiltinType::Bool:
3562 return 1 + (getIntWidth(BoolTy) << 3);
3563 case BuiltinType::Char_S:
3564 case BuiltinType::Char_U:
3565 case BuiltinType::SChar:
3566 case BuiltinType::UChar:
3567 return 2 + (getIntWidth(CharTy) << 3);
3568 case BuiltinType::Short:
3569 case BuiltinType::UShort:
3570 return 3 + (getIntWidth(ShortTy) << 3);
3571 case BuiltinType::Int:
3572 case BuiltinType::UInt:
3573 return 4 + (getIntWidth(IntTy) << 3);
3574 case BuiltinType::Long:
3575 case BuiltinType::ULong:
3576 return 5 + (getIntWidth(LongTy) << 3);
3577 case BuiltinType::LongLong:
3578 case BuiltinType::ULongLong:
3579 return 6 + (getIntWidth(LongLongTy) << 3);
3580 case BuiltinType::Int128:
3581 case BuiltinType::UInt128:
3582 return 7 + (getIntWidth(Int128Ty) << 3);
3586 /// \brief Whether this is a promotable bitfield reference according
3587 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3589 /// \returns the type this bit-field will promote to, or NULL if no
3590 /// promotion occurs.
3591 QualType ASTContext::isPromotableBitField(Expr *E) const {
3592 if (E->isTypeDependent() || E->isValueDependent())
3595 FieldDecl *Field = E->getBitField();
3599 QualType FT = Field->getType();
3601 uint64_t BitWidth = Field->getBitWidthValue(*this);
3602 uint64_t IntSize = getTypeSize(IntTy);
3603 // GCC extension compatibility: if the bit-field size is less than or equal
3604 // to the size of int, it gets promoted no matter what its type is.
3605 // For instance, unsigned long bf : 4 gets promoted to signed int.
3606 if (BitWidth < IntSize)
3609 if (BitWidth == IntSize)
3610 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3612 // Types bigger than int are not subject to promotions, and therefore act
3613 // like the base type.
3614 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3619 /// getPromotedIntegerType - Returns the type that Promotable will
3620 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3622 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3623 assert(!Promotable.isNull());
3624 assert(Promotable->isPromotableIntegerType());
3625 if (const EnumType *ET = Promotable->getAs<EnumType>())
3626 return ET->getDecl()->getPromotionType();
3627 if (Promotable->isSignedIntegerType())
3629 uint64_t PromotableSize = getTypeSize(Promotable);
3630 uint64_t IntSize = getTypeSize(IntTy);
3631 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3632 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3635 /// \brief Recurses in pointer/array types until it finds an objc retainable
3636 /// type and returns its ownership.
3637 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3638 while (!T.isNull()) {
3639 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3640 return T.getObjCLifetime();
3641 if (T->isArrayType())
3642 T = getBaseElementType(T);
3643 else if (const PointerType *PT = T->getAs<PointerType>())
3644 T = PT->getPointeeType();
3645 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3646 T = RT->getPointeeType();
3651 return Qualifiers::OCL_None;
3654 /// getIntegerTypeOrder - Returns the highest ranked integer type:
3655 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
3656 /// LHS < RHS, return -1.
3657 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3658 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3659 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3660 if (LHSC == RHSC) return 0;
3662 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3663 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3665 unsigned LHSRank = getIntegerRank(LHSC);
3666 unsigned RHSRank = getIntegerRank(RHSC);
3668 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3669 if (LHSRank == RHSRank) return 0;
3670 return LHSRank > RHSRank ? 1 : -1;
3673 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3675 // If the unsigned [LHS] type is larger, return it.
3676 if (LHSRank >= RHSRank)
3679 // If the signed type can represent all values of the unsigned type, it
3680 // wins. Because we are dealing with 2's complement and types that are
3681 // powers of two larger than each other, this is always safe.
3685 // If the unsigned [RHS] type is larger, return it.
3686 if (RHSRank >= LHSRank)
3689 // If the signed type can represent all values of the unsigned type, it
3690 // wins. Because we are dealing with 2's complement and types that are
3691 // powers of two larger than each other, this is always safe.
3696 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3697 DeclContext *DC, IdentifierInfo *Id) {
3699 if (Ctx.getLangOptions().CPlusPlus)
3700 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3702 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3705 // getCFConstantStringType - Return the type used for constant CFStrings.
3706 QualType ASTContext::getCFConstantStringType() const {
3707 if (!CFConstantStringTypeDecl) {
3708 CFConstantStringTypeDecl =
3709 CreateRecordDecl(*this, TTK_Struct, TUDecl,
3710 &Idents.get("NSConstantString"));
3711 CFConstantStringTypeDecl->startDefinition();
3713 QualType FieldTypes[4];
3716 FieldTypes[0] = getPointerType(IntTy.withConst());
3718 FieldTypes[1] = IntTy;
3720 FieldTypes[2] = getPointerType(CharTy.withConst());
3722 FieldTypes[3] = LongTy;
3725 for (unsigned i = 0; i < 4; ++i) {
3726 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3728 SourceLocation(), 0,
3729 FieldTypes[i], /*TInfo=*/0,
3733 Field->setAccess(AS_public);
3734 CFConstantStringTypeDecl->addDecl(Field);
3737 CFConstantStringTypeDecl->completeDefinition();
3740 return getTagDeclType(CFConstantStringTypeDecl);
3743 void ASTContext::setCFConstantStringType(QualType T) {
3744 const RecordType *Rec = T->getAs<RecordType>();
3745 assert(Rec && "Invalid CFConstantStringType");
3746 CFConstantStringTypeDecl = Rec->getDecl();
3749 QualType ASTContext::getBlockDescriptorType() const {
3750 if (BlockDescriptorType)
3751 return getTagDeclType(BlockDescriptorType);
3754 // FIXME: Needs the FlagAppleBlock bit.
3755 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3756 &Idents.get("__block_descriptor"));
3757 T->startDefinition();
3759 QualType FieldTypes[] = {
3764 const char *FieldNames[] = {
3769 for (size_t i = 0; i < 2; ++i) {
3770 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3772 &Idents.get(FieldNames[i]),
3773 FieldTypes[i], /*TInfo=*/0,
3777 Field->setAccess(AS_public);
3781 T->completeDefinition();
3783 BlockDescriptorType = T;
3785 return getTagDeclType(BlockDescriptorType);
3788 QualType ASTContext::getBlockDescriptorExtendedType() const {
3789 if (BlockDescriptorExtendedType)
3790 return getTagDeclType(BlockDescriptorExtendedType);
3793 // FIXME: Needs the FlagAppleBlock bit.
3794 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3795 &Idents.get("__block_descriptor_withcopydispose"));
3796 T->startDefinition();
3798 QualType FieldTypes[] = {
3801 getPointerType(VoidPtrTy),
3802 getPointerType(VoidPtrTy)
3805 const char *FieldNames[] = {
3812 for (size_t i = 0; i < 4; ++i) {
3813 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3815 &Idents.get(FieldNames[i]),
3816 FieldTypes[i], /*TInfo=*/0,
3820 Field->setAccess(AS_public);
3824 T->completeDefinition();
3826 BlockDescriptorExtendedType = T;
3828 return getTagDeclType(BlockDescriptorExtendedType);
3831 bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3832 if (Ty->isObjCRetainableType())
3834 if (getLangOptions().CPlusPlus) {
3835 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3836 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3837 return RD->hasConstCopyConstructor();
3845 ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
3846 // type = struct __Block_byref_1_X {
3848 // struct __Block_byref_1_X *__forwarding;
3849 // unsigned int __flags;
3850 // unsigned int __size;
3851 // void *__copy_helper; // as needed
3852 // void *__destroy_help // as needed
3856 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3859 llvm::SmallString<36> Name;
3860 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3861 ++UniqueBlockByRefTypeID << '_' << DeclName;
3863 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3864 T->startDefinition();
3865 QualType Int32Ty = IntTy;
3866 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3867 QualType FieldTypes[] = {
3868 getPointerType(VoidPtrTy),
3869 getPointerType(getTagDeclType(T)),
3872 getPointerType(VoidPtrTy),
3873 getPointerType(VoidPtrTy),
3877 StringRef FieldNames[] = {
3887 for (size_t i = 0; i < 7; ++i) {
3888 if (!HasCopyAndDispose && i >=4 && i <= 5)
3890 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3892 &Idents.get(FieldNames[i]),
3893 FieldTypes[i], /*TInfo=*/0,
3894 /*BitWidth=*/0, /*Mutable=*/false,
3896 Field->setAccess(AS_public);
3900 T->completeDefinition();
3902 return getPointerType(getTagDeclType(T));
3905 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3906 if (!ObjCInstanceTypeDecl)
3907 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3908 getTranslationUnitDecl(),
3911 &Idents.get("instancetype"),
3912 getTrivialTypeSourceInfo(getObjCIdType()));
3913 return ObjCInstanceTypeDecl;
3916 // This returns true if a type has been typedefed to BOOL:
3917 // typedef <type> BOOL;
3918 static bool isTypeTypedefedAsBOOL(QualType T) {
3919 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3920 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3921 return II->isStr("BOOL");
3926 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
3928 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
3929 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3930 return CharUnits::Zero();
3932 CharUnits sz = getTypeSizeInChars(type);
3934 // Make all integer and enum types at least as large as an int
3935 if (sz.isPositive() && type->isIntegralOrEnumerationType())
3936 sz = std::max(sz, getTypeSizeInChars(IntTy));
3937 // Treat arrays as pointers, since that's how they're passed in.
3938 else if (type->isArrayType())
3939 sz = getTypeSizeInChars(VoidPtrTy);
3944 std::string charUnitsToString(const CharUnits &CU) {
3945 return llvm::itostr(CU.getQuantity());
3948 /// getObjCEncodingForBlock - Return the encoded type for this block
3950 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3953 const BlockDecl *Decl = Expr->getBlockDecl();
3955 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3956 // Encode result type.
3957 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3958 // Compute size of all parameters.
3959 // Start with computing size of a pointer in number of bytes.
3960 // FIXME: There might(should) be a better way of doing this computation!
3962 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3963 CharUnits ParmOffset = PtrSize;
3964 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3965 E = Decl->param_end(); PI != E; ++PI) {
3966 QualType PType = (*PI)->getType();
3967 CharUnits sz = getObjCEncodingTypeSize(PType);
3968 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3971 // Size of the argument frame
3972 S += charUnitsToString(ParmOffset);
3973 // Block pointer and offset.
3977 ParmOffset = PtrSize;
3978 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3979 Decl->param_end(); PI != E; ++PI) {
3980 ParmVarDecl *PVDecl = *PI;
3981 QualType PType = PVDecl->getOriginalType();
3982 if (const ArrayType *AT =
3983 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3984 // Use array's original type only if it has known number of
3986 if (!isa<ConstantArrayType>(AT))
3987 PType = PVDecl->getType();
3988 } else if (PType->isFunctionType())
3989 PType = PVDecl->getType();
3990 getObjCEncodingForType(PType, S);
3991 S += charUnitsToString(ParmOffset);
3992 ParmOffset += getObjCEncodingTypeSize(PType);
3998 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4000 // Encode result type.
4001 getObjCEncodingForType(Decl->getResultType(), S);
4002 CharUnits ParmOffset;
4003 // Compute size of all parameters.
4004 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4005 E = Decl->param_end(); PI != E; ++PI) {
4006 QualType PType = (*PI)->getType();
4007 CharUnits sz = getObjCEncodingTypeSize(PType);
4011 assert (sz.isPositive() &&
4012 "getObjCEncodingForFunctionDecl - Incomplete param type");
4015 S += charUnitsToString(ParmOffset);
4016 ParmOffset = CharUnits::Zero();
4019 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4020 E = Decl->param_end(); PI != E; ++PI) {
4021 ParmVarDecl *PVDecl = *PI;
4022 QualType PType = PVDecl->getOriginalType();
4023 if (const ArrayType *AT =
4024 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4025 // Use array's original type only if it has known number of
4027 if (!isa<ConstantArrayType>(AT))
4028 PType = PVDecl->getType();
4029 } else if (PType->isFunctionType())
4030 PType = PVDecl->getType();
4031 getObjCEncodingForType(PType, S);
4032 S += charUnitsToString(ParmOffset);
4033 ParmOffset += getObjCEncodingTypeSize(PType);
4039 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4041 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4042 std::string& S) const {
4043 // FIXME: This is not very efficient.
4044 // Encode type qualifer, 'in', 'inout', etc. for the return type.
4045 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
4046 // Encode result type.
4047 getObjCEncodingForType(Decl->getResultType(), S);
4048 // Compute size of all parameters.
4049 // Start with computing size of a pointer in number of bytes.
4050 // FIXME: There might(should) be a better way of doing this computation!
4052 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4053 // The first two arguments (self and _cmd) are pointers; account for
4055 CharUnits ParmOffset = 2 * PtrSize;
4056 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4057 E = Decl->sel_param_end(); PI != E; ++PI) {
4058 QualType PType = (*PI)->getType();
4059 CharUnits sz = getObjCEncodingTypeSize(PType);
4063 assert (sz.isPositive() &&
4064 "getObjCEncodingForMethodDecl - Incomplete param type");
4067 S += charUnitsToString(ParmOffset);
4069 S += charUnitsToString(PtrSize);
4072 ParmOffset = 2 * PtrSize;
4073 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4074 E = Decl->sel_param_end(); PI != E; ++PI) {
4075 const ParmVarDecl *PVDecl = *PI;
4076 QualType PType = PVDecl->getOriginalType();
4077 if (const ArrayType *AT =
4078 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4079 // Use array's original type only if it has known number of
4081 if (!isa<ConstantArrayType>(AT))
4082 PType = PVDecl->getType();
4083 } else if (PType->isFunctionType())
4084 PType = PVDecl->getType();
4085 // Process argument qualifiers for user supplied arguments; such as,
4086 // 'in', 'inout', etc.
4087 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
4088 getObjCEncodingForType(PType, S);
4089 S += charUnitsToString(ParmOffset);
4090 ParmOffset += getObjCEncodingTypeSize(PType);
4096 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4097 /// property declaration. If non-NULL, Container must be either an
4098 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4099 /// NULL when getting encodings for protocol properties.
4100 /// Property attributes are stored as a comma-delimited C string. The simple
4101 /// attributes readonly and bycopy are encoded as single characters. The
4102 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4103 /// encoded as single characters, followed by an identifier. Property types
4104 /// are also encoded as a parametrized attribute. The characters used to encode
4105 /// these attributes are defined by the following enumeration:
4107 /// enum PropertyAttributes {
4108 /// kPropertyReadOnly = 'R', // property is read-only.
4109 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4110 /// kPropertyByref = '&', // property is a reference to the value last assigned
4111 /// kPropertyDynamic = 'D', // property is dynamic
4112 /// kPropertyGetter = 'G', // followed by getter selector name
4113 /// kPropertySetter = 'S', // followed by setter selector name
4114 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4115 /// kPropertyType = 't' // followed by old-style type encoding.
4116 /// kPropertyWeak = 'W' // 'weak' property
4117 /// kPropertyStrong = 'P' // property GC'able
4118 /// kPropertyNonAtomic = 'N' // property non-atomic
4121 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4122 const Decl *Container,
4123 std::string& S) const {
4124 // Collect information from the property implementation decl(s).
4125 bool Dynamic = false;
4126 ObjCPropertyImplDecl *SynthesizePID = 0;
4128 // FIXME: Duplicated code due to poor abstraction.
4130 if (const ObjCCategoryImplDecl *CID =
4131 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4132 for (ObjCCategoryImplDecl::propimpl_iterator
4133 i = CID->propimpl_begin(), e = CID->propimpl_end();
4135 ObjCPropertyImplDecl *PID = *i;
4136 if (PID->getPropertyDecl() == PD) {
4137 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4140 SynthesizePID = PID;
4145 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4146 for (ObjCCategoryImplDecl::propimpl_iterator
4147 i = OID->propimpl_begin(), e = OID->propimpl_end();
4149 ObjCPropertyImplDecl *PID = *i;
4150 if (PID->getPropertyDecl() == PD) {
4151 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4154 SynthesizePID = PID;
4161 // FIXME: This is not very efficient.
4164 // Encode result type.
4165 // GCC has some special rules regarding encoding of properties which
4166 // closely resembles encoding of ivars.
4167 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4168 true /* outermost type */,
4169 true /* encoding for property */);
4171 if (PD->isReadOnly()) {
4174 switch (PD->getSetterKind()) {
4175 case ObjCPropertyDecl::Assign: break;
4176 case ObjCPropertyDecl::Copy: S += ",C"; break;
4177 case ObjCPropertyDecl::Retain: S += ",&"; break;
4178 case ObjCPropertyDecl::Weak: S += ",W"; break;
4182 // It really isn't clear at all what this means, since properties
4183 // are "dynamic by default".
4187 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4190 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4192 S += PD->getGetterName().getAsString();
4195 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4197 S += PD->getSetterName().getAsString();
4200 if (SynthesizePID) {
4201 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4203 S += OID->getNameAsString();
4206 // FIXME: OBJCGC: weak & strong
4209 /// getLegacyIntegralTypeEncoding -
4210 /// Another legacy compatibility encoding: 32-bit longs are encoded as
4211 /// 'l' or 'L' , but not always. For typedefs, we need to use
4212 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
4214 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4215 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4216 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4217 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4218 PointeeTy = UnsignedIntTy;
4220 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4226 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4227 const FieldDecl *Field) const {
4228 // We follow the behavior of gcc, expanding structures which are
4229 // directly pointed to, and expanding embedded structures. Note that
4230 // these rules are sufficient to prevent recursive encoding of the
4232 getObjCEncodingForTypeImpl(T, S, true, true, Field,
4233 true /* outermost type */);
4236 static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4237 switch (T->getAs<BuiltinType>()->getKind()) {
4238 default: llvm_unreachable("Unhandled builtin type kind");
4239 case BuiltinType::Void: return 'v';
4240 case BuiltinType::Bool: return 'B';
4241 case BuiltinType::Char_U:
4242 case BuiltinType::UChar: return 'C';
4243 case BuiltinType::UShort: return 'S';
4244 case BuiltinType::UInt: return 'I';
4245 case BuiltinType::ULong:
4246 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4247 case BuiltinType::UInt128: return 'T';
4248 case BuiltinType::ULongLong: return 'Q';
4249 case BuiltinType::Char_S:
4250 case BuiltinType::SChar: return 'c';
4251 case BuiltinType::Short: return 's';
4252 case BuiltinType::WChar_S:
4253 case BuiltinType::WChar_U:
4254 case BuiltinType::Int: return 'i';
4255 case BuiltinType::Long:
4256 return C->getIntWidth(T) == 32 ? 'l' : 'q';
4257 case BuiltinType::LongLong: return 'q';
4258 case BuiltinType::Int128: return 't';
4259 case BuiltinType::Float: return 'f';
4260 case BuiltinType::Double: return 'd';
4261 case BuiltinType::LongDouble: return 'D';
4265 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4266 EnumDecl *Enum = ET->getDecl();
4268 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4269 if (!Enum->isFixed())
4272 // The encoding of a fixed enum type matches its fixed underlying type.
4273 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4276 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4277 QualType T, const FieldDecl *FD) {
4278 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4280 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4281 // The GNU runtime requires more information; bitfields are encoded as b,
4282 // then the offset (in bits) of the first element, then the type of the
4283 // bitfield, then the size in bits. For example, in this structure:
4290 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4291 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4292 // information is not especially sensible, but we're stuck with it for
4293 // compatibility with GCC, although providing it breaks anything that
4294 // actually uses runtime introspection and wants to work on both runtimes...
4295 if (!Ctx->getLangOptions().NeXTRuntime) {
4296 const RecordDecl *RD = FD->getParent();
4297 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4298 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4299 if (const EnumType *ET = T->getAs<EnumType>())
4300 S += ObjCEncodingForEnumType(Ctx, ET);
4302 S += ObjCEncodingForPrimitiveKind(Ctx, T);
4304 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4307 // FIXME: Use SmallString for accumulating string.
4308 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4309 bool ExpandPointedToStructures,
4310 bool ExpandStructures,
4311 const FieldDecl *FD,
4313 bool EncodingProperty,
4314 bool StructField) const {
4315 if (T->getAs<BuiltinType>()) {
4316 if (FD && FD->isBitField())
4317 return EncodeBitField(this, S, T, FD);
4318 S += ObjCEncodingForPrimitiveKind(this, T);
4322 if (const ComplexType *CT = T->getAs<ComplexType>()) {
4324 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4329 // encoding for pointer or r3eference types.
4331 if (const PointerType *PT = T->getAs<PointerType>()) {
4332 if (PT->isObjCSelType()) {
4336 PointeeTy = PT->getPointeeType();
4338 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4339 PointeeTy = RT->getPointeeType();
4340 if (!PointeeTy.isNull()) {
4341 bool isReadOnly = false;
4342 // For historical/compatibility reasons, the read-only qualifier of the
4343 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4344 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4345 // Also, do not emit the 'r' for anything but the outermost type!
4346 if (isa<TypedefType>(T.getTypePtr())) {
4347 if (OutermostType && T.isConstQualified()) {
4351 } else if (OutermostType) {
4352 QualType P = PointeeTy;
4353 while (P->getAs<PointerType>())
4354 P = P->getAs<PointerType>()->getPointeeType();
4355 if (P.isConstQualified()) {
4361 // Another legacy compatibility encoding. Some ObjC qualifier and type
4362 // combinations need to be rearranged.
4363 // Rewrite "in const" from "nr" to "rn"
4364 if (StringRef(S).endswith("nr"))
4365 S.replace(S.end()-2, S.end(), "rn");
4368 if (PointeeTy->isCharType()) {
4369 // char pointer types should be encoded as '*' unless it is a
4370 // type that has been typedef'd to 'BOOL'.
4371 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4375 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4376 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4377 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4381 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4382 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4389 getLegacyIntegralTypeEncoding(PointeeTy);
4391 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4396 if (const ArrayType *AT =
4397 // Ignore type qualifiers etc.
4398 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4399 if (isa<IncompleteArrayType>(AT) && !StructField) {
4400 // Incomplete arrays are encoded as a pointer to the array element.
4403 getObjCEncodingForTypeImpl(AT->getElementType(), S,
4404 false, ExpandStructures, FD);
4408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4409 if (getTypeSize(CAT->getElementType()) == 0)
4412 S += llvm::utostr(CAT->getSize().getZExtValue());
4414 //Variable length arrays are encoded as a regular array with 0 elements.
4415 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4416 "Unknown array type!");
4420 getObjCEncodingForTypeImpl(AT->getElementType(), S,
4421 false, ExpandStructures, FD);
4427 if (T->getAs<FunctionType>()) {
4432 if (const RecordType *RTy = T->getAs<RecordType>()) {
4433 RecordDecl *RDecl = RTy->getDecl();
4434 S += RDecl->isUnion() ? '(' : '{';
4435 // Anonymous structures print as '?'
4436 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4438 if (ClassTemplateSpecializationDecl *Spec
4439 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4440 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4441 std::string TemplateArgsStr
4442 = TemplateSpecializationType::PrintTemplateArgumentList(
4443 TemplateArgs.data(),
4444 TemplateArgs.size(),
4445 (*this).getPrintingPolicy());
4447 S += TemplateArgsStr;
4452 if (ExpandStructures) {
4454 if (!RDecl->isUnion()) {
4455 getObjCEncodingForStructureImpl(RDecl, S, FD);
4457 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4458 FieldEnd = RDecl->field_end();
4459 Field != FieldEnd; ++Field) {
4462 S += Field->getNameAsString();
4466 // Special case bit-fields.
4467 if (Field->isBitField()) {
4468 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4471 QualType qt = Field->getType();
4472 getLegacyIntegralTypeEncoding(qt);
4473 getObjCEncodingForTypeImpl(qt, S, false, true,
4474 FD, /*OutermostType*/false,
4475 /*EncodingProperty*/false,
4476 /*StructField*/true);
4481 S += RDecl->isUnion() ? ')' : '}';
4485 if (const EnumType *ET = T->getAs<EnumType>()) {
4486 if (FD && FD->isBitField())
4487 EncodeBitField(this, S, T, FD);
4489 S += ObjCEncodingForEnumType(this, ET);
4493 if (T->isBlockPointerType()) {
4494 S += "@?"; // Unlike a pointer-to-function, which is "^?".
4498 // Ignore protocol qualifiers when mangling at this level.
4499 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4500 T = OT->getBaseType();
4502 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4503 // @encode(class_name)
4504 ObjCInterfaceDecl *OI = OIT->getDecl();
4506 const IdentifierInfo *II = OI->getIdentifier();
4509 SmallVector<const ObjCIvarDecl*, 32> Ivars;
4510 DeepCollectObjCIvars(OI, true, Ivars);
4511 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4512 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4513 if (Field->isBitField())
4514 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4516 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4522 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4523 if (OPT->isObjCIdType()) {
4528 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4529 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4530 // Since this is a binary compatibility issue, need to consult with runtime
4531 // folks. Fortunately, this is a *very* obsure construct.
4536 if (OPT->isObjCQualifiedIdType()) {
4537 getObjCEncodingForTypeImpl(getObjCIdType(), S,
4538 ExpandPointedToStructures,
4539 ExpandStructures, FD);
4540 if (FD || EncodingProperty) {
4541 // Note that we do extended encoding of protocol qualifer list
4542 // Only when doing ivar or property encoding.
4544 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4545 E = OPT->qual_end(); I != E; ++I) {
4547 S += (*I)->getNameAsString();
4555 QualType PointeeTy = OPT->getPointeeType();
4556 if (!EncodingProperty &&
4557 isa<TypedefType>(PointeeTy.getTypePtr())) {
4558 // Another historical/compatibility reason.
4559 // We encode the underlying type which comes out as
4562 getObjCEncodingForTypeImpl(PointeeTy, S,
4563 false, ExpandPointedToStructures,
4569 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
4571 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4572 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4573 E = OPT->qual_end(); I != E; ++I) {
4575 S += (*I)->getNameAsString();
4583 // gcc just blithely ignores member pointers.
4584 // TODO: maybe there should be a mangling for these
4585 if (T->getAs<MemberPointerType>())
4588 if (T->isVectorType()) {
4589 // This matches gcc's encoding, even though technically it is
4591 // FIXME. We should do a better job than gcc.
4595 llvm_unreachable("@encode for type not implemented!");
4598 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4600 const FieldDecl *FD,
4601 bool includeVBases) const {
4602 assert(RDecl && "Expected non-null RecordDecl");
4603 assert(!RDecl->isUnion() && "Should not be called for unions");
4604 if (!RDecl->getDefinition())
4607 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4608 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4609 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4612 for (CXXRecordDecl::base_class_iterator
4613 BI = CXXRec->bases_begin(),
4614 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4615 if (!BI->isVirtual()) {
4616 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4617 if (base->isEmpty())
4619 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4620 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4621 std::make_pair(offs, base));
4627 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4628 FieldEnd = RDecl->field_end();
4629 Field != FieldEnd; ++Field, ++i) {
4630 uint64_t offs = layout.getFieldOffset(i);
4631 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4632 std::make_pair(offs, *Field));
4635 if (CXXRec && includeVBases) {
4636 for (CXXRecordDecl::base_class_iterator
4637 BI = CXXRec->vbases_begin(),
4638 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4639 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4640 if (base->isEmpty())
4642 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4643 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4644 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4645 std::make_pair(offs, base));
4651 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4653 size = layout.getSize();
4656 uint64_t CurOffs = 0;
4657 std::multimap<uint64_t, NamedDecl *>::iterator
4658 CurLayObj = FieldOrBaseOffsets.begin();
4660 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4661 (CurLayObj == FieldOrBaseOffsets.end() &&
4662 CXXRec && CXXRec->isDynamicClass())) {
4663 assert(CXXRec && CXXRec->isDynamicClass() &&
4664 "Offset 0 was empty but no VTable ?");
4667 std::string recname = CXXRec->getNameAsString();
4668 if (recname.empty()) recname = "?";
4673 CurOffs += getTypeSize(VoidPtrTy);
4676 if (!RDecl->hasFlexibleArrayMember()) {
4677 // Mark the end of the structure.
4678 uint64_t offs = toBits(size);
4679 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4680 std::make_pair(offs, (NamedDecl*)0));
4683 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4684 assert(CurOffs <= CurLayObj->first);
4686 if (CurOffs < CurLayObj->first) {
4687 uint64_t padding = CurLayObj->first - CurOffs;
4688 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4689 // packing/alignment of members is different that normal, in which case
4690 // the encoding will be out-of-sync with the real layout.
4691 // If the runtime switches to just consider the size of types without
4692 // taking into account alignment, we could make padding explicit in the
4693 // encoding (e.g. using arrays of chars). The encoding strings would be
4694 // longer then though.
4698 NamedDecl *dcl = CurLayObj->second;
4700 break; // reached end of structure.
4702 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4703 // We expand the bases without their virtual bases since those are going
4704 // in the initial structure. Note that this differs from gcc which
4705 // expands virtual bases each time one is encountered in the hierarchy,
4706 // making the encoding type bigger than it really is.
4707 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4708 assert(!base->isEmpty());
4709 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4711 FieldDecl *field = cast<FieldDecl>(dcl);
4714 S += field->getNameAsString();
4718 if (field->isBitField()) {
4719 EncodeBitField(this, S, field->getType(), field);
4720 CurOffs += field->getBitWidthValue(*this);
4722 QualType qt = field->getType();
4723 getLegacyIntegralTypeEncoding(qt);
4724 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4725 /*OutermostType*/false,
4726 /*EncodingProperty*/false,
4727 /*StructField*/true);
4728 CurOffs += getTypeSize(field->getType());
4734 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4735 std::string& S) const {
4736 if (QT & Decl::OBJC_TQ_In)
4738 if (QT & Decl::OBJC_TQ_Inout)
4740 if (QT & Decl::OBJC_TQ_Out)
4742 if (QT & Decl::OBJC_TQ_Bycopy)
4744 if (QT & Decl::OBJC_TQ_Byref)
4746 if (QT & Decl::OBJC_TQ_Oneway)
4750 void ASTContext::setBuiltinVaListType(QualType T) {
4751 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4753 BuiltinVaListType = T;
4756 TypedefDecl *ASTContext::getObjCIdDecl() const {
4758 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4759 T = getObjCObjectPointerType(T);
4760 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4761 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4762 getTranslationUnitDecl(),
4763 SourceLocation(), SourceLocation(),
4764 &Idents.get("id"), IdInfo);
4770 TypedefDecl *ASTContext::getObjCSelDecl() const {
4772 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4773 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4774 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4775 getTranslationUnitDecl(),
4776 SourceLocation(), SourceLocation(),
4777 &Idents.get("SEL"), SelInfo);
4782 void ASTContext::setObjCProtoType(QualType QT) {
4786 TypedefDecl *ASTContext::getObjCClassDecl() const {
4787 if (!ObjCClassDecl) {
4788 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4789 T = getObjCObjectPointerType(T);
4790 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4791 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4792 getTranslationUnitDecl(),
4793 SourceLocation(), SourceLocation(),
4794 &Idents.get("Class"), ClassInfo);
4797 return ObjCClassDecl;
4800 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4801 assert(ObjCConstantStringType.isNull() &&
4802 "'NSConstantString' type already set!");
4804 ObjCConstantStringType = getObjCInterfaceType(Decl);
4807 /// \brief Retrieve the template name that corresponds to a non-empty
4810 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4811 UnresolvedSetIterator End) const {
4812 unsigned size = End - Begin;
4813 assert(size > 1 && "set is not overloaded!");
4815 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4816 size * sizeof(FunctionTemplateDecl*));
4817 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4819 NamedDecl **Storage = OT->getStorage();
4820 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4822 assert(isa<FunctionTemplateDecl>(D) ||
4823 (isa<UsingShadowDecl>(D) &&
4824 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4828 return TemplateName(OT);
4831 /// \brief Retrieve the template name that represents a qualified
4832 /// template name such as \c std::vector.
4834 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4835 bool TemplateKeyword,
4836 TemplateDecl *Template) const {
4837 assert(NNS && "Missing nested-name-specifier in qualified template name");
4839 // FIXME: Canonicalization?
4840 llvm::FoldingSetNodeID ID;
4841 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4843 void *InsertPos = 0;
4844 QualifiedTemplateName *QTN =
4845 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4847 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4848 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4851 return TemplateName(QTN);
4854 /// \brief Retrieve the template name that represents a dependent
4855 /// template name such as \c MetaFun::template apply.
4857 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4858 const IdentifierInfo *Name) const {
4859 assert((!NNS || NNS->isDependent()) &&
4860 "Nested name specifier must be dependent");
4862 llvm::FoldingSetNodeID ID;
4863 DependentTemplateName::Profile(ID, NNS, Name);
4865 void *InsertPos = 0;
4866 DependentTemplateName *QTN =
4867 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4870 return TemplateName(QTN);
4872 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4873 if (CanonNNS == NNS) {
4874 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4876 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4877 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4878 DependentTemplateName *CheckQTN =
4879 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4880 assert(!CheckQTN && "Dependent type name canonicalization broken");
4884 DependentTemplateNames.InsertNode(QTN, InsertPos);
4885 return TemplateName(QTN);
4888 /// \brief Retrieve the template name that represents a dependent
4889 /// template name such as \c MetaFun::template operator+.
4891 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4892 OverloadedOperatorKind Operator) const {
4893 assert((!NNS || NNS->isDependent()) &&
4894 "Nested name specifier must be dependent");
4896 llvm::FoldingSetNodeID ID;
4897 DependentTemplateName::Profile(ID, NNS, Operator);
4899 void *InsertPos = 0;
4900 DependentTemplateName *QTN
4901 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4904 return TemplateName(QTN);
4906 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4907 if (CanonNNS == NNS) {
4908 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4910 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4911 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4913 DependentTemplateName *CheckQTN
4914 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4915 assert(!CheckQTN && "Dependent template name canonicalization broken");
4919 DependentTemplateNames.InsertNode(QTN, InsertPos);
4920 return TemplateName(QTN);
4924 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4925 TemplateName replacement) const {
4926 llvm::FoldingSetNodeID ID;
4927 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4929 void *insertPos = 0;
4930 SubstTemplateTemplateParmStorage *subst
4931 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4934 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4935 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4938 return TemplateName(subst);
4942 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4943 const TemplateArgument &ArgPack) const {
4944 ASTContext &Self = const_cast<ASTContext &>(*this);
4945 llvm::FoldingSetNodeID ID;
4946 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4948 void *InsertPos = 0;
4949 SubstTemplateTemplateParmPackStorage *Subst
4950 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4953 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
4954 ArgPack.pack_size(),
4955 ArgPack.pack_begin());
4956 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4959 return TemplateName(Subst);
4962 /// getFromTargetType - Given one of the integer types provided by
4963 /// TargetInfo, produce the corresponding type. The unsigned @p Type
4964 /// is actually a value of type @c TargetInfo::IntType.
4965 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4967 case TargetInfo::NoInt: return CanQualType();
4968 case TargetInfo::SignedShort: return ShortTy;
4969 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4970 case TargetInfo::SignedInt: return IntTy;
4971 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4972 case TargetInfo::SignedLong: return LongTy;
4973 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4974 case TargetInfo::SignedLongLong: return LongLongTy;
4975 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4978 llvm_unreachable("Unhandled TargetInfo::IntType value");
4981 //===----------------------------------------------------------------------===//
4983 //===----------------------------------------------------------------------===//
4985 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4986 /// garbage collection attribute.
4988 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4989 if (getLangOptions().getGC() == LangOptions::NonGC)
4990 return Qualifiers::GCNone;
4992 assert(getLangOptions().ObjC1);
4993 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4995 // Default behaviour under objective-C's gc is for ObjC pointers
4996 // (or pointers to them) be treated as though they were declared
4998 if (GCAttrs == Qualifiers::GCNone) {
4999 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5000 return Qualifiers::Strong;
5001 else if (Ty->isPointerType())
5002 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5004 // It's not valid to set GC attributes on anything that isn't a
5007 QualType CT = Ty->getCanonicalTypeInternal();
5008 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5009 CT = AT->getElementType();
5010 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5016 //===----------------------------------------------------------------------===//
5017 // Type Compatibility Testing
5018 //===----------------------------------------------------------------------===//
5020 /// areCompatVectorTypes - Return true if the two specified vector types are
5022 static bool areCompatVectorTypes(const VectorType *LHS,
5023 const VectorType *RHS) {
5024 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5025 return LHS->getElementType() == RHS->getElementType() &&
5026 LHS->getNumElements() == RHS->getNumElements();
5029 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5030 QualType SecondVec) {
5031 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5032 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5034 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5037 // Treat Neon vector types and most AltiVec vector types as if they are the
5038 // equivalent GCC vector types.
5039 const VectorType *First = FirstVec->getAs<VectorType>();
5040 const VectorType *Second = SecondVec->getAs<VectorType>();
5041 if (First->getNumElements() == Second->getNumElements() &&
5042 hasSameType(First->getElementType(), Second->getElementType()) &&
5043 First->getVectorKind() != VectorType::AltiVecPixel &&
5044 First->getVectorKind() != VectorType::AltiVecBool &&
5045 Second->getVectorKind() != VectorType::AltiVecPixel &&
5046 Second->getVectorKind() != VectorType::AltiVecBool)
5052 //===----------------------------------------------------------------------===//
5053 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5054 //===----------------------------------------------------------------------===//
5056 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5057 /// inheritance hierarchy of 'rProto'.
5059 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5060 ObjCProtocolDecl *rProto) const {
5061 if (lProto == rProto)
5063 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5064 E = rProto->protocol_end(); PI != E; ++PI)
5065 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5070 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5071 /// return true if lhs's protocols conform to rhs's protocol; false
5073 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5074 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5075 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5079 /// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5081 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5083 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5084 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5085 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5087 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5088 E = lhsQID->qual_end(); I != E; ++I) {
5090 ObjCProtocolDecl *lhsProto = *I;
5091 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5092 E = rhsOPT->qual_end(); J != E; ++J) {
5093 ObjCProtocolDecl *rhsProto = *J;
5094 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5105 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5106 /// ObjCQualifiedIDType.
5107 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5109 // Allow id<P..> and an 'id' or void* type in all cases.
5110 if (lhs->isVoidPointerType() ||
5111 lhs->isObjCIdType() || lhs->isObjCClassType())
5113 else if (rhs->isVoidPointerType() ||
5114 rhs->isObjCIdType() || rhs->isObjCClassType())
5117 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5118 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5120 if (!rhsOPT) return false;
5122 if (rhsOPT->qual_empty()) {
5123 // If the RHS is a unqualified interface pointer "NSString*",
5124 // make sure we check the class hierarchy.
5125 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5126 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5127 E = lhsQID->qual_end(); I != E; ++I) {
5128 // when comparing an id<P> on lhs with a static type on rhs,
5129 // see if static class implements all of id's protocols, directly or
5130 // through its super class and categories.
5131 if (!rhsID->ClassImplementsProtocol(*I, true))
5135 // If there are no qualifiers and no interface, we have an 'id'.
5138 // Both the right and left sides have qualifiers.
5139 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5140 E = lhsQID->qual_end(); I != E; ++I) {
5141 ObjCProtocolDecl *lhsProto = *I;
5144 // when comparing an id<P> on lhs with a static type on rhs,
5145 // see if static class implements all of id's protocols, directly or
5146 // through its super class and categories.
5147 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5148 E = rhsOPT->qual_end(); J != E; ++J) {
5149 ObjCProtocolDecl *rhsProto = *J;
5150 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5151 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5156 // If the RHS is a qualified interface pointer "NSString<P>*",
5157 // make sure we check the class hierarchy.
5158 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5159 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5160 E = lhsQID->qual_end(); I != E; ++I) {
5161 // when comparing an id<P> on lhs with a static type on rhs,
5162 // see if static class implements all of id's protocols, directly or
5163 // through its super class and categories.
5164 if (rhsID->ClassImplementsProtocol(*I, true)) {
5177 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5178 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5180 if (const ObjCObjectPointerType *lhsOPT =
5181 lhs->getAsObjCInterfacePointerType()) {
5182 // If both the right and left sides have qualifiers.
5183 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5184 E = lhsOPT->qual_end(); I != E; ++I) {
5185 ObjCProtocolDecl *lhsProto = *I;
5188 // when comparing an id<P> on rhs with a static type on lhs,
5189 // see if static class implements all of id's protocols, directly or
5190 // through its super class and categories.
5191 // First, lhs protocols in the qualifier list must be found, direct
5192 // or indirect in rhs's qualifier list or it is a mismatch.
5193 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5194 E = rhsQID->qual_end(); J != E; ++J) {
5195 ObjCProtocolDecl *rhsProto = *J;
5196 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5197 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5206 // Static class's protocols, or its super class or category protocols
5207 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5208 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5209 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5210 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5211 // This is rather dubious but matches gcc's behavior. If lhs has
5212 // no type qualifier and its class has no static protocol(s)
5213 // assume that it is mismatch.
5214 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5216 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5217 LHSInheritedProtocols.begin(),
5218 E = LHSInheritedProtocols.end(); I != E; ++I) {
5220 ObjCProtocolDecl *lhsProto = (*I);
5221 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5222 E = rhsQID->qual_end(); J != E; ++J) {
5223 ObjCProtocolDecl *rhsProto = *J;
5224 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5225 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5239 /// canAssignObjCInterfaces - Return true if the two interface types are
5240 /// compatible for assignment from RHS to LHS. This handles validation of any
5241 /// protocol qualifiers on the LHS or RHS.
5243 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5244 const ObjCObjectPointerType *RHSOPT) {
5245 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5246 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5248 // If either type represents the built-in 'id' or 'Class' types, return true.
5249 if (LHS->isObjCUnqualifiedIdOrClass() ||
5250 RHS->isObjCUnqualifiedIdOrClass())
5253 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5254 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5258 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5259 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5260 QualType(RHSOPT,0));
5262 // If we have 2 user-defined types, fall into that path.
5263 if (LHS->getInterface() && RHS->getInterface())
5264 return canAssignObjCInterfaces(LHS, RHS);
5269 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5270 /// for providing type-safety for objective-c pointers used to pass/return
5271 /// arguments in block literals. When passed as arguments, passing 'A*' where
5272 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5273 /// not OK. For the return type, the opposite is not OK.
5274 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5275 const ObjCObjectPointerType *LHSOPT,
5276 const ObjCObjectPointerType *RHSOPT,
5277 bool BlockReturnType) {
5278 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5281 if (LHSOPT->isObjCBuiltinType()) {
5282 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5285 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5286 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5290 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5291 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5292 if (LHS && RHS) { // We have 2 user-defined types.
5294 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5295 return BlockReturnType;
5296 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5297 return !BlockReturnType;
5305 /// getIntersectionOfProtocols - This routine finds the intersection of set
5306 /// of protocols inherited from two distinct objective-c pointer objects.
5307 /// It is used to build composite qualifier list of the composite type of
5308 /// the conditional expression involving two objective-c pointer objects.
5310 void getIntersectionOfProtocols(ASTContext &Context,
5311 const ObjCObjectPointerType *LHSOPT,
5312 const ObjCObjectPointerType *RHSOPT,
5313 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5315 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5316 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5317 assert(LHS->getInterface() && "LHS must have an interface base");
5318 assert(RHS->getInterface() && "RHS must have an interface base");
5320 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5321 unsigned LHSNumProtocols = LHS->getNumProtocols();
5322 if (LHSNumProtocols > 0)
5323 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5325 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5326 Context.CollectInheritedProtocols(LHS->getInterface(),
5327 LHSInheritedProtocols);
5328 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5329 LHSInheritedProtocols.end());
5332 unsigned RHSNumProtocols = RHS->getNumProtocols();
5333 if (RHSNumProtocols > 0) {
5334 ObjCProtocolDecl **RHSProtocols =
5335 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5336 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5337 if (InheritedProtocolSet.count(RHSProtocols[i]))
5338 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5340 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5341 Context.CollectInheritedProtocols(RHS->getInterface(),
5342 RHSInheritedProtocols);
5343 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5344 RHSInheritedProtocols.begin(),
5345 E = RHSInheritedProtocols.end(); I != E; ++I)
5346 if (InheritedProtocolSet.count((*I)))
5347 IntersectionOfProtocols.push_back((*I));
5351 /// areCommonBaseCompatible - Returns common base class of the two classes if
5352 /// one found. Note that this is O'2 algorithm. But it will be called as the
5353 /// last type comparison in a ?-exp of ObjC pointer types before a
5354 /// warning is issued. So, its invokation is extremely rare.
5355 QualType ASTContext::areCommonBaseCompatible(
5356 const ObjCObjectPointerType *Lptr,
5357 const ObjCObjectPointerType *Rptr) {
5358 const ObjCObjectType *LHS = Lptr->getObjectType();
5359 const ObjCObjectType *RHS = Rptr->getObjectType();
5360 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5361 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5362 if (!LDecl || !RDecl || (LDecl == RDecl))
5366 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5367 if (canAssignObjCInterfaces(LHS, RHS)) {
5368 SmallVector<ObjCProtocolDecl *, 8> Protocols;
5369 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5371 QualType Result = QualType(LHS, 0);
5372 if (!Protocols.empty())
5373 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5374 Result = getObjCObjectPointerType(Result);
5377 } while ((LDecl = LDecl->getSuperClass()));
5382 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5383 const ObjCObjectType *RHS) {
5384 assert(LHS->getInterface() && "LHS is not an interface type");
5385 assert(RHS->getInterface() && "RHS is not an interface type");
5387 // Verify that the base decls are compatible: the RHS must be a subclass of
5389 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5392 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5393 // protocol qualified at all, then we are good.
5394 if (LHS->getNumProtocols() == 0)
5397 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5398 // more detailed analysis is required.
5399 if (RHS->getNumProtocols() == 0) {
5400 // OK, if LHS is a superclass of RHS *and*
5401 // this superclass is assignment compatible with LHS.
5404 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5406 // OK if conversion of LHS to SuperClass results in narrowing of types
5407 // ; i.e., SuperClass may implement at least one of the protocols
5408 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5409 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5410 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5411 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5412 // If super class has no protocols, it is not a match.
5413 if (SuperClassInheritedProtocols.empty())
5416 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5417 LHSPE = LHS->qual_end();
5418 LHSPI != LHSPE; LHSPI++) {
5419 bool SuperImplementsProtocol = false;
5420 ObjCProtocolDecl *LHSProto = (*LHSPI);
5422 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5423 SuperClassInheritedProtocols.begin(),
5424 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5425 ObjCProtocolDecl *SuperClassProto = (*I);
5426 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5427 SuperImplementsProtocol = true;
5431 if (!SuperImplementsProtocol)
5439 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5440 LHSPE = LHS->qual_end();
5441 LHSPI != LHSPE; LHSPI++) {
5442 bool RHSImplementsProtocol = false;
5444 // If the RHS doesn't implement the protocol on the left, the types
5445 // are incompatible.
5446 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5447 RHSPE = RHS->qual_end();
5448 RHSPI != RHSPE; RHSPI++) {
5449 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5450 RHSImplementsProtocol = true;
5454 // FIXME: For better diagnostics, consider passing back the protocol name.
5455 if (!RHSImplementsProtocol)
5458 // The RHS implements all protocols listed on the LHS.
5462 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5463 // get the "pointed to" types
5464 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5465 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5467 if (!LHSOPT || !RHSOPT)
5470 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5471 canAssignObjCInterfaces(RHSOPT, LHSOPT);
5474 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5475 return canAssignObjCInterfaces(
5476 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5477 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5480 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5481 /// both shall have the identically qualified version of a compatible type.
5482 /// C99 6.2.7p1: Two types have compatible types if their types are the
5483 /// same. See 6.7.[2,3,5] for additional rules.
5484 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5485 bool CompareUnqualified) {
5486 if (getLangOptions().CPlusPlus)
5487 return hasSameType(LHS, RHS);
5489 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5492 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5493 return typesAreCompatible(LHS, RHS);
5496 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5497 return !mergeTypes(LHS, RHS, true).isNull();
5500 /// mergeTransparentUnionType - if T is a transparent union type and a member
5501 /// of T is compatible with SubType, return the merged type, else return
5503 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5504 bool OfBlockPointer,
5506 if (const RecordType *UT = T->getAsUnionType()) {
5507 RecordDecl *UD = UT->getDecl();
5508 if (UD->hasAttr<TransparentUnionAttr>()) {
5509 for (RecordDecl::field_iterator it = UD->field_begin(),
5510 itend = UD->field_end(); it != itend; ++it) {
5511 QualType ET = it->getType().getUnqualifiedType();
5512 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5522 /// mergeFunctionArgumentTypes - merge two types which appear as function
5524 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5525 bool OfBlockPointer,
5527 // GNU extension: two types are compatible if they appear as a function
5528 // argument, one of the types is a transparent union type and the other
5529 // type is compatible with a union member
5530 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5532 if (!lmerge.isNull())
5535 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5537 if (!rmerge.isNull())
5540 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5543 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5544 bool OfBlockPointer,
5546 const FunctionType *lbase = lhs->getAs<FunctionType>();
5547 const FunctionType *rbase = rhs->getAs<FunctionType>();
5548 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5549 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5550 bool allLTypes = true;
5551 bool allRTypes = true;
5553 // Check return type
5555 if (OfBlockPointer) {
5556 QualType RHS = rbase->getResultType();
5557 QualType LHS = lbase->getResultType();
5558 bool UnqualifiedResult = Unqualified;
5559 if (!UnqualifiedResult)
5560 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5561 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5564 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5566 if (retType.isNull()) return QualType();
5569 retType = retType.getUnqualifiedType();
5571 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5572 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5574 LRetType = LRetType.getUnqualifiedType();
5575 RRetType = RRetType.getUnqualifiedType();
5578 if (getCanonicalType(retType) != LRetType)
5580 if (getCanonicalType(retType) != RRetType)
5583 // FIXME: double check this
5584 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5585 // rbase->getRegParmAttr() != 0 &&
5586 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5587 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5588 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5590 // Compatible functions must have compatible calling conventions
5591 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5594 // Regparm is part of the calling convention.
5595 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5597 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5600 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5603 // functypes which return are preferred over those that do not.
5604 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5606 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5608 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5609 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5611 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
5613 if (lproto && rproto) { // two C99 style function prototypes
5614 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5615 "C++ shouldn't be here");
5616 unsigned lproto_nargs = lproto->getNumArgs();
5617 unsigned rproto_nargs = rproto->getNumArgs();
5619 // Compatible functions must have the same number of arguments
5620 if (lproto_nargs != rproto_nargs)
5623 // Variadic and non-variadic functions aren't compatible
5624 if (lproto->isVariadic() != rproto->isVariadic())
5627 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5630 if (LangOpts.ObjCAutoRefCount &&
5631 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5634 // Check argument compatibility
5635 SmallVector<QualType, 10> types;
5636 for (unsigned i = 0; i < lproto_nargs; i++) {
5637 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5638 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5639 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5642 if (argtype.isNull()) return QualType();
5645 argtype = argtype.getUnqualifiedType();
5647 types.push_back(argtype);
5649 largtype = largtype.getUnqualifiedType();
5650 rargtype = rargtype.getUnqualifiedType();
5653 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5655 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5659 if (allLTypes) return lhs;
5660 if (allRTypes) return rhs;
5662 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5663 EPI.ExtInfo = einfo;
5664 return getFunctionType(retType, types.begin(), types.size(), EPI);
5667 if (lproto) allRTypes = false;
5668 if (rproto) allLTypes = false;
5670 const FunctionProtoType *proto = lproto ? lproto : rproto;
5672 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5673 if (proto->isVariadic()) return QualType();
5674 // Check that the types are compatible with the types that
5675 // would result from default argument promotions (C99 6.7.5.3p15).
5676 // The only types actually affected are promotable integer
5677 // types and floats, which would be passed as a different
5678 // type depending on whether the prototype is visible.
5679 unsigned proto_nargs = proto->getNumArgs();
5680 for (unsigned i = 0; i < proto_nargs; ++i) {
5681 QualType argTy = proto->getArgType(i);
5683 // Look at the promotion type of enum types, since that is the type used
5684 // to pass enum values.
5685 if (const EnumType *Enum = argTy->getAs<EnumType>())
5686 argTy = Enum->getDecl()->getPromotionType();
5688 if (argTy->isPromotableIntegerType() ||
5689 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5693 if (allLTypes) return lhs;
5694 if (allRTypes) return rhs;
5696 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5697 EPI.ExtInfo = einfo;
5698 return getFunctionType(retType, proto->arg_type_begin(),
5699 proto->getNumArgs(), EPI);
5702 if (allLTypes) return lhs;
5703 if (allRTypes) return rhs;
5704 return getFunctionNoProtoType(retType, einfo);
5707 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5708 bool OfBlockPointer,
5709 bool Unqualified, bool BlockReturnType) {
5710 // C++ [expr]: If an expression initially has the type "reference to T", the
5711 // type is adjusted to "T" prior to any further analysis, the expression
5712 // designates the object or function denoted by the reference, and the
5713 // expression is an lvalue unless the reference is an rvalue reference and
5714 // the expression is a function call (possibly inside parentheses).
5715 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5716 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5719 LHS = LHS.getUnqualifiedType();
5720 RHS = RHS.getUnqualifiedType();
5723 QualType LHSCan = getCanonicalType(LHS),
5724 RHSCan = getCanonicalType(RHS);
5726 // If two types are identical, they are compatible.
5727 if (LHSCan == RHSCan)
5730 // If the qualifiers are different, the types aren't compatible... mostly.
5731 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5732 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5733 if (LQuals != RQuals) {
5734 // If any of these qualifiers are different, we have a type
5736 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5737 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5738 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
5741 // Exactly one GC qualifier difference is allowed: __strong is
5742 // okay if the other type has no GC qualifier but is an Objective
5743 // C object pointer (i.e. implicitly strong by default). We fix
5744 // this by pretending that the unqualified type was actually
5745 // qualified __strong.
5746 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5747 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5748 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5750 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5753 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5754 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5756 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5757 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5762 // Okay, qualifiers are equal.
5764 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5765 Type::TypeClass RHSClass = RHSCan->getTypeClass();
5767 // We want to consider the two function types to be the same for these
5768 // comparisons, just force one to the other.
5769 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5770 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5772 // Same as above for arrays
5773 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5774 LHSClass = Type::ConstantArray;
5775 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5776 RHSClass = Type::ConstantArray;
5778 // ObjCInterfaces are just specialized ObjCObjects.
5779 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5780 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5782 // Canonicalize ExtVector -> Vector.
5783 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5784 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5786 // If the canonical type classes don't match.
5787 if (LHSClass != RHSClass) {
5788 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5789 // a signed integer type, or an unsigned integer type.
5790 // Compatibility is based on the underlying type, not the promotion
5792 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5793 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5796 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5797 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5804 // The canonical type classes match.
5806 #define TYPE(Class, Base)
5807 #define ABSTRACT_TYPE(Class, Base)
5808 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5809 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5810 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
5811 #include "clang/AST/TypeNodes.def"
5812 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
5814 case Type::LValueReference:
5815 case Type::RValueReference:
5816 case Type::MemberPointer:
5817 llvm_unreachable("C++ should never be in mergeTypes");
5819 case Type::ObjCInterface:
5820 case Type::IncompleteArray:
5821 case Type::VariableArray:
5822 case Type::FunctionProto:
5823 case Type::ExtVector:
5824 llvm_unreachable("Types are eliminated above");
5828 // Merge two pointer types, while trying to preserve typedef info
5829 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5830 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5832 LHSPointee = LHSPointee.getUnqualifiedType();
5833 RHSPointee = RHSPointee.getUnqualifiedType();
5835 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5837 if (ResultType.isNull()) return QualType();
5838 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5840 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5842 return getPointerType(ResultType);
5844 case Type::BlockPointer:
5846 // Merge two block pointer types, while trying to preserve typedef info
5847 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5848 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5850 LHSPointee = LHSPointee.getUnqualifiedType();
5851 RHSPointee = RHSPointee.getUnqualifiedType();
5853 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5855 if (ResultType.isNull()) return QualType();
5856 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5858 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5860 return getBlockPointerType(ResultType);
5864 // Merge two pointer types, while trying to preserve typedef info
5865 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5866 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5868 LHSValue = LHSValue.getUnqualifiedType();
5869 RHSValue = RHSValue.getUnqualifiedType();
5871 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5873 if (ResultType.isNull()) return QualType();
5874 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5876 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5878 return getAtomicType(ResultType);
5880 case Type::ConstantArray:
5882 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5883 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5884 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5887 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5888 QualType RHSElem = getAsArrayType(RHS)->getElementType();
5890 LHSElem = LHSElem.getUnqualifiedType();
5891 RHSElem = RHSElem.getUnqualifiedType();
5894 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
5895 if (ResultType.isNull()) return QualType();
5896 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5898 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5900 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5901 ArrayType::ArraySizeModifier(), 0);
5902 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5903 ArrayType::ArraySizeModifier(), 0);
5904 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5905 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
5906 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5908 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5911 // FIXME: This isn't correct! But tricky to implement because
5912 // the array's size has to be the size of LHS, but the type
5913 // has to be different.
5917 // FIXME: This isn't correct! But tricky to implement because
5918 // the array's size has to be the size of RHS, but the type
5919 // has to be different.
5922 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5923 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
5924 return getIncompleteArrayType(ResultType,
5925 ArrayType::ArraySizeModifier(), 0);
5927 case Type::FunctionNoProto:
5928 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
5933 // Only exactly equal builtin types are compatible, which is tested above.
5936 // Distinct complex types are incompatible.
5939 // FIXME: The merged type should be an ExtVector!
5940 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5941 RHSCan->getAs<VectorType>()))
5944 case Type::ObjCObject: {
5945 // Check if the types are assignment compatible.
5946 // FIXME: This should be type compatibility, e.g. whether
5947 // "LHS x; RHS x;" at global scope is legal.
5948 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5949 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5950 if (canAssignObjCInterfaces(LHSIface, RHSIface))
5955 case Type::ObjCObjectPointer: {
5956 if (OfBlockPointer) {
5957 if (canAssignObjCInterfacesInBlockPointer(
5958 LHS->getAs<ObjCObjectPointerType>(),
5959 RHS->getAs<ObjCObjectPointerType>(),
5964 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5965 RHS->getAs<ObjCObjectPointerType>()))
5975 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5976 const FunctionProtoType *FromFunctionType,
5977 const FunctionProtoType *ToFunctionType) {
5978 if (FromFunctionType->hasAnyConsumedArgs() !=
5979 ToFunctionType->hasAnyConsumedArgs())
5981 FunctionProtoType::ExtProtoInfo FromEPI =
5982 FromFunctionType->getExtProtoInfo();
5983 FunctionProtoType::ExtProtoInfo ToEPI =
5984 ToFunctionType->getExtProtoInfo();
5985 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
5986 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
5987 ArgIdx != NumArgs; ++ArgIdx) {
5988 if (FromEPI.ConsumedArguments[ArgIdx] !=
5989 ToEPI.ConsumedArguments[ArgIdx])
5995 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5996 /// 'RHS' attributes and returns the merged version; including for function
5998 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5999 QualType LHSCan = getCanonicalType(LHS),
6000 RHSCan = getCanonicalType(RHS);
6001 // If two types are identical, they are compatible.
6002 if (LHSCan == RHSCan)
6004 if (RHSCan->isFunctionType()) {
6005 if (!LHSCan->isFunctionType())
6007 QualType OldReturnType =
6008 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6009 QualType NewReturnType =
6010 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6011 QualType ResReturnType =
6012 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6013 if (ResReturnType.isNull())
6015 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6016 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6017 // In either case, use OldReturnType to build the new function type.
6018 const FunctionType *F = LHS->getAs<FunctionType>();
6019 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6021 EPI.ExtInfo = getFunctionExtInfo(LHS);
6023 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6024 FPT->getNumArgs(), EPI);
6031 // If the qualifiers are different, the types can still be merged.
6032 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6033 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6034 if (LQuals != RQuals) {
6035 // If any of these qualifiers are different, we have a type mismatch.
6036 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6037 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6040 // Exactly one GC qualifier difference is allowed: __strong is
6041 // okay if the other type has no GC qualifier but is an Objective
6042 // C object pointer (i.e. implicitly strong by default). We fix
6043 // this by pretending that the unqualified type was actually
6044 // qualified __strong.
6045 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6046 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6047 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6049 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6052 if (GC_L == Qualifiers::Strong)
6054 if (GC_R == Qualifiers::Strong)
6059 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6060 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6061 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6062 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6063 if (ResQT == LHSBaseQT)
6065 if (ResQT == RHSBaseQT)
6071 //===----------------------------------------------------------------------===//
6072 // Integer Predicates
6073 //===----------------------------------------------------------------------===//
6075 unsigned ASTContext::getIntWidth(QualType T) const {
6076 if (const EnumType *ET = dyn_cast<EnumType>(T))
6077 T = ET->getDecl()->getIntegerType();
6078 if (T->isBooleanType())
6080 // For builtin types, just use the standard type sizing method
6081 return (unsigned)getTypeSize(T);
6084 QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6085 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6087 // Turn <4 x signed int> -> <4 x unsigned int>
6088 if (const VectorType *VTy = T->getAs<VectorType>())
6089 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6090 VTy->getNumElements(), VTy->getVectorKind());
6092 // For enums, we return the unsigned version of the base type.
6093 if (const EnumType *ETy = T->getAs<EnumType>())
6094 T = ETy->getDecl()->getIntegerType();
6096 const BuiltinType *BTy = T->getAs<BuiltinType>();
6097 assert(BTy && "Unexpected signed integer type");
6098 switch (BTy->getKind()) {
6099 case BuiltinType::Char_S:
6100 case BuiltinType::SChar:
6101 return UnsignedCharTy;
6102 case BuiltinType::Short:
6103 return UnsignedShortTy;
6104 case BuiltinType::Int:
6105 return UnsignedIntTy;
6106 case BuiltinType::Long:
6107 return UnsignedLongTy;
6108 case BuiltinType::LongLong:
6109 return UnsignedLongLongTy;
6110 case BuiltinType::Int128:
6111 return UnsignedInt128Ty;
6113 llvm_unreachable("Unexpected signed integer type");
6117 ASTMutationListener::~ASTMutationListener() { }
6120 //===----------------------------------------------------------------------===//
6121 // Builtin Type Computation
6122 //===----------------------------------------------------------------------===//
6124 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6125 /// pointer over the consumed characters. This returns the resultant type. If
6126 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6127 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6128 /// a vector of "i*".
6130 /// RequiresICE is filled in on return to indicate whether the value is required
6131 /// to be an Integer Constant Expression.
6132 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6133 ASTContext::GetBuiltinTypeError &Error,
6135 bool AllowTypeModifiers) {
6138 bool Signed = false, Unsigned = false;
6139 RequiresICE = false;
6141 // Read the prefixed modifiers first.
6145 default: Done = true; --Str; break;
6150 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6151 assert(!Signed && "Can't use 'S' modifier multiple times!");
6155 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6156 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6160 assert(HowLong <= 2 && "Can't have LLLL modifier");
6168 // Read the base type.
6170 default: llvm_unreachable("Unknown builtin type letter!");
6172 assert(HowLong == 0 && !Signed && !Unsigned &&
6173 "Bad modifiers used with 'v'!");
6174 Type = Context.VoidTy;
6177 assert(HowLong == 0 && !Signed && !Unsigned &&
6178 "Bad modifiers used with 'f'!");
6179 Type = Context.FloatTy;
6182 assert(HowLong < 2 && !Signed && !Unsigned &&
6183 "Bad modifiers used with 'd'!");
6185 Type = Context.LongDoubleTy;
6187 Type = Context.DoubleTy;
6190 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6192 Type = Context.UnsignedShortTy;
6194 Type = Context.ShortTy;
6198 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6199 else if (HowLong == 2)
6200 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6201 else if (HowLong == 1)
6202 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6204 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6207 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6209 Type = Context.SignedCharTy;
6211 Type = Context.UnsignedCharTy;
6213 Type = Context.CharTy;
6215 case 'b': // boolean
6216 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6217 Type = Context.BoolTy;
6219 case 'z': // size_t.
6220 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6221 Type = Context.getSizeType();
6224 Type = Context.getCFConstantStringType();
6227 Type = Context.getObjCIdType();
6230 Type = Context.getObjCSelType();
6233 Type = Context.getBuiltinVaListType();
6234 assert(!Type.isNull() && "builtin va list type not initialized!");
6237 // This is a "reference" to a va_list; however, what exactly
6238 // this means depends on how va_list is defined. There are two
6239 // different kinds of va_list: ones passed by value, and ones
6240 // passed by reference. An example of a by-value va_list is
6241 // x86, where va_list is a char*. An example of by-ref va_list
6242 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6243 // we want this argument to be a char*&; for x86-64, we want
6244 // it to be a __va_list_tag*.
6245 Type = Context.getBuiltinVaListType();
6246 assert(!Type.isNull() && "builtin va list type not initialized!");
6247 if (Type->isArrayType())
6248 Type = Context.getArrayDecayedType(Type);
6250 Type = Context.getLValueReferenceType(Type);
6254 unsigned NumElements = strtoul(Str, &End, 10);
6255 assert(End != Str && "Missing vector size");
6258 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6259 RequiresICE, false);
6260 assert(!RequiresICE && "Can't require vector ICE");
6262 // TODO: No way to make AltiVec vectors in builtins yet.
6263 Type = Context.getVectorType(ElementType, NumElements,
6264 VectorType::GenericVector);
6268 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6270 assert(!RequiresICE && "Can't require complex ICE");
6271 Type = Context.getComplexType(ElementType);
6275 Type = Context.getPointerDiffType();
6279 Type = Context.getFILEType();
6280 if (Type.isNull()) {
6281 Error = ASTContext::GE_Missing_stdio;
6287 Type = Context.getsigjmp_bufType();
6289 Type = Context.getjmp_bufType();
6291 if (Type.isNull()) {
6292 Error = ASTContext::GE_Missing_setjmp;
6298 // If there are modifiers and if we're allowed to parse them, go for it.
6299 Done = !AllowTypeModifiers;
6301 switch (char c = *Str++) {
6302 default: Done = true; --Str; break;
6305 // Both pointers and references can have their pointee types
6306 // qualified with an address space.
6308 unsigned AddrSpace = strtoul(Str, &End, 10);
6309 if (End != Str && AddrSpace != 0) {
6310 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6314 Type = Context.getPointerType(Type);
6316 Type = Context.getLValueReferenceType(Type);
6319 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6321 Type = Type.withConst();
6324 Type = Context.getVolatileType(Type);
6329 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6330 "Integer constant 'I' type must be an integer");
6335 /// GetBuiltinType - Return the type for the specified builtin.
6336 QualType ASTContext::GetBuiltinType(unsigned Id,
6337 GetBuiltinTypeError &Error,
6338 unsigned *IntegerConstantArgs) const {
6339 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6341 SmallVector<QualType, 8> ArgTypes;
6343 bool RequiresICE = false;
6345 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6347 if (Error != GE_None)
6350 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6352 while (TypeStr[0] && TypeStr[0] != '.') {
6353 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6354 if (Error != GE_None)
6357 // If this argument is required to be an IntegerConstantExpression and the
6358 // caller cares, fill in the bitmask we return.
6359 if (RequiresICE && IntegerConstantArgs)
6360 *IntegerConstantArgs |= 1 << ArgTypes.size();
6362 // Do array -> pointer decay. The builtin should use the decayed type.
6363 if (Ty->isArrayType())
6364 Ty = getArrayDecayedType(Ty);
6366 ArgTypes.push_back(Ty);
6369 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6370 "'.' should only occur at end of builtin type list!");
6372 FunctionType::ExtInfo EI;
6373 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6375 bool Variadic = (TypeStr[0] == '.');
6377 // We really shouldn't be making a no-proto type here, especially in C++.
6378 if (ArgTypes.empty() && Variadic)
6379 return getFunctionNoProtoType(ResType, EI);
6381 FunctionProtoType::ExtProtoInfo EPI;
6383 EPI.Variadic = Variadic;
6385 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6388 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6389 GVALinkage External = GVA_StrongExternal;
6391 Linkage L = FD->getLinkage();
6394 case InternalLinkage:
6395 case UniqueExternalLinkage:
6396 return GVA_Internal;
6398 case ExternalLinkage:
6399 switch (FD->getTemplateSpecializationKind()) {
6400 case TSK_Undeclared:
6401 case TSK_ExplicitSpecialization:
6402 External = GVA_StrongExternal;
6405 case TSK_ExplicitInstantiationDefinition:
6406 return GVA_ExplicitTemplateInstantiation;
6408 case TSK_ExplicitInstantiationDeclaration:
6409 case TSK_ImplicitInstantiation:
6410 External = GVA_TemplateInstantiation;
6415 if (!FD->isInlined())
6418 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6419 // GNU or C99 inline semantics. Determine whether this symbol should be
6420 // externally visible.
6421 if (FD->isInlineDefinitionExternallyVisible())
6424 // C99 inline semantics, where the symbol is not externally visible.
6425 return GVA_C99Inline;
6428 // C++0x [temp.explicit]p9:
6429 // [ Note: The intent is that an inline function that is the subject of
6430 // an explicit instantiation declaration will still be implicitly
6431 // instantiated when used so that the body can be considered for
6432 // inlining, but that no out-of-line copy of the inline function would be
6433 // generated in the translation unit. -- end note ]
6434 if (FD->getTemplateSpecializationKind()
6435 == TSK_ExplicitInstantiationDeclaration)
6436 return GVA_C99Inline;
6438 return GVA_CXXInline;
6441 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6442 // If this is a static data member, compute the kind of template
6443 // specialization. Otherwise, this variable is not part of a
6445 TemplateSpecializationKind TSK = TSK_Undeclared;
6446 if (VD->isStaticDataMember())
6447 TSK = VD->getTemplateSpecializationKind();
6449 Linkage L = VD->getLinkage();
6450 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6451 VD->getType()->getLinkage() == UniqueExternalLinkage)
6452 L = UniqueExternalLinkage;
6456 case InternalLinkage:
6457 case UniqueExternalLinkage:
6458 return GVA_Internal;
6460 case ExternalLinkage:
6462 case TSK_Undeclared:
6463 case TSK_ExplicitSpecialization:
6464 return GVA_StrongExternal;
6466 case TSK_ExplicitInstantiationDeclaration:
6467 llvm_unreachable("Variable should not be instantiated");
6468 // Fall through to treat this like any other instantiation.
6470 case TSK_ExplicitInstantiationDefinition:
6471 return GVA_ExplicitTemplateInstantiation;
6473 case TSK_ImplicitInstantiation:
6474 return GVA_TemplateInstantiation;
6478 return GVA_StrongExternal;
6481 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6482 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6483 if (!VD->isFileVarDecl())
6485 } else if (!isa<FunctionDecl>(D))
6488 // Weak references don't produce any output by themselves.
6489 if (D->hasAttr<WeakRefAttr>())
6492 // Aliases and used decls are required.
6493 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6496 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6497 // Forward declarations aren't required.
6498 if (!FD->doesThisDeclarationHaveABody())
6499 return FD->doesDeclarationForceExternallyVisibleDefinition();
6501 // Constructors and destructors are required.
6502 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6505 // The key function for a class is required.
6506 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6507 const CXXRecordDecl *RD = MD->getParent();
6508 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6509 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6510 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6515 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6517 // static, static inline, always_inline, and extern inline functions can
6518 // always be deferred. Normal inline functions can be deferred in C99/C++.
6519 // Implicit template instantiations can also be deferred in C++.
6520 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6521 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6526 const VarDecl *VD = cast<VarDecl>(D);
6527 assert(VD->isFileVarDecl() && "Expected file scoped var");
6529 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6532 // Structs that have non-trivial constructors or destructors are required.
6534 // FIXME: Handle references.
6535 // FIXME: Be more selective about which constructors we care about.
6536 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6537 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6538 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6539 RD->hasTrivialCopyConstructor() &&
6540 RD->hasTrivialMoveConstructor() &&
6541 RD->hasTrivialDestructor()))
6546 GVALinkage L = GetGVALinkageForVariable(VD);
6547 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6548 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6555 CallingConv ASTContext::getDefaultMethodCallConv() {
6556 // Pass through to the C++ ABI object
6557 return ABI->getDefaultMethodCallConv();
6560 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6561 // Pass through to the C++ ABI object
6562 return ABI->isNearlyEmpty(RD);
6565 MangleContext *ASTContext::createMangleContext() {
6566 switch (Target->getCXXABI()) {
6568 case CXXABI_Itanium:
6569 return createItaniumMangleContext(*this, getDiagnostics());
6570 case CXXABI_Microsoft:
6571 return createMicrosoftMangleContext(*this, getDiagnostics());
6573 llvm_unreachable("Unsupported ABI");
6576 CXXABI::~CXXABI() {}
6578 size_t ASTContext::getSideTableAllocatedMemory() const {
6579 return ASTRecordLayouts.getMemorySize()
6580 + llvm::capacity_in_bytes(ObjCLayouts)
6581 + llvm::capacity_in_bytes(KeyFunctions)
6582 + llvm::capacity_in_bytes(ObjCImpls)
6583 + llvm::capacity_in_bytes(BlockVarCopyInits)
6584 + llvm::capacity_in_bytes(DeclAttrs)
6585 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6586 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6587 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6588 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6589 + llvm::capacity_in_bytes(OverriddenMethods)
6590 + llvm::capacity_in_bytes(Types)
6591 + llvm::capacity_in_bytes(VariableArrayTypes)
6592 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
6595 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6596 ParamIndices[D] = index;
6599 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6600 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6601 assert(I != ParamIndices.end() &&
6602 "ParmIndices lacks entry set by ParmVarDecl");