ASTContext.cpp revision 4923aa25eb39d64106a5817c02d560a3aecf8b2c
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the ASTContext interface. 11// 12//===----------------------------------------------------------------------===// 13 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/RecordLayout.h" 24#include "clang/Basic/Builtins.h" 25#include "clang/Basic/SourceManager.h" 26#include "clang/Basic/TargetInfo.h" 27#include "llvm/ADT/SmallString.h" 28#include "llvm/ADT/StringExtras.h" 29#include "llvm/Support/MathExtras.h" 30#include "llvm/Support/raw_ostream.h" 31 32using namespace clang; 33 34unsigned ASTContext::NumImplicitDestructors; 35unsigned ASTContext::NumImplicitDestructorsDeclared; 36 37enum FloatingRank { 38 FloatRank, DoubleRank, LongDoubleRank 39}; 40 41void 42ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 43 TemplateTemplateParmDecl *Parm) { 44 ID.AddInteger(Parm->getDepth()); 45 ID.AddInteger(Parm->getPosition()); 46 // FIXME: Parameter pack 47 48 TemplateParameterList *Params = Parm->getTemplateParameters(); 49 ID.AddInteger(Params->size()); 50 for (TemplateParameterList::const_iterator P = Params->begin(), 51 PEnd = Params->end(); 52 P != PEnd; ++P) { 53 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 54 ID.AddInteger(0); 55 ID.AddBoolean(TTP->isParameterPack()); 56 continue; 57 } 58 59 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 60 ID.AddInteger(1); 61 // FIXME: Parameter pack 62 ID.AddPointer(NTTP->getType().getAsOpaquePtr()); 63 continue; 64 } 65 66 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 67 ID.AddInteger(2); 68 Profile(ID, TTP); 69 } 70} 71 72TemplateTemplateParmDecl * 73ASTContext::getCanonicalTemplateTemplateParmDecl( 74 TemplateTemplateParmDecl *TTP) { 75 // Check if we already have a canonical template template parameter. 76 llvm::FoldingSetNodeID ID; 77 CanonicalTemplateTemplateParm::Profile(ID, TTP); 78 void *InsertPos = 0; 79 CanonicalTemplateTemplateParm *Canonical 80 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 81 if (Canonical) 82 return Canonical->getParam(); 83 84 // Build a canonical template parameter list. 85 TemplateParameterList *Params = TTP->getTemplateParameters(); 86 llvm::SmallVector<NamedDecl *, 4> CanonParams; 87 CanonParams.reserve(Params->size()); 88 for (TemplateParameterList::const_iterator P = Params->begin(), 89 PEnd = Params->end(); 90 P != PEnd; ++P) { 91 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 92 CanonParams.push_back( 93 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 94 SourceLocation(), TTP->getDepth(), 95 TTP->getIndex(), 0, false, 96 TTP->isParameterPack())); 97 else if (NonTypeTemplateParmDecl *NTTP 98 = dyn_cast<NonTypeTemplateParmDecl>(*P)) 99 CanonParams.push_back( 100 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 101 SourceLocation(), NTTP->getDepth(), 102 NTTP->getPosition(), 0, 103 getCanonicalType(NTTP->getType()), 104 0)); 105 else 106 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 107 cast<TemplateTemplateParmDecl>(*P))); 108 } 109 110 TemplateTemplateParmDecl *CanonTTP 111 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 112 SourceLocation(), TTP->getDepth(), 113 TTP->getPosition(), 0, 114 TemplateParameterList::Create(*this, SourceLocation(), 115 SourceLocation(), 116 CanonParams.data(), 117 CanonParams.size(), 118 SourceLocation())); 119 120 // Get the new insert position for the node we care about. 121 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 122 assert(Canonical == 0 && "Shouldn't be in the map!"); 123 (void)Canonical; 124 125 // Create the canonical template template parameter entry. 126 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 127 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 128 return CanonTTP; 129} 130 131ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 132 const TargetInfo &t, 133 IdentifierTable &idents, SelectorTable &sels, 134 Builtin::Context &builtins, 135 bool FreeMem, unsigned size_reserve) : 136 TemplateSpecializationTypes(this_()), 137 DependentTemplateSpecializationTypes(this_()), 138 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), 139 NSConstantStringTypeDecl(0), 140 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0), 141 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0), 142 NullTypeSourceInfo(QualType()), 143 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t), 144 Idents(idents), Selectors(sels), 145 BuiltinInfo(builtins), 146 DeclarationNames(*this), 147 ExternalSource(0), PrintingPolicy(LOpts), 148 LastSDM(0, 0), 149 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) { 150 ObjCIdRedefinitionType = QualType(); 151 ObjCClassRedefinitionType = QualType(); 152 ObjCSelRedefinitionType = QualType(); 153 if (size_reserve > 0) Types.reserve(size_reserve); 154 TUDecl = TranslationUnitDecl::Create(*this); 155 InitBuiltinTypes(); 156} 157 158ASTContext::~ASTContext() { 159 // Release the DenseMaps associated with DeclContext objects. 160 // FIXME: Is this the ideal solution? 161 ReleaseDeclContextMaps(); 162 163 if (!FreeMemory) { 164 // Call all of the deallocation functions. 165 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 166 Deallocations[I].first(Deallocations[I].second); 167 } 168 169 // Release all of the memory associated with overridden C++ methods. 170 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator 171 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end(); 172 OM != OMEnd; ++OM) 173 OM->second.Destroy(); 174 175 if (FreeMemory) { 176 // Deallocate all the types. 177 while (!Types.empty()) { 178 Types.back()->Destroy(*this); 179 Types.pop_back(); 180 } 181 182 for (llvm::FoldingSet<ExtQuals>::iterator 183 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) { 184 // Increment in loop to prevent using deallocated memory. 185 Deallocate(&*I++); 186 } 187 188 for (llvm::DenseMap<const ObjCContainerDecl*, 189 const ASTRecordLayout*>::iterator 190 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) { 191 // Increment in loop to prevent using deallocated memory. 192 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 193 R->Destroy(*this); 194 } 195 } 196 197 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 198 // even when using the BumpPtrAllocator because they can contain 199 // DenseMaps. 200 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 201 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 202 // Increment in loop to prevent using deallocated memory. 203 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 204 R->Destroy(*this); 205 } 206 207 // Destroy nested-name-specifiers. 208 for (llvm::FoldingSet<NestedNameSpecifier>::iterator 209 NNS = NestedNameSpecifiers.begin(), 210 NNSEnd = NestedNameSpecifiers.end(); 211 NNS != NNSEnd; ) { 212 // Increment in loop to prevent using deallocated memory. 213 (*NNS++).Destroy(*this); 214 } 215 216 if (GlobalNestedNameSpecifier) 217 GlobalNestedNameSpecifier->Destroy(*this); 218 219 TUDecl->Destroy(*this); 220} 221 222void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 223 Deallocations.push_back(std::make_pair(Callback, Data)); 224} 225 226void 227ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 228 ExternalSource.reset(Source.take()); 229} 230 231void ASTContext::PrintStats() const { 232 fprintf(stderr, "*** AST Context Stats:\n"); 233 fprintf(stderr, " %d types total.\n", (int)Types.size()); 234 235 unsigned counts[] = { 236#define TYPE(Name, Parent) 0, 237#define ABSTRACT_TYPE(Name, Parent) 238#include "clang/AST/TypeNodes.def" 239 0 // Extra 240 }; 241 242 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 243 Type *T = Types[i]; 244 counts[(unsigned)T->getTypeClass()]++; 245 } 246 247 unsigned Idx = 0; 248 unsigned TotalBytes = 0; 249#define TYPE(Name, Parent) \ 250 if (counts[Idx]) \ 251 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 252 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 253 ++Idx; 254#define ABSTRACT_TYPE(Name, Parent) 255#include "clang/AST/TypeNodes.def" 256 257 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 258 259 // Implicit special member functions. 260 fprintf(stderr, " %u/%u implicit destructors created\n", 261 NumImplicitDestructorsDeclared, NumImplicitDestructors); 262 263 if (ExternalSource.get()) { 264 fprintf(stderr, "\n"); 265 ExternalSource->PrintStats(); 266 } 267} 268 269 270void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 271 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 272 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 273 Types.push_back(Ty); 274} 275 276void ASTContext::InitBuiltinTypes() { 277 assert(VoidTy.isNull() && "Context reinitialized?"); 278 279 // C99 6.2.5p19. 280 InitBuiltinType(VoidTy, BuiltinType::Void); 281 282 // C99 6.2.5p2. 283 InitBuiltinType(BoolTy, BuiltinType::Bool); 284 // C99 6.2.5p3. 285 if (LangOpts.CharIsSigned) 286 InitBuiltinType(CharTy, BuiltinType::Char_S); 287 else 288 InitBuiltinType(CharTy, BuiltinType::Char_U); 289 // C99 6.2.5p4. 290 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 291 InitBuiltinType(ShortTy, BuiltinType::Short); 292 InitBuiltinType(IntTy, BuiltinType::Int); 293 InitBuiltinType(LongTy, BuiltinType::Long); 294 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 295 296 // C99 6.2.5p6. 297 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 298 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 299 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 300 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 301 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 302 303 // C99 6.2.5p10. 304 InitBuiltinType(FloatTy, BuiltinType::Float); 305 InitBuiltinType(DoubleTy, BuiltinType::Double); 306 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 307 308 // GNU extension, 128-bit integers. 309 InitBuiltinType(Int128Ty, BuiltinType::Int128); 310 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 311 312 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 313 InitBuiltinType(WCharTy, BuiltinType::WChar); 314 else // C99 315 WCharTy = getFromTargetType(Target.getWCharType()); 316 317 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 318 InitBuiltinType(Char16Ty, BuiltinType::Char16); 319 else // C99 320 Char16Ty = getFromTargetType(Target.getChar16Type()); 321 322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 323 InitBuiltinType(Char32Ty, BuiltinType::Char32); 324 else // C99 325 Char32Ty = getFromTargetType(Target.getChar32Type()); 326 327 // Placeholder type for functions. 328 InitBuiltinType(OverloadTy, BuiltinType::Overload); 329 330 // Placeholder type for type-dependent expressions whose type is 331 // completely unknown. No code should ever check a type against 332 // DependentTy and users should never see it; however, it is here to 333 // help diagnose failures to properly check for type-dependent 334 // expressions. 335 InitBuiltinType(DependentTy, BuiltinType::Dependent); 336 337 // Placeholder type for C++0x auto declarations whose real type has 338 // not yet been deduced. 339 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); 340 341 // C99 6.2.5p11. 342 FloatComplexTy = getComplexType(FloatTy); 343 DoubleComplexTy = getComplexType(DoubleTy); 344 LongDoubleComplexTy = getComplexType(LongDoubleTy); 345 346 BuiltinVaListType = QualType(); 347 348 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope(). 349 ObjCIdTypedefType = QualType(); 350 ObjCClassTypedefType = QualType(); 351 ObjCSelTypedefType = QualType(); 352 353 // Builtin types for 'id', 'Class', and 'SEL'. 354 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 355 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 356 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 357 358 ObjCConstantStringType = QualType(); 359 360 // void * type 361 VoidPtrTy = getPointerType(VoidTy); 362 363 // nullptr type (C++0x 2.14.7) 364 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 365} 366 367MemberSpecializationInfo * 368ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 369 assert(Var->isStaticDataMember() && "Not a static data member"); 370 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 371 = InstantiatedFromStaticDataMember.find(Var); 372 if (Pos == InstantiatedFromStaticDataMember.end()) 373 return 0; 374 375 return Pos->second; 376} 377 378void 379ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 380 TemplateSpecializationKind TSK) { 381 assert(Inst->isStaticDataMember() && "Not a static data member"); 382 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 383 assert(!InstantiatedFromStaticDataMember[Inst] && 384 "Already noted what static data member was instantiated from"); 385 InstantiatedFromStaticDataMember[Inst] 386 = new (*this) MemberSpecializationInfo(Tmpl, TSK); 387} 388 389NamedDecl * 390ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 391 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 392 = InstantiatedFromUsingDecl.find(UUD); 393 if (Pos == InstantiatedFromUsingDecl.end()) 394 return 0; 395 396 return Pos->second; 397} 398 399void 400ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 401 assert((isa<UsingDecl>(Pattern) || 402 isa<UnresolvedUsingValueDecl>(Pattern) || 403 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 404 "pattern decl is not a using decl"); 405 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 406 InstantiatedFromUsingDecl[Inst] = Pattern; 407} 408 409UsingShadowDecl * 410ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 411 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 412 = InstantiatedFromUsingShadowDecl.find(Inst); 413 if (Pos == InstantiatedFromUsingShadowDecl.end()) 414 return 0; 415 416 return Pos->second; 417} 418 419void 420ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 421 UsingShadowDecl *Pattern) { 422 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 423 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 424} 425 426FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 427 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 428 = InstantiatedFromUnnamedFieldDecl.find(Field); 429 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 430 return 0; 431 432 return Pos->second; 433} 434 435void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 436 FieldDecl *Tmpl) { 437 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 438 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 439 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 440 "Already noted what unnamed field was instantiated from"); 441 442 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 443} 444 445ASTContext::overridden_cxx_method_iterator 446ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 447 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 448 = OverriddenMethods.find(Method); 449 if (Pos == OverriddenMethods.end()) 450 return 0; 451 452 return Pos->second.begin(); 453} 454 455ASTContext::overridden_cxx_method_iterator 456ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 457 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 458 = OverriddenMethods.find(Method); 459 if (Pos == OverriddenMethods.end()) 460 return 0; 461 462 return Pos->second.end(); 463} 464 465void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 466 const CXXMethodDecl *Overridden) { 467 OverriddenMethods[Method].push_back(Overridden); 468} 469 470namespace { 471 class BeforeInTranslationUnit 472 : std::binary_function<SourceRange, SourceRange, bool> { 473 SourceManager *SourceMgr; 474 475 public: 476 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { } 477 478 bool operator()(SourceRange X, SourceRange Y) { 479 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin()); 480 } 481 }; 482} 483 484//===----------------------------------------------------------------------===// 485// Type Sizing and Analysis 486//===----------------------------------------------------------------------===// 487 488/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 489/// scalar floating point type. 490const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 491 const BuiltinType *BT = T->getAs<BuiltinType>(); 492 assert(BT && "Not a floating point type!"); 493 switch (BT->getKind()) { 494 default: assert(0 && "Not a floating point type!"); 495 case BuiltinType::Float: return Target.getFloatFormat(); 496 case BuiltinType::Double: return Target.getDoubleFormat(); 497 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 498 } 499} 500 501/// getDeclAlign - Return a conservative estimate of the alignment of the 502/// specified decl. Note that bitfields do not have a valid alignment, so 503/// this method will assert on them. 504/// If @p RefAsPointee, references are treated like their underlying type 505/// (for alignof), else they're treated like pointers (for CodeGen). 506CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) { 507 unsigned Align = Target.getCharWidth(); 508 509 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) 510 Align = std::max(Align, AA->getMaxAlignment()); 511 512 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 513 QualType T = VD->getType(); 514 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 515 if (RefAsPointee) 516 T = RT->getPointeeType(); 517 else 518 T = getPointerType(RT->getPointeeType()); 519 } 520 if (!T->isIncompleteType() && !T->isFunctionType()) { 521 unsigned MinWidth = Target.getLargeArrayMinWidth(); 522 unsigned ArrayAlign = Target.getLargeArrayAlign(); 523 if (isa<VariableArrayType>(T) && MinWidth != 0) 524 Align = std::max(Align, ArrayAlign); 525 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) { 526 unsigned Size = getTypeSize(CT); 527 if (MinWidth != 0 && MinWidth <= Size) 528 Align = std::max(Align, ArrayAlign); 529 } 530 // Incomplete or function types default to 1. 531 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 532 T = cast<ArrayType>(T)->getElementType(); 533 534 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 535 } 536 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 537 // In the case of a field in a packed struct, we want the minimum 538 // of the alignment of the field and the alignment of the struct. 539 Align = std::min(Align, 540 getPreferredTypeAlign(FD->getParent()->getTypeForDecl())); 541 } 542 } 543 544 return CharUnits::fromQuantity(Align / Target.getCharWidth()); 545} 546 547std::pair<CharUnits, CharUnits> 548ASTContext::getTypeInfoInChars(const Type *T) { 549 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 550 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()), 551 CharUnits::fromQuantity(Info.second / getCharWidth())); 552} 553 554std::pair<CharUnits, CharUnits> 555ASTContext::getTypeInfoInChars(QualType T) { 556 return getTypeInfoInChars(T.getTypePtr()); 557} 558 559/// getTypeSize - Return the size of the specified type, in bits. This method 560/// does not work on incomplete types. 561/// 562/// FIXME: Pointers into different addr spaces could have different sizes and 563/// alignment requirements: getPointerInfo should take an AddrSpace, this 564/// should take a QualType, &c. 565std::pair<uint64_t, unsigned> 566ASTContext::getTypeInfo(const Type *T) { 567 uint64_t Width=0; 568 unsigned Align=8; 569 switch (T->getTypeClass()) { 570#define TYPE(Class, Base) 571#define ABSTRACT_TYPE(Class, Base) 572#define NON_CANONICAL_TYPE(Class, Base) 573#define DEPENDENT_TYPE(Class, Base) case Type::Class: 574#include "clang/AST/TypeNodes.def" 575 assert(false && "Should not see dependent types"); 576 break; 577 578 case Type::FunctionNoProto: 579 case Type::FunctionProto: 580 // GCC extension: alignof(function) = 32 bits 581 Width = 0; 582 Align = 32; 583 break; 584 585 case Type::IncompleteArray: 586 case Type::VariableArray: 587 Width = 0; 588 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 589 break; 590 591 case Type::ConstantArray: { 592 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 593 594 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 595 Width = EltInfo.first*CAT->getSize().getZExtValue(); 596 Align = EltInfo.second; 597 break; 598 } 599 case Type::ExtVector: 600 case Type::Vector: { 601 const VectorType *VT = cast<VectorType>(T); 602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 603 Width = EltInfo.first*VT->getNumElements(); 604 Align = Width; 605 // If the alignment is not a power of 2, round up to the next power of 2. 606 // This happens for non-power-of-2 length vectors. 607 if (Align & (Align-1)) { 608 Align = llvm::NextPowerOf2(Align); 609 Width = llvm::RoundUpToAlignment(Width, Align); 610 } 611 break; 612 } 613 614 case Type::Builtin: 615 switch (cast<BuiltinType>(T)->getKind()) { 616 default: assert(0 && "Unknown builtin type!"); 617 case BuiltinType::Void: 618 // GCC extension: alignof(void) = 8 bits. 619 Width = 0; 620 Align = 8; 621 break; 622 623 case BuiltinType::Bool: 624 Width = Target.getBoolWidth(); 625 Align = Target.getBoolAlign(); 626 break; 627 case BuiltinType::Char_S: 628 case BuiltinType::Char_U: 629 case BuiltinType::UChar: 630 case BuiltinType::SChar: 631 Width = Target.getCharWidth(); 632 Align = Target.getCharAlign(); 633 break; 634 case BuiltinType::WChar: 635 Width = Target.getWCharWidth(); 636 Align = Target.getWCharAlign(); 637 break; 638 case BuiltinType::Char16: 639 Width = Target.getChar16Width(); 640 Align = Target.getChar16Align(); 641 break; 642 case BuiltinType::Char32: 643 Width = Target.getChar32Width(); 644 Align = Target.getChar32Align(); 645 break; 646 case BuiltinType::UShort: 647 case BuiltinType::Short: 648 Width = Target.getShortWidth(); 649 Align = Target.getShortAlign(); 650 break; 651 case BuiltinType::UInt: 652 case BuiltinType::Int: 653 Width = Target.getIntWidth(); 654 Align = Target.getIntAlign(); 655 break; 656 case BuiltinType::ULong: 657 case BuiltinType::Long: 658 Width = Target.getLongWidth(); 659 Align = Target.getLongAlign(); 660 break; 661 case BuiltinType::ULongLong: 662 case BuiltinType::LongLong: 663 Width = Target.getLongLongWidth(); 664 Align = Target.getLongLongAlign(); 665 break; 666 case BuiltinType::Int128: 667 case BuiltinType::UInt128: 668 Width = 128; 669 Align = 128; // int128_t is 128-bit aligned on all targets. 670 break; 671 case BuiltinType::Float: 672 Width = Target.getFloatWidth(); 673 Align = Target.getFloatAlign(); 674 break; 675 case BuiltinType::Double: 676 Width = Target.getDoubleWidth(); 677 Align = Target.getDoubleAlign(); 678 break; 679 case BuiltinType::LongDouble: 680 Width = Target.getLongDoubleWidth(); 681 Align = Target.getLongDoubleAlign(); 682 break; 683 case BuiltinType::NullPtr: 684 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 685 Align = Target.getPointerAlign(0); // == sizeof(void*) 686 break; 687 } 688 break; 689 case Type::ObjCObjectPointer: 690 Width = Target.getPointerWidth(0); 691 Align = Target.getPointerAlign(0); 692 break; 693 case Type::BlockPointer: { 694 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 695 Width = Target.getPointerWidth(AS); 696 Align = Target.getPointerAlign(AS); 697 break; 698 } 699 case Type::LValueReference: 700 case Type::RValueReference: { 701 // alignof and sizeof should never enter this code path here, so we go 702 // the pointer route. 703 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace(); 704 Width = Target.getPointerWidth(AS); 705 Align = Target.getPointerAlign(AS); 706 break; 707 } 708 case Type::Pointer: { 709 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 710 Width = Target.getPointerWidth(AS); 711 Align = Target.getPointerAlign(AS); 712 break; 713 } 714 case Type::MemberPointer: { 715 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 716 std::pair<uint64_t, unsigned> PtrDiffInfo = 717 getTypeInfo(getPointerDiffType()); 718 Width = PtrDiffInfo.first; 719 if (Pointee->isFunctionType()) 720 Width *= 2; 721 Align = PtrDiffInfo.second; 722 break; 723 } 724 case Type::Complex: { 725 // Complex types have the same alignment as their elements, but twice the 726 // size. 727 std::pair<uint64_t, unsigned> EltInfo = 728 getTypeInfo(cast<ComplexType>(T)->getElementType()); 729 Width = EltInfo.first*2; 730 Align = EltInfo.second; 731 break; 732 } 733 case Type::ObjCObject: 734 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 735 case Type::ObjCInterface: { 736 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 737 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 738 Width = Layout.getSize(); 739 Align = Layout.getAlignment(); 740 break; 741 } 742 case Type::Record: 743 case Type::Enum: { 744 const TagType *TT = cast<TagType>(T); 745 746 if (TT->getDecl()->isInvalidDecl()) { 747 Width = 1; 748 Align = 1; 749 break; 750 } 751 752 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 753 return getTypeInfo(ET->getDecl()->getIntegerType()); 754 755 const RecordType *RT = cast<RecordType>(TT); 756 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 757 Width = Layout.getSize(); 758 Align = Layout.getAlignment(); 759 break; 760 } 761 762 case Type::SubstTemplateTypeParm: 763 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 764 getReplacementType().getTypePtr()); 765 766 case Type::Typedef: { 767 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 768 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) { 769 Align = std::max(Aligned->getMaxAlignment(), 770 getTypeAlign(Typedef->getUnderlyingType().getTypePtr())); 771 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr()); 772 } else 773 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 774 break; 775 } 776 777 case Type::TypeOfExpr: 778 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 779 .getTypePtr()); 780 781 case Type::TypeOf: 782 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 783 784 case Type::Decltype: 785 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 786 .getTypePtr()); 787 788 case Type::Elaborated: 789 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 790 791 case Type::TemplateSpecialization: 792 assert(getCanonicalType(T) != T && 793 "Cannot request the size of a dependent type"); 794 // FIXME: this is likely to be wrong once we support template 795 // aliases, since a template alias could refer to a typedef that 796 // has an __aligned__ attribute on it. 797 return getTypeInfo(getCanonicalType(T)); 798 } 799 800 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 801 return std::make_pair(Width, Align); 802} 803 804/// getTypeSizeInChars - Return the size of the specified type, in characters. 805/// This method does not work on incomplete types. 806CharUnits ASTContext::getTypeSizeInChars(QualType T) { 807 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 808} 809CharUnits ASTContext::getTypeSizeInChars(const Type *T) { 810 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 811} 812 813/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 814/// characters. This method does not work on incomplete types. 815CharUnits ASTContext::getTypeAlignInChars(QualType T) { 816 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 817} 818CharUnits ASTContext::getTypeAlignInChars(const Type *T) { 819 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 820} 821 822/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 823/// type for the current target in bits. This can be different than the ABI 824/// alignment in cases where it is beneficial for performance to overalign 825/// a data type. 826unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 827 unsigned ABIAlign = getTypeAlign(T); 828 829 // Double and long long should be naturally aligned if possible. 830 if (const ComplexType* CT = T->getAs<ComplexType>()) 831 T = CT->getElementType().getTypePtr(); 832 if (T->isSpecificBuiltinType(BuiltinType::Double) || 833 T->isSpecificBuiltinType(BuiltinType::LongLong)) 834 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 835 836 return ABIAlign; 837} 838 839static void CollectLocalObjCIvars(ASTContext *Ctx, 840 const ObjCInterfaceDecl *OI, 841 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 842 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 843 E = OI->ivar_end(); I != E; ++I) { 844 ObjCIvarDecl *IVDecl = *I; 845 if (!IVDecl->isInvalidDecl()) 846 Fields.push_back(cast<FieldDecl>(IVDecl)); 847 } 848} 849 850void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI, 851 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 852 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 853 CollectObjCIvars(SuperClass, Fields); 854 CollectLocalObjCIvars(this, OI, Fields); 855} 856 857/// ShallowCollectObjCIvars - 858/// Collect all ivars, including those synthesized, in the current class. 859/// 860void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 861 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 862 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 863 E = OI->ivar_end(); I != E; ++I) { 864 Ivars.push_back(*I); 865 } 866 867 CollectNonClassIvars(OI, Ivars); 868} 869 870/// CollectNonClassIvars - 871/// This routine collects all other ivars which are not declared in the class. 872/// This includes synthesized ivars (via @synthesize) and those in 873// class's @implementation. 874/// 875void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI, 876 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 877 // Find ivars declared in class extension. 878 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 879 CDecl = CDecl->getNextClassExtension()) { 880 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(), 881 E = CDecl->ivar_end(); I != E; ++I) { 882 Ivars.push_back(*I); 883 } 884 } 885 886 // Also add any ivar defined in this class's implementation. This 887 // includes synthesized ivars. 888 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) { 889 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(), 890 E = ImplDecl->ivar_end(); I != E; ++I) 891 Ivars.push_back(*I); 892 } 893} 894 895/// CollectInheritedProtocols - Collect all protocols in current class and 896/// those inherited by it. 897void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 898 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 899 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 900 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 901 PE = OI->protocol_end(); P != PE; ++P) { 902 ObjCProtocolDecl *Proto = (*P); 903 Protocols.insert(Proto); 904 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 905 PE = Proto->protocol_end(); P != PE; ++P) { 906 Protocols.insert(*P); 907 CollectInheritedProtocols(*P, Protocols); 908 } 909 } 910 911 // Categories of this Interface. 912 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 913 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 914 CollectInheritedProtocols(CDeclChain, Protocols); 915 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 916 while (SD) { 917 CollectInheritedProtocols(SD, Protocols); 918 SD = SD->getSuperClass(); 919 } 920 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 921 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(), 922 PE = OC->protocol_end(); P != PE; ++P) { 923 ObjCProtocolDecl *Proto = (*P); 924 Protocols.insert(Proto); 925 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 926 PE = Proto->protocol_end(); P != PE; ++P) 927 CollectInheritedProtocols(*P, Protocols); 928 } 929 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 930 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 931 PE = OP->protocol_end(); P != PE; ++P) { 932 ObjCProtocolDecl *Proto = (*P); 933 Protocols.insert(Proto); 934 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 935 PE = Proto->protocol_end(); P != PE; ++P) 936 CollectInheritedProtocols(*P, Protocols); 937 } 938 } 939} 940 941unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) { 942 unsigned count = 0; 943 // Count ivars declared in class extension. 944 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 945 CDecl = CDecl->getNextClassExtension()) 946 count += CDecl->ivar_size(); 947 948 // Count ivar defined in this class's implementation. This 949 // includes synthesized ivars. 950 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 951 count += ImplDecl->ivar_size(); 952 953 return count; 954} 955 956/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 957ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 958 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 959 I = ObjCImpls.find(D); 960 if (I != ObjCImpls.end()) 961 return cast<ObjCImplementationDecl>(I->second); 962 return 0; 963} 964/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 965ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 966 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 967 I = ObjCImpls.find(D); 968 if (I != ObjCImpls.end()) 969 return cast<ObjCCategoryImplDecl>(I->second); 970 return 0; 971} 972 973/// \brief Set the implementation of ObjCInterfaceDecl. 974void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 975 ObjCImplementationDecl *ImplD) { 976 assert(IFaceD && ImplD && "Passed null params"); 977 ObjCImpls[IFaceD] = ImplD; 978} 979/// \brief Set the implementation of ObjCCategoryDecl. 980void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 981 ObjCCategoryImplDecl *ImplD) { 982 assert(CatD && ImplD && "Passed null params"); 983 ObjCImpls[CatD] = ImplD; 984} 985 986/// \brief Allocate an uninitialized TypeSourceInfo. 987/// 988/// The caller should initialize the memory held by TypeSourceInfo using 989/// the TypeLoc wrappers. 990/// 991/// \param T the type that will be the basis for type source info. This type 992/// should refer to how the declarator was written in source code, not to 993/// what type semantic analysis resolved the declarator to. 994TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 995 unsigned DataSize) { 996 if (!DataSize) 997 DataSize = TypeLoc::getFullDataSizeForType(T); 998 else 999 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1000 "incorrect data size provided to CreateTypeSourceInfo!"); 1001 1002 TypeSourceInfo *TInfo = 1003 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1004 new (TInfo) TypeSourceInfo(T); 1005 return TInfo; 1006} 1007 1008TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1009 SourceLocation L) { 1010 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1011 DI->getTypeLoc().initialize(L); 1012 return DI; 1013} 1014 1015const ASTRecordLayout & 1016ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 1017 return getObjCLayout(D, 0); 1018} 1019 1020const ASTRecordLayout & 1021ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 1022 return getObjCLayout(D->getClassInterface(), D); 1023} 1024 1025//===----------------------------------------------------------------------===// 1026// Type creation/memoization methods 1027//===----------------------------------------------------------------------===// 1028 1029QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) { 1030 unsigned Fast = Quals.getFastQualifiers(); 1031 Quals.removeFastQualifiers(); 1032 1033 // Check if we've already instantiated this type. 1034 llvm::FoldingSetNodeID ID; 1035 ExtQuals::Profile(ID, TypeNode, Quals); 1036 void *InsertPos = 0; 1037 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) { 1038 assert(EQ->getQualifiers() == Quals); 1039 QualType T = QualType(EQ, Fast); 1040 return T; 1041 } 1042 1043 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals); 1044 ExtQualNodes.InsertNode(New, InsertPos); 1045 QualType T = QualType(New, Fast); 1046 return T; 1047} 1048 1049QualType ASTContext::getVolatileType(QualType T) { 1050 QualType CanT = getCanonicalType(T); 1051 if (CanT.isVolatileQualified()) return T; 1052 1053 QualifierCollector Quals; 1054 const Type *TypeNode = Quals.strip(T); 1055 Quals.addVolatile(); 1056 1057 return getExtQualType(TypeNode, Quals); 1058} 1059 1060QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 1061 QualType CanT = getCanonicalType(T); 1062 if (CanT.getAddressSpace() == AddressSpace) 1063 return T; 1064 1065 // If we are composing extended qualifiers together, merge together 1066 // into one ExtQuals node. 1067 QualifierCollector Quals; 1068 const Type *TypeNode = Quals.strip(T); 1069 1070 // If this type already has an address space specified, it cannot get 1071 // another one. 1072 assert(!Quals.hasAddressSpace() && 1073 "Type cannot be in multiple addr spaces!"); 1074 Quals.addAddressSpace(AddressSpace); 1075 1076 return getExtQualType(TypeNode, Quals); 1077} 1078 1079QualType ASTContext::getObjCGCQualType(QualType T, 1080 Qualifiers::GC GCAttr) { 1081 QualType CanT = getCanonicalType(T); 1082 if (CanT.getObjCGCAttr() == GCAttr) 1083 return T; 1084 1085 if (T->isPointerType()) { 1086 QualType Pointee = T->getAs<PointerType>()->getPointeeType(); 1087 if (Pointee->isAnyPointerType()) { 1088 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1089 return getPointerType(ResultType); 1090 } 1091 } 1092 1093 // If we are composing extended qualifiers together, merge together 1094 // into one ExtQuals node. 1095 QualifierCollector Quals; 1096 const Type *TypeNode = Quals.strip(T); 1097 1098 // If this type already has an ObjCGC specified, it cannot get 1099 // another one. 1100 assert(!Quals.hasObjCGCAttr() && 1101 "Type cannot have multiple ObjCGCs!"); 1102 Quals.addObjCGCAttr(GCAttr); 1103 1104 return getExtQualType(TypeNode, Quals); 1105} 1106 1107static QualType getExtFunctionType(ASTContext& Context, QualType T, 1108 const FunctionType::ExtInfo &Info) { 1109 QualType ResultType; 1110 if (const PointerType *Pointer = T->getAs<PointerType>()) { 1111 QualType Pointee = Pointer->getPointeeType(); 1112 ResultType = getExtFunctionType(Context, Pointee, Info); 1113 if (ResultType == Pointee) 1114 return T; 1115 1116 ResultType = Context.getPointerType(ResultType); 1117 } else if (const BlockPointerType *BlockPointer 1118 = T->getAs<BlockPointerType>()) { 1119 QualType Pointee = BlockPointer->getPointeeType(); 1120 ResultType = getExtFunctionType(Context, Pointee, Info); 1121 if (ResultType == Pointee) 1122 return T; 1123 1124 ResultType = Context.getBlockPointerType(ResultType); 1125 } else if (const FunctionType *F = T->getAs<FunctionType>()) { 1126 if (F->getExtInfo() == Info) 1127 return T; 1128 1129 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) { 1130 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(), 1131 Info); 1132 } else { 1133 const FunctionProtoType *FPT = cast<FunctionProtoType>(F); 1134 ResultType 1135 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1136 FPT->getNumArgs(), FPT->isVariadic(), 1137 FPT->getTypeQuals(), 1138 FPT->hasExceptionSpec(), 1139 FPT->hasAnyExceptionSpec(), 1140 FPT->getNumExceptions(), 1141 FPT->exception_begin(), 1142 Info); 1143 } 1144 } else 1145 return T; 1146 1147 return Context.getQualifiedType(ResultType, T.getLocalQualifiers()); 1148} 1149 1150QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) { 1151 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1152 return getExtFunctionType(*this, T, 1153 Info.withNoReturn(AddNoReturn)); 1154} 1155 1156QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) { 1157 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1158 return getExtFunctionType(*this, T, 1159 Info.withCallingConv(CallConv)); 1160} 1161 1162QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) { 1163 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1164 return getExtFunctionType(*this, T, 1165 Info.withRegParm(RegParm)); 1166} 1167 1168/// getComplexType - Return the uniqued reference to the type for a complex 1169/// number with the specified element type. 1170QualType ASTContext::getComplexType(QualType T) { 1171 // Unique pointers, to guarantee there is only one pointer of a particular 1172 // structure. 1173 llvm::FoldingSetNodeID ID; 1174 ComplexType::Profile(ID, T); 1175 1176 void *InsertPos = 0; 1177 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1178 return QualType(CT, 0); 1179 1180 // If the pointee type isn't canonical, this won't be a canonical type either, 1181 // so fill in the canonical type field. 1182 QualType Canonical; 1183 if (!T.isCanonical()) { 1184 Canonical = getComplexType(getCanonicalType(T)); 1185 1186 // Get the new insert position for the node we care about. 1187 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1188 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1189 } 1190 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1191 Types.push_back(New); 1192 ComplexTypes.InsertNode(New, InsertPos); 1193 return QualType(New, 0); 1194} 1195 1196/// getPointerType - Return the uniqued reference to the type for a pointer to 1197/// the specified type. 1198QualType ASTContext::getPointerType(QualType T) { 1199 // Unique pointers, to guarantee there is only one pointer of a particular 1200 // structure. 1201 llvm::FoldingSetNodeID ID; 1202 PointerType::Profile(ID, T); 1203 1204 void *InsertPos = 0; 1205 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1206 return QualType(PT, 0); 1207 1208 // If the pointee type isn't canonical, this won't be a canonical type either, 1209 // so fill in the canonical type field. 1210 QualType Canonical; 1211 if (!T.isCanonical()) { 1212 Canonical = getPointerType(getCanonicalType(T)); 1213 1214 // Get the new insert position for the node we care about. 1215 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1216 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1217 } 1218 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1219 Types.push_back(New); 1220 PointerTypes.InsertNode(New, InsertPos); 1221 return QualType(New, 0); 1222} 1223 1224/// getBlockPointerType - Return the uniqued reference to the type for 1225/// a pointer to the specified block. 1226QualType ASTContext::getBlockPointerType(QualType T) { 1227 assert(T->isFunctionType() && "block of function types only"); 1228 // Unique pointers, to guarantee there is only one block of a particular 1229 // structure. 1230 llvm::FoldingSetNodeID ID; 1231 BlockPointerType::Profile(ID, T); 1232 1233 void *InsertPos = 0; 1234 if (BlockPointerType *PT = 1235 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1236 return QualType(PT, 0); 1237 1238 // If the block pointee type isn't canonical, this won't be a canonical 1239 // type either so fill in the canonical type field. 1240 QualType Canonical; 1241 if (!T.isCanonical()) { 1242 Canonical = getBlockPointerType(getCanonicalType(T)); 1243 1244 // Get the new insert position for the node we care about. 1245 BlockPointerType *NewIP = 1246 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1247 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1248 } 1249 BlockPointerType *New 1250 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1251 Types.push_back(New); 1252 BlockPointerTypes.InsertNode(New, InsertPos); 1253 return QualType(New, 0); 1254} 1255 1256/// getLValueReferenceType - Return the uniqued reference to the type for an 1257/// lvalue reference to the specified type. 1258QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) { 1259 // Unique pointers, to guarantee there is only one pointer of a particular 1260 // structure. 1261 llvm::FoldingSetNodeID ID; 1262 ReferenceType::Profile(ID, T, SpelledAsLValue); 1263 1264 void *InsertPos = 0; 1265 if (LValueReferenceType *RT = 1266 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1267 return QualType(RT, 0); 1268 1269 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1270 1271 // If the referencee type isn't canonical, this won't be a canonical type 1272 // either, so fill in the canonical type field. 1273 QualType Canonical; 1274 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1275 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1276 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1277 1278 // Get the new insert position for the node we care about. 1279 LValueReferenceType *NewIP = 1280 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1281 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1282 } 1283 1284 LValueReferenceType *New 1285 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1286 SpelledAsLValue); 1287 Types.push_back(New); 1288 LValueReferenceTypes.InsertNode(New, InsertPos); 1289 1290 return QualType(New, 0); 1291} 1292 1293/// getRValueReferenceType - Return the uniqued reference to the type for an 1294/// rvalue reference to the specified type. 1295QualType ASTContext::getRValueReferenceType(QualType T) { 1296 // Unique pointers, to guarantee there is only one pointer of a particular 1297 // structure. 1298 llvm::FoldingSetNodeID ID; 1299 ReferenceType::Profile(ID, T, false); 1300 1301 void *InsertPos = 0; 1302 if (RValueReferenceType *RT = 1303 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1304 return QualType(RT, 0); 1305 1306 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1307 1308 // If the referencee type isn't canonical, this won't be a canonical type 1309 // either, so fill in the canonical type field. 1310 QualType Canonical; 1311 if (InnerRef || !T.isCanonical()) { 1312 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1313 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1314 1315 // Get the new insert position for the node we care about. 1316 RValueReferenceType *NewIP = 1317 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1319 } 1320 1321 RValueReferenceType *New 1322 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1323 Types.push_back(New); 1324 RValueReferenceTypes.InsertNode(New, InsertPos); 1325 return QualType(New, 0); 1326} 1327 1328/// getMemberPointerType - Return the uniqued reference to the type for a 1329/// member pointer to the specified type, in the specified class. 1330QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) { 1331 // Unique pointers, to guarantee there is only one pointer of a particular 1332 // structure. 1333 llvm::FoldingSetNodeID ID; 1334 MemberPointerType::Profile(ID, T, Cls); 1335 1336 void *InsertPos = 0; 1337 if (MemberPointerType *PT = 1338 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1339 return QualType(PT, 0); 1340 1341 // If the pointee or class type isn't canonical, this won't be a canonical 1342 // type either, so fill in the canonical type field. 1343 QualType Canonical; 1344 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1345 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1346 1347 // Get the new insert position for the node we care about. 1348 MemberPointerType *NewIP = 1349 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1351 } 1352 MemberPointerType *New 1353 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1354 Types.push_back(New); 1355 MemberPointerTypes.InsertNode(New, InsertPos); 1356 return QualType(New, 0); 1357} 1358 1359/// getConstantArrayType - Return the unique reference to the type for an 1360/// array of the specified element type. 1361QualType ASTContext::getConstantArrayType(QualType EltTy, 1362 const llvm::APInt &ArySizeIn, 1363 ArrayType::ArraySizeModifier ASM, 1364 unsigned EltTypeQuals) { 1365 assert((EltTy->isDependentType() || 1366 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1367 "Constant array of VLAs is illegal!"); 1368 1369 // Convert the array size into a canonical width matching the pointer size for 1370 // the target. 1371 llvm::APInt ArySize(ArySizeIn); 1372 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1373 1374 llvm::FoldingSetNodeID ID; 1375 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1376 1377 void *InsertPos = 0; 1378 if (ConstantArrayType *ATP = 1379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1380 return QualType(ATP, 0); 1381 1382 // If the element type isn't canonical, this won't be a canonical type either, 1383 // so fill in the canonical type field. 1384 QualType Canonical; 1385 if (!EltTy.isCanonical()) { 1386 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1387 ASM, EltTypeQuals); 1388 // Get the new insert position for the node we care about. 1389 ConstantArrayType *NewIP = 1390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1391 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1392 } 1393 1394 ConstantArrayType *New = new(*this,TypeAlignment) 1395 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1396 ConstantArrayTypes.InsertNode(New, InsertPos); 1397 Types.push_back(New); 1398 return QualType(New, 0); 1399} 1400 1401/// getVariableArrayType - Returns a non-unique reference to the type for a 1402/// variable array of the specified element type. 1403QualType ASTContext::getVariableArrayType(QualType EltTy, 1404 Expr *NumElts, 1405 ArrayType::ArraySizeModifier ASM, 1406 unsigned EltTypeQuals, 1407 SourceRange Brackets) { 1408 // Since we don't unique expressions, it isn't possible to unique VLA's 1409 // that have an expression provided for their size. 1410 QualType CanonType; 1411 1412 if (!EltTy.isCanonical()) { 1413 if (NumElts) 1414 NumElts->Retain(); 1415 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM, 1416 EltTypeQuals, Brackets); 1417 } 1418 1419 VariableArrayType *New = new(*this, TypeAlignment) 1420 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets); 1421 1422 VariableArrayTypes.push_back(New); 1423 Types.push_back(New); 1424 return QualType(New, 0); 1425} 1426 1427/// getDependentSizedArrayType - Returns a non-unique reference to 1428/// the type for a dependently-sized array of the specified element 1429/// type. 1430QualType ASTContext::getDependentSizedArrayType(QualType EltTy, 1431 Expr *NumElts, 1432 ArrayType::ArraySizeModifier ASM, 1433 unsigned EltTypeQuals, 1434 SourceRange Brackets) { 1435 assert((!NumElts || NumElts->isTypeDependent() || 1436 NumElts->isValueDependent()) && 1437 "Size must be type- or value-dependent!"); 1438 1439 void *InsertPos = 0; 1440 DependentSizedArrayType *Canon = 0; 1441 llvm::FoldingSetNodeID ID; 1442 1443 if (NumElts) { 1444 // Dependently-sized array types that do not have a specified 1445 // number of elements will have their sizes deduced from an 1446 // initializer. 1447 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM, 1448 EltTypeQuals, NumElts); 1449 1450 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1451 } 1452 1453 DependentSizedArrayType *New; 1454 if (Canon) { 1455 // We already have a canonical version of this array type; use it as 1456 // the canonical type for a newly-built type. 1457 New = new (*this, TypeAlignment) 1458 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0), 1459 NumElts, ASM, EltTypeQuals, Brackets); 1460 } else { 1461 QualType CanonEltTy = getCanonicalType(EltTy); 1462 if (CanonEltTy == EltTy) { 1463 New = new (*this, TypeAlignment) 1464 DependentSizedArrayType(*this, EltTy, QualType(), 1465 NumElts, ASM, EltTypeQuals, Brackets); 1466 1467 if (NumElts) { 1468 DependentSizedArrayType *CanonCheck 1469 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1470 assert(!CanonCheck && "Dependent-sized canonical array type broken"); 1471 (void)CanonCheck; 1472 DependentSizedArrayTypes.InsertNode(New, InsertPos); 1473 } 1474 } else { 1475 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts, 1476 ASM, EltTypeQuals, 1477 SourceRange()); 1478 New = new (*this, TypeAlignment) 1479 DependentSizedArrayType(*this, EltTy, Canon, 1480 NumElts, ASM, EltTypeQuals, Brackets); 1481 } 1482 } 1483 1484 Types.push_back(New); 1485 return QualType(New, 0); 1486} 1487 1488QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1489 ArrayType::ArraySizeModifier ASM, 1490 unsigned EltTypeQuals) { 1491 llvm::FoldingSetNodeID ID; 1492 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1493 1494 void *InsertPos = 0; 1495 if (IncompleteArrayType *ATP = 1496 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1497 return QualType(ATP, 0); 1498 1499 // If the element type isn't canonical, this won't be a canonical type 1500 // either, so fill in the canonical type field. 1501 QualType Canonical; 1502 1503 if (!EltTy.isCanonical()) { 1504 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1505 ASM, EltTypeQuals); 1506 1507 // Get the new insert position for the node we care about. 1508 IncompleteArrayType *NewIP = 1509 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1510 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1511 } 1512 1513 IncompleteArrayType *New = new (*this, TypeAlignment) 1514 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals); 1515 1516 IncompleteArrayTypes.InsertNode(New, InsertPos); 1517 Types.push_back(New); 1518 return QualType(New, 0); 1519} 1520 1521/// getVectorType - Return the unique reference to a vector type of 1522/// the specified element type and size. VectorType must be a built-in type. 1523QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 1524 VectorType::AltiVecSpecific AltiVecSpec) { 1525 BuiltinType *baseType; 1526 1527 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1528 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1529 1530 // Check if we've already instantiated a vector of this type. 1531 llvm::FoldingSetNodeID ID; 1532 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec); 1533 1534 void *InsertPos = 0; 1535 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1536 return QualType(VTP, 0); 1537 1538 // If the element type isn't canonical, this won't be a canonical type either, 1539 // so fill in the canonical type field. 1540 QualType Canonical; 1541 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) { 1542 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical 1543 // vector type (except 'vector bool ...' and 'vector Pixel') the same as 1544 // the equivalent GCC vector types 1545 Canonical = getVectorType(getCanonicalType(vecType), NumElts, 1546 VectorType::NotAltiVec); 1547 1548 // Get the new insert position for the node we care about. 1549 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1550 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1551 } 1552 VectorType *New = new (*this, TypeAlignment) 1553 VectorType(vecType, NumElts, Canonical, AltiVecSpec); 1554 VectorTypes.InsertNode(New, InsertPos); 1555 Types.push_back(New); 1556 return QualType(New, 0); 1557} 1558 1559/// getExtVectorType - Return the unique reference to an extended vector type of 1560/// the specified element type and size. VectorType must be a built-in type. 1561QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1562 BuiltinType *baseType; 1563 1564 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1565 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1566 1567 // Check if we've already instantiated a vector of this type. 1568 llvm::FoldingSetNodeID ID; 1569 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 1570 VectorType::NotAltiVec); 1571 void *InsertPos = 0; 1572 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1573 return QualType(VTP, 0); 1574 1575 // If the element type isn't canonical, this won't be a canonical type either, 1576 // so fill in the canonical type field. 1577 QualType Canonical; 1578 if (!vecType.isCanonical()) { 1579 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1580 1581 // Get the new insert position for the node we care about. 1582 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1583 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1584 } 1585 ExtVectorType *New = new (*this, TypeAlignment) 1586 ExtVectorType(vecType, NumElts, Canonical); 1587 VectorTypes.InsertNode(New, InsertPos); 1588 Types.push_back(New); 1589 return QualType(New, 0); 1590} 1591 1592QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, 1593 Expr *SizeExpr, 1594 SourceLocation AttrLoc) { 1595 llvm::FoldingSetNodeID ID; 1596 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 1597 SizeExpr); 1598 1599 void *InsertPos = 0; 1600 DependentSizedExtVectorType *Canon 1601 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1602 DependentSizedExtVectorType *New; 1603 if (Canon) { 1604 // We already have a canonical version of this array type; use it as 1605 // the canonical type for a newly-built type. 1606 New = new (*this, TypeAlignment) 1607 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 1608 SizeExpr, AttrLoc); 1609 } else { 1610 QualType CanonVecTy = getCanonicalType(vecType); 1611 if (CanonVecTy == vecType) { 1612 New = new (*this, TypeAlignment) 1613 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 1614 AttrLoc); 1615 1616 DependentSizedExtVectorType *CanonCheck 1617 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1618 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 1619 (void)CanonCheck; 1620 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 1621 } else { 1622 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 1623 SourceLocation()); 1624 New = new (*this, TypeAlignment) 1625 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 1626 } 1627 } 1628 1629 Types.push_back(New); 1630 return QualType(New, 0); 1631} 1632 1633/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1634/// 1635QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, 1636 const FunctionType::ExtInfo &Info) { 1637 const CallingConv CallConv = Info.getCC(); 1638 // Unique functions, to guarantee there is only one function of a particular 1639 // structure. 1640 llvm::FoldingSetNodeID ID; 1641 FunctionNoProtoType::Profile(ID, ResultTy, Info); 1642 1643 void *InsertPos = 0; 1644 if (FunctionNoProtoType *FT = 1645 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1646 return QualType(FT, 0); 1647 1648 QualType Canonical; 1649 if (!ResultTy.isCanonical() || 1650 getCanonicalCallConv(CallConv) != CallConv) { 1651 Canonical = 1652 getFunctionNoProtoType(getCanonicalType(ResultTy), 1653 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1654 1655 // Get the new insert position for the node we care about. 1656 FunctionNoProtoType *NewIP = 1657 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1658 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1659 } 1660 1661 FunctionNoProtoType *New = new (*this, TypeAlignment) 1662 FunctionNoProtoType(ResultTy, Canonical, Info); 1663 Types.push_back(New); 1664 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1665 return QualType(New, 0); 1666} 1667 1668/// getFunctionType - Return a normal function type with a typed argument 1669/// list. isVariadic indicates whether the argument list includes '...'. 1670QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1671 unsigned NumArgs, bool isVariadic, 1672 unsigned TypeQuals, bool hasExceptionSpec, 1673 bool hasAnyExceptionSpec, unsigned NumExs, 1674 const QualType *ExArray, 1675 const FunctionType::ExtInfo &Info) { 1676 const CallingConv CallConv= Info.getCC(); 1677 // Unique functions, to guarantee there is only one function of a particular 1678 // structure. 1679 llvm::FoldingSetNodeID ID; 1680 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1681 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1682 NumExs, ExArray, Info); 1683 1684 void *InsertPos = 0; 1685 if (FunctionProtoType *FTP = 1686 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1687 return QualType(FTP, 0); 1688 1689 // Determine whether the type being created is already canonical or not. 1690 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical(); 1691 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1692 if (!ArgArray[i].isCanonicalAsParam()) 1693 isCanonical = false; 1694 1695 // If this type isn't canonical, get the canonical version of it. 1696 // The exception spec is not part of the canonical type. 1697 QualType Canonical; 1698 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 1699 llvm::SmallVector<QualType, 16> CanonicalArgs; 1700 CanonicalArgs.reserve(NumArgs); 1701 for (unsigned i = 0; i != NumArgs; ++i) 1702 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 1703 1704 Canonical = getFunctionType(getCanonicalType(ResultTy), 1705 CanonicalArgs.data(), NumArgs, 1706 isVariadic, TypeQuals, false, 1707 false, 0, 0, 1708 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1709 1710 // Get the new insert position for the node we care about. 1711 FunctionProtoType *NewIP = 1712 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1713 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1714 } 1715 1716 // FunctionProtoType objects are allocated with extra bytes after them 1717 // for two variable size arrays (for parameter and exception types) at the 1718 // end of them. 1719 FunctionProtoType *FTP = 1720 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1721 NumArgs*sizeof(QualType) + 1722 NumExs*sizeof(QualType), TypeAlignment); 1723 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1724 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1725 ExArray, NumExs, Canonical, Info); 1726 Types.push_back(FTP); 1727 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1728 return QualType(FTP, 0); 1729} 1730 1731#ifndef NDEBUG 1732static bool NeedsInjectedClassNameType(const RecordDecl *D) { 1733 if (!isa<CXXRecordDecl>(D)) return false; 1734 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 1735 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 1736 return true; 1737 if (RD->getDescribedClassTemplate() && 1738 !isa<ClassTemplateSpecializationDecl>(RD)) 1739 return true; 1740 return false; 1741} 1742#endif 1743 1744/// getInjectedClassNameType - Return the unique reference to the 1745/// injected class name type for the specified templated declaration. 1746QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 1747 QualType TST) { 1748 assert(NeedsInjectedClassNameType(Decl)); 1749 if (Decl->TypeForDecl) { 1750 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1751 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) { 1752 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 1753 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1754 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1755 } else { 1756 Decl->TypeForDecl = 1757 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 1758 Types.push_back(Decl->TypeForDecl); 1759 } 1760 return QualType(Decl->TypeForDecl, 0); 1761} 1762 1763/// getTypeDeclType - Return the unique reference to the type for the 1764/// specified type declaration. 1765QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) { 1766 assert(Decl && "Passed null for Decl param"); 1767 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 1768 1769 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1770 return getTypedefType(Typedef); 1771 1772 assert(!isa<TemplateTypeParmDecl>(Decl) && 1773 "Template type parameter types are always available."); 1774 1775 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1776 assert(!Record->getPreviousDeclaration() && 1777 "struct/union has previous declaration"); 1778 assert(!NeedsInjectedClassNameType(Record)); 1779 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record); 1780 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1781 assert(!Enum->getPreviousDeclaration() && 1782 "enum has previous declaration"); 1783 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum); 1784 } else if (const UnresolvedUsingTypenameDecl *Using = 1785 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 1786 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using); 1787 } else 1788 llvm_unreachable("TypeDecl without a type?"); 1789 1790 Types.push_back(Decl->TypeForDecl); 1791 return QualType(Decl->TypeForDecl, 0); 1792} 1793 1794/// getTypedefType - Return the unique reference to the type for the 1795/// specified typename decl. 1796QualType 1797ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) { 1798 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1799 1800 if (Canonical.isNull()) 1801 Canonical = getCanonicalType(Decl->getUnderlyingType()); 1802 Decl->TypeForDecl = new(*this, TypeAlignment) 1803 TypedefType(Type::Typedef, Decl, Canonical); 1804 Types.push_back(Decl->TypeForDecl); 1805 return QualType(Decl->TypeForDecl, 0); 1806} 1807 1808/// \brief Retrieve a substitution-result type. 1809QualType 1810ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 1811 QualType Replacement) { 1812 assert(Replacement.isCanonical() 1813 && "replacement types must always be canonical"); 1814 1815 llvm::FoldingSetNodeID ID; 1816 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 1817 void *InsertPos = 0; 1818 SubstTemplateTypeParmType *SubstParm 1819 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1820 1821 if (!SubstParm) { 1822 SubstParm = new (*this, TypeAlignment) 1823 SubstTemplateTypeParmType(Parm, Replacement); 1824 Types.push_back(SubstParm); 1825 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 1826 } 1827 1828 return QualType(SubstParm, 0); 1829} 1830 1831/// \brief Retrieve the template type parameter type for a template 1832/// parameter or parameter pack with the given depth, index, and (optionally) 1833/// name. 1834QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1835 bool ParameterPack, 1836 IdentifierInfo *Name) { 1837 llvm::FoldingSetNodeID ID; 1838 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); 1839 void *InsertPos = 0; 1840 TemplateTypeParmType *TypeParm 1841 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1842 1843 if (TypeParm) 1844 return QualType(TypeParm, 0); 1845 1846 if (Name) { 1847 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 1848 TypeParm = new (*this, TypeAlignment) 1849 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon); 1850 1851 TemplateTypeParmType *TypeCheck 1852 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1853 assert(!TypeCheck && "Template type parameter canonical type broken"); 1854 (void)TypeCheck; 1855 } else 1856 TypeParm = new (*this, TypeAlignment) 1857 TemplateTypeParmType(Depth, Index, ParameterPack); 1858 1859 Types.push_back(TypeParm); 1860 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1861 1862 return QualType(TypeParm, 0); 1863} 1864 1865TypeSourceInfo * 1866ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 1867 SourceLocation NameLoc, 1868 const TemplateArgumentListInfo &Args, 1869 QualType CanonType) { 1870 QualType TST = getTemplateSpecializationType(Name, Args, CanonType); 1871 1872 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 1873 TemplateSpecializationTypeLoc TL 1874 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1875 TL.setTemplateNameLoc(NameLoc); 1876 TL.setLAngleLoc(Args.getLAngleLoc()); 1877 TL.setRAngleLoc(Args.getRAngleLoc()); 1878 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 1879 TL.setArgLocInfo(i, Args[i].getLocInfo()); 1880 return DI; 1881} 1882 1883QualType 1884ASTContext::getTemplateSpecializationType(TemplateName Template, 1885 const TemplateArgumentListInfo &Args, 1886 QualType Canon) { 1887 unsigned NumArgs = Args.size(); 1888 1889 llvm::SmallVector<TemplateArgument, 4> ArgVec; 1890 ArgVec.reserve(NumArgs); 1891 for (unsigned i = 0; i != NumArgs; ++i) 1892 ArgVec.push_back(Args[i].getArgument()); 1893 1894 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 1895 Canon); 1896} 1897 1898QualType 1899ASTContext::getTemplateSpecializationType(TemplateName Template, 1900 const TemplateArgument *Args, 1901 unsigned NumArgs, 1902 QualType Canon) { 1903 if (!Canon.isNull()) 1904 Canon = getCanonicalType(Canon); 1905 else 1906 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs); 1907 1908 // Allocate the (non-canonical) template specialization type, but don't 1909 // try to unique it: these types typically have location information that 1910 // we don't unique and don't want to lose. 1911 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1912 sizeof(TemplateArgument) * NumArgs), 1913 TypeAlignment); 1914 TemplateSpecializationType *Spec 1915 = new (Mem) TemplateSpecializationType(Template, 1916 Args, NumArgs, 1917 Canon); 1918 1919 Types.push_back(Spec); 1920 return QualType(Spec, 0); 1921} 1922 1923QualType 1924ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 1925 const TemplateArgument *Args, 1926 unsigned NumArgs) { 1927 // Build the canonical template specialization type. 1928 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 1929 llvm::SmallVector<TemplateArgument, 4> CanonArgs; 1930 CanonArgs.reserve(NumArgs); 1931 for (unsigned I = 0; I != NumArgs; ++I) 1932 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 1933 1934 // Determine whether this canonical template specialization type already 1935 // exists. 1936 llvm::FoldingSetNodeID ID; 1937 TemplateSpecializationType::Profile(ID, CanonTemplate, 1938 CanonArgs.data(), NumArgs, *this); 1939 1940 void *InsertPos = 0; 1941 TemplateSpecializationType *Spec 1942 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 1943 1944 if (!Spec) { 1945 // Allocate a new canonical template specialization type. 1946 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1947 sizeof(TemplateArgument) * NumArgs), 1948 TypeAlignment); 1949 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 1950 CanonArgs.data(), NumArgs, 1951 QualType()); 1952 Types.push_back(Spec); 1953 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 1954 } 1955 1956 assert(Spec->isDependentType() && 1957 "Non-dependent template-id type must have a canonical type"); 1958 return QualType(Spec, 0); 1959} 1960 1961QualType 1962ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 1963 NestedNameSpecifier *NNS, 1964 QualType NamedType) { 1965 llvm::FoldingSetNodeID ID; 1966 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 1967 1968 void *InsertPos = 0; 1969 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 1970 if (T) 1971 return QualType(T, 0); 1972 1973 QualType Canon = NamedType; 1974 if (!Canon.isCanonical()) { 1975 Canon = getCanonicalType(NamedType); 1976 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 1977 assert(!CheckT && "Elaborated canonical type broken"); 1978 (void)CheckT; 1979 } 1980 1981 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 1982 Types.push_back(T); 1983 ElaboratedTypes.InsertNode(T, InsertPos); 1984 return QualType(T, 0); 1985} 1986 1987QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 1988 NestedNameSpecifier *NNS, 1989 const IdentifierInfo *Name, 1990 QualType Canon) { 1991 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1992 1993 if (Canon.isNull()) { 1994 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1995 ElaboratedTypeKeyword CanonKeyword = Keyword; 1996 if (Keyword == ETK_None) 1997 CanonKeyword = ETK_Typename; 1998 1999 if (CanonNNS != NNS || CanonKeyword != Keyword) 2000 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2001 } 2002 2003 llvm::FoldingSetNodeID ID; 2004 DependentNameType::Profile(ID, Keyword, NNS, Name); 2005 2006 void *InsertPos = 0; 2007 DependentNameType *T 2008 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2009 if (T) 2010 return QualType(T, 0); 2011 2012 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2013 Types.push_back(T); 2014 DependentNameTypes.InsertNode(T, InsertPos); 2015 return QualType(T, 0); 2016} 2017 2018QualType 2019ASTContext::getDependentTemplateSpecializationType( 2020 ElaboratedTypeKeyword Keyword, 2021 NestedNameSpecifier *NNS, 2022 const IdentifierInfo *Name, 2023 const TemplateArgumentListInfo &Args) { 2024 // TODO: avoid this copy 2025 llvm::SmallVector<TemplateArgument, 16> ArgCopy; 2026 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2027 ArgCopy.push_back(Args[I].getArgument()); 2028 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2029 ArgCopy.size(), 2030 ArgCopy.data()); 2031} 2032 2033QualType 2034ASTContext::getDependentTemplateSpecializationType( 2035 ElaboratedTypeKeyword Keyword, 2036 NestedNameSpecifier *NNS, 2037 const IdentifierInfo *Name, 2038 unsigned NumArgs, 2039 const TemplateArgument *Args) { 2040 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2041 2042 llvm::FoldingSetNodeID ID; 2043 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2044 Name, NumArgs, Args); 2045 2046 void *InsertPos = 0; 2047 DependentTemplateSpecializationType *T 2048 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2049 if (T) 2050 return QualType(T, 0); 2051 2052 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2053 2054 ElaboratedTypeKeyword CanonKeyword = Keyword; 2055 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2056 2057 bool AnyNonCanonArgs = false; 2058 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2059 for (unsigned I = 0; I != NumArgs; ++I) { 2060 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2061 if (!CanonArgs[I].structurallyEquals(Args[I])) 2062 AnyNonCanonArgs = true; 2063 } 2064 2065 QualType Canon; 2066 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2067 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2068 Name, NumArgs, 2069 CanonArgs.data()); 2070 2071 // Find the insert position again. 2072 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2073 } 2074 2075 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2076 sizeof(TemplateArgument) * NumArgs), 2077 TypeAlignment); 2078 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2079 Name, NumArgs, Args, Canon); 2080 Types.push_back(T); 2081 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2082 return QualType(T, 0); 2083} 2084 2085/// CmpProtocolNames - Comparison predicate for sorting protocols 2086/// alphabetically. 2087static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2088 const ObjCProtocolDecl *RHS) { 2089 return LHS->getDeclName() < RHS->getDeclName(); 2090} 2091 2092static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2093 unsigned NumProtocols) { 2094 if (NumProtocols == 0) return true; 2095 2096 for (unsigned i = 1; i != NumProtocols; ++i) 2097 if (!CmpProtocolNames(Protocols[i-1], Protocols[i])) 2098 return false; 2099 return true; 2100} 2101 2102static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2103 unsigned &NumProtocols) { 2104 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2105 2106 // Sort protocols, keyed by name. 2107 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2108 2109 // Remove duplicates. 2110 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2111 NumProtocols = ProtocolsEnd-Protocols; 2112} 2113 2114QualType ASTContext::getObjCObjectType(QualType BaseType, 2115 ObjCProtocolDecl * const *Protocols, 2116 unsigned NumProtocols) { 2117 // If the base type is an interface and there aren't any protocols 2118 // to add, then the interface type will do just fine. 2119 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2120 return BaseType; 2121 2122 // Look in the folding set for an existing type. 2123 llvm::FoldingSetNodeID ID; 2124 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2125 void *InsertPos = 0; 2126 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2127 return QualType(QT, 0); 2128 2129 // Build the canonical type, which has the canonical base type and 2130 // a sorted-and-uniqued list of protocols. 2131 QualType Canonical; 2132 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2133 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2134 if (!ProtocolsSorted) { 2135 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2136 Protocols + NumProtocols); 2137 unsigned UniqueCount = NumProtocols; 2138 2139 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2140 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2141 &Sorted[0], UniqueCount); 2142 } else { 2143 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2144 Protocols, NumProtocols); 2145 } 2146 2147 // Regenerate InsertPos. 2148 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2149 } 2150 2151 unsigned Size = sizeof(ObjCObjectTypeImpl); 2152 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2153 void *Mem = Allocate(Size, TypeAlignment); 2154 ObjCObjectTypeImpl *T = 2155 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2156 2157 Types.push_back(T); 2158 ObjCObjectTypes.InsertNode(T, InsertPos); 2159 return QualType(T, 0); 2160} 2161 2162/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2163/// the given object type. 2164QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) { 2165 llvm::FoldingSetNodeID ID; 2166 ObjCObjectPointerType::Profile(ID, ObjectT); 2167 2168 void *InsertPos = 0; 2169 if (ObjCObjectPointerType *QT = 2170 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2171 return QualType(QT, 0); 2172 2173 // Find the canonical object type. 2174 QualType Canonical; 2175 if (!ObjectT.isCanonical()) { 2176 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2177 2178 // Regenerate InsertPos. 2179 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2180 } 2181 2182 // No match. 2183 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2184 ObjCObjectPointerType *QType = 2185 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2186 2187 Types.push_back(QType); 2188 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2189 return QualType(QType, 0); 2190} 2191 2192/// getObjCInterfaceType - Return the unique reference to the type for the 2193/// specified ObjC interface decl. The list of protocols is optional. 2194QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 2195 if (Decl->TypeForDecl) 2196 return QualType(Decl->TypeForDecl, 0); 2197 2198 // FIXME: redeclarations? 2199 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2200 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2201 Decl->TypeForDecl = T; 2202 Types.push_back(T); 2203 return QualType(T, 0); 2204} 2205 2206/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2207/// TypeOfExprType AST's (since expression's are never shared). For example, 2208/// multiple declarations that refer to "typeof(x)" all contain different 2209/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2210/// on canonical type's (which are always unique). 2211QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 2212 TypeOfExprType *toe; 2213 if (tofExpr->isTypeDependent()) { 2214 llvm::FoldingSetNodeID ID; 2215 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2216 2217 void *InsertPos = 0; 2218 DependentTypeOfExprType *Canon 2219 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2220 if (Canon) { 2221 // We already have a "canonical" version of an identical, dependent 2222 // typeof(expr) type. Use that as our canonical type. 2223 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 2224 QualType((TypeOfExprType*)Canon, 0)); 2225 } 2226 else { 2227 // Build a new, canonical typeof(expr) type. 2228 Canon 2229 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 2230 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 2231 toe = Canon; 2232 } 2233 } else { 2234 QualType Canonical = getCanonicalType(tofExpr->getType()); 2235 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 2236 } 2237 Types.push_back(toe); 2238 return QualType(toe, 0); 2239} 2240 2241/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 2242/// TypeOfType AST's. The only motivation to unique these nodes would be 2243/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 2244/// an issue. This doesn't effect the type checker, since it operates 2245/// on canonical type's (which are always unique). 2246QualType ASTContext::getTypeOfType(QualType tofType) { 2247 QualType Canonical = getCanonicalType(tofType); 2248 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 2249 Types.push_back(tot); 2250 return QualType(tot, 0); 2251} 2252 2253/// getDecltypeForExpr - Given an expr, will return the decltype for that 2254/// expression, according to the rules in C++0x [dcl.type.simple]p4 2255static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { 2256 if (e->isTypeDependent()) 2257 return Context.DependentTy; 2258 2259 // If e is an id expression or a class member access, decltype(e) is defined 2260 // as the type of the entity named by e. 2261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 2262 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 2263 return VD->getType(); 2264 } 2265 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 2266 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2267 return FD->getType(); 2268 } 2269 // If e is a function call or an invocation of an overloaded operator, 2270 // (parentheses around e are ignored), decltype(e) is defined as the 2271 // return type of that function. 2272 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 2273 return CE->getCallReturnType(); 2274 2275 QualType T = e->getType(); 2276 2277 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 2278 // defined as T&, otherwise decltype(e) is defined as T. 2279 if (e->isLvalue(Context) == Expr::LV_Valid) 2280 T = Context.getLValueReferenceType(T); 2281 2282 return T; 2283} 2284 2285/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 2286/// DecltypeType AST's. The only motivation to unique these nodes would be 2287/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 2288/// an issue. This doesn't effect the type checker, since it operates 2289/// on canonical type's (which are always unique). 2290QualType ASTContext::getDecltypeType(Expr *e) { 2291 DecltypeType *dt; 2292 if (e->isTypeDependent()) { 2293 llvm::FoldingSetNodeID ID; 2294 DependentDecltypeType::Profile(ID, *this, e); 2295 2296 void *InsertPos = 0; 2297 DependentDecltypeType *Canon 2298 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 2299 if (Canon) { 2300 // We already have a "canonical" version of an equivalent, dependent 2301 // decltype type. Use that as our canonical type. 2302 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 2303 QualType((DecltypeType*)Canon, 0)); 2304 } 2305 else { 2306 // Build a new, canonical typeof(expr) type. 2307 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 2308 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 2309 dt = Canon; 2310 } 2311 } else { 2312 QualType T = getDecltypeForExpr(e, *this); 2313 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T)); 2314 } 2315 Types.push_back(dt); 2316 return QualType(dt, 0); 2317} 2318 2319/// getTagDeclType - Return the unique reference to the type for the 2320/// specified TagDecl (struct/union/class/enum) decl. 2321QualType ASTContext::getTagDeclType(const TagDecl *Decl) { 2322 assert (Decl); 2323 // FIXME: What is the design on getTagDeclType when it requires casting 2324 // away const? mutable? 2325 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 2326} 2327 2328/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 2329/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 2330/// needs to agree with the definition in <stddef.h>. 2331CanQualType ASTContext::getSizeType() const { 2332 return getFromTargetType(Target.getSizeType()); 2333} 2334 2335/// getSignedWCharType - Return the type of "signed wchar_t". 2336/// Used when in C++, as a GCC extension. 2337QualType ASTContext::getSignedWCharType() const { 2338 // FIXME: derive from "Target" ? 2339 return WCharTy; 2340} 2341 2342/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 2343/// Used when in C++, as a GCC extension. 2344QualType ASTContext::getUnsignedWCharType() const { 2345 // FIXME: derive from "Target" ? 2346 return UnsignedIntTy; 2347} 2348 2349/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 2350/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 2351QualType ASTContext::getPointerDiffType() const { 2352 return getFromTargetType(Target.getPtrDiffType(0)); 2353} 2354 2355//===----------------------------------------------------------------------===// 2356// Type Operators 2357//===----------------------------------------------------------------------===// 2358 2359CanQualType ASTContext::getCanonicalParamType(QualType T) { 2360 // Push qualifiers into arrays, and then discard any remaining 2361 // qualifiers. 2362 T = getCanonicalType(T); 2363 const Type *Ty = T.getTypePtr(); 2364 2365 QualType Result; 2366 if (isa<ArrayType>(Ty)) { 2367 Result = getArrayDecayedType(QualType(Ty,0)); 2368 } else if (isa<FunctionType>(Ty)) { 2369 Result = getPointerType(QualType(Ty, 0)); 2370 } else { 2371 Result = QualType(Ty, 0); 2372 } 2373 2374 return CanQualType::CreateUnsafe(Result); 2375} 2376 2377/// getCanonicalType - Return the canonical (structural) type corresponding to 2378/// the specified potentially non-canonical type. The non-canonical version 2379/// of a type may have many "decorated" versions of types. Decorators can 2380/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 2381/// to be free of any of these, allowing two canonical types to be compared 2382/// for exact equality with a simple pointer comparison. 2383CanQualType ASTContext::getCanonicalType(QualType T) { 2384 QualifierCollector Quals; 2385 const Type *Ptr = Quals.strip(T); 2386 QualType CanType = Ptr->getCanonicalTypeInternal(); 2387 2388 // The canonical internal type will be the canonical type *except* 2389 // that we push type qualifiers down through array types. 2390 2391 // If there are no new qualifiers to push down, stop here. 2392 if (!Quals.hasQualifiers()) 2393 return CanQualType::CreateUnsafe(CanType); 2394 2395 // If the type qualifiers are on an array type, get the canonical 2396 // type of the array with the qualifiers applied to the element 2397 // type. 2398 ArrayType *AT = dyn_cast<ArrayType>(CanType); 2399 if (!AT) 2400 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals)); 2401 2402 // Get the canonical version of the element with the extra qualifiers on it. 2403 // This can recursively sink qualifiers through multiple levels of arrays. 2404 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals); 2405 NewEltTy = getCanonicalType(NewEltTy); 2406 2407 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2408 return CanQualType::CreateUnsafe( 2409 getConstantArrayType(NewEltTy, CAT->getSize(), 2410 CAT->getSizeModifier(), 2411 CAT->getIndexTypeCVRQualifiers())); 2412 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 2413 return CanQualType::CreateUnsafe( 2414 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 2415 IAT->getIndexTypeCVRQualifiers())); 2416 2417 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 2418 return CanQualType::CreateUnsafe( 2419 getDependentSizedArrayType(NewEltTy, 2420 DSAT->getSizeExpr() ? 2421 DSAT->getSizeExpr()->Retain() : 0, 2422 DSAT->getSizeModifier(), 2423 DSAT->getIndexTypeCVRQualifiers(), 2424 DSAT->getBracketsRange())->getCanonicalTypeInternal()); 2425 2426 VariableArrayType *VAT = cast<VariableArrayType>(AT); 2427 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy, 2428 VAT->getSizeExpr() ? 2429 VAT->getSizeExpr()->Retain() : 0, 2430 VAT->getSizeModifier(), 2431 VAT->getIndexTypeCVRQualifiers(), 2432 VAT->getBracketsRange())); 2433} 2434 2435QualType ASTContext::getUnqualifiedArrayType(QualType T, 2436 Qualifiers &Quals) { 2437 Quals = T.getQualifiers(); 2438 const ArrayType *AT = getAsArrayType(T); 2439 if (!AT) { 2440 return T.getUnqualifiedType(); 2441 } 2442 2443 QualType Elt = AT->getElementType(); 2444 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals); 2445 if (Elt == UnqualElt) 2446 return T; 2447 2448 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 2449 return getConstantArrayType(UnqualElt, CAT->getSize(), 2450 CAT->getSizeModifier(), 0); 2451 } 2452 2453 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 2454 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0); 2455 } 2456 2457 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 2458 return getVariableArrayType(UnqualElt, 2459 VAT->getSizeExpr() ? 2460 VAT->getSizeExpr()->Retain() : 0, 2461 VAT->getSizeModifier(), 2462 VAT->getIndexTypeCVRQualifiers(), 2463 VAT->getBracketsRange()); 2464 } 2465 2466 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 2467 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(), 2468 DSAT->getSizeModifier(), 0, 2469 SourceRange()); 2470} 2471 2472/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 2473/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 2474/// they point to and return true. If T1 and T2 aren't pointer types 2475/// or pointer-to-member types, or if they are not similar at this 2476/// level, returns false and leaves T1 and T2 unchanged. Top-level 2477/// qualifiers on T1 and T2 are ignored. This function will typically 2478/// be called in a loop that successively "unwraps" pointer and 2479/// pointer-to-member types to compare them at each level. 2480bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 2481 const PointerType *T1PtrType = T1->getAs<PointerType>(), 2482 *T2PtrType = T2->getAs<PointerType>(); 2483 if (T1PtrType && T2PtrType) { 2484 T1 = T1PtrType->getPointeeType(); 2485 T2 = T2PtrType->getPointeeType(); 2486 return true; 2487 } 2488 2489 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 2490 *T2MPType = T2->getAs<MemberPointerType>(); 2491 if (T1MPType && T2MPType && 2492 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 2493 QualType(T2MPType->getClass(), 0))) { 2494 T1 = T1MPType->getPointeeType(); 2495 T2 = T2MPType->getPointeeType(); 2496 return true; 2497 } 2498 2499 if (getLangOptions().ObjC1) { 2500 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 2501 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 2502 if (T1OPType && T2OPType) { 2503 T1 = T1OPType->getPointeeType(); 2504 T2 = T2OPType->getPointeeType(); 2505 return true; 2506 } 2507 } 2508 2509 // FIXME: Block pointers, too? 2510 2511 return false; 2512} 2513 2514DeclarationName ASTContext::getNameForTemplate(TemplateName Name) { 2515 if (TemplateDecl *TD = Name.getAsTemplateDecl()) 2516 return TD->getDeclName(); 2517 2518 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { 2519 if (DTN->isIdentifier()) { 2520 return DeclarationNames.getIdentifier(DTN->getIdentifier()); 2521 } else { 2522 return DeclarationNames.getCXXOperatorName(DTN->getOperator()); 2523 } 2524 } 2525 2526 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 2527 assert(Storage); 2528 return (*Storage->begin())->getDeclName(); 2529} 2530 2531TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 2532 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 2533 if (TemplateTemplateParmDecl *TTP 2534 = dyn_cast<TemplateTemplateParmDecl>(Template)) 2535 Template = getCanonicalTemplateTemplateParmDecl(TTP); 2536 2537 // The canonical template name is the canonical template declaration. 2538 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 2539 } 2540 2541 assert(!Name.getAsOverloadedTemplate()); 2542 2543 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 2544 assert(DTN && "Non-dependent template names must refer to template decls."); 2545 return DTN->CanonicalTemplateName; 2546} 2547 2548bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 2549 X = getCanonicalTemplateName(X); 2550 Y = getCanonicalTemplateName(Y); 2551 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 2552} 2553 2554TemplateArgument 2555ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { 2556 switch (Arg.getKind()) { 2557 case TemplateArgument::Null: 2558 return Arg; 2559 2560 case TemplateArgument::Expression: 2561 return Arg; 2562 2563 case TemplateArgument::Declaration: 2564 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl()); 2565 2566 case TemplateArgument::Template: 2567 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 2568 2569 case TemplateArgument::Integral: 2570 return TemplateArgument(*Arg.getAsIntegral(), 2571 getCanonicalType(Arg.getIntegralType())); 2572 2573 case TemplateArgument::Type: 2574 return TemplateArgument(getCanonicalType(Arg.getAsType())); 2575 2576 case TemplateArgument::Pack: { 2577 // FIXME: Allocate in ASTContext 2578 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()]; 2579 unsigned Idx = 0; 2580 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 2581 AEnd = Arg.pack_end(); 2582 A != AEnd; (void)++A, ++Idx) 2583 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 2584 2585 TemplateArgument Result; 2586 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false); 2587 return Result; 2588 } 2589 } 2590 2591 // Silence GCC warning 2592 assert(false && "Unhandled template argument kind"); 2593 return TemplateArgument(); 2594} 2595 2596NestedNameSpecifier * 2597ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 2598 if (!NNS) 2599 return 0; 2600 2601 switch (NNS->getKind()) { 2602 case NestedNameSpecifier::Identifier: 2603 // Canonicalize the prefix but keep the identifier the same. 2604 return NestedNameSpecifier::Create(*this, 2605 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 2606 NNS->getAsIdentifier()); 2607 2608 case NestedNameSpecifier::Namespace: 2609 // A namespace is canonical; build a nested-name-specifier with 2610 // this namespace and no prefix. 2611 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 2612 2613 case NestedNameSpecifier::TypeSpec: 2614 case NestedNameSpecifier::TypeSpecWithTemplate: { 2615 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 2616 return NestedNameSpecifier::Create(*this, 0, 2617 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 2618 T.getTypePtr()); 2619 } 2620 2621 case NestedNameSpecifier::Global: 2622 // The global specifier is canonical and unique. 2623 return NNS; 2624 } 2625 2626 // Required to silence a GCC warning 2627 return 0; 2628} 2629 2630 2631const ArrayType *ASTContext::getAsArrayType(QualType T) { 2632 // Handle the non-qualified case efficiently. 2633 if (!T.hasLocalQualifiers()) { 2634 // Handle the common positive case fast. 2635 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 2636 return AT; 2637 } 2638 2639 // Handle the common negative case fast. 2640 QualType CType = T->getCanonicalTypeInternal(); 2641 if (!isa<ArrayType>(CType)) 2642 return 0; 2643 2644 // Apply any qualifiers from the array type to the element type. This 2645 // implements C99 6.7.3p8: "If the specification of an array type includes 2646 // any type qualifiers, the element type is so qualified, not the array type." 2647 2648 // If we get here, we either have type qualifiers on the type, or we have 2649 // sugar such as a typedef in the way. If we have type qualifiers on the type 2650 // we must propagate them down into the element type. 2651 2652 QualifierCollector Qs; 2653 const Type *Ty = Qs.strip(T.getDesugaredType()); 2654 2655 // If we have a simple case, just return now. 2656 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 2657 if (ATy == 0 || Qs.empty()) 2658 return ATy; 2659 2660 // Otherwise, we have an array and we have qualifiers on it. Push the 2661 // qualifiers into the array element type and return a new array type. 2662 // Get the canonical version of the element with the extra qualifiers on it. 2663 // This can recursively sink qualifiers through multiple levels of arrays. 2664 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs); 2665 2666 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 2667 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 2668 CAT->getSizeModifier(), 2669 CAT->getIndexTypeCVRQualifiers())); 2670 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 2671 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 2672 IAT->getSizeModifier(), 2673 IAT->getIndexTypeCVRQualifiers())); 2674 2675 if (const DependentSizedArrayType *DSAT 2676 = dyn_cast<DependentSizedArrayType>(ATy)) 2677 return cast<ArrayType>( 2678 getDependentSizedArrayType(NewEltTy, 2679 DSAT->getSizeExpr() ? 2680 DSAT->getSizeExpr()->Retain() : 0, 2681 DSAT->getSizeModifier(), 2682 DSAT->getIndexTypeCVRQualifiers(), 2683 DSAT->getBracketsRange())); 2684 2685 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 2686 return cast<ArrayType>(getVariableArrayType(NewEltTy, 2687 VAT->getSizeExpr() ? 2688 VAT->getSizeExpr()->Retain() : 0, 2689 VAT->getSizeModifier(), 2690 VAT->getIndexTypeCVRQualifiers(), 2691 VAT->getBracketsRange())); 2692} 2693 2694 2695/// getArrayDecayedType - Return the properly qualified result of decaying the 2696/// specified array type to a pointer. This operation is non-trivial when 2697/// handling typedefs etc. The canonical type of "T" must be an array type, 2698/// this returns a pointer to a properly qualified element of the array. 2699/// 2700/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2701QualType ASTContext::getArrayDecayedType(QualType Ty) { 2702 // Get the element type with 'getAsArrayType' so that we don't lose any 2703 // typedefs in the element type of the array. This also handles propagation 2704 // of type qualifiers from the array type into the element type if present 2705 // (C99 6.7.3p8). 2706 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 2707 assert(PrettyArrayType && "Not an array type!"); 2708 2709 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 2710 2711 // int x[restrict 4] -> int *restrict 2712 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 2713} 2714 2715QualType ASTContext::getBaseElementType(QualType QT) { 2716 QualifierCollector Qs; 2717 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0))) 2718 QT = AT->getElementType(); 2719 return Qs.apply(QT); 2720} 2721 2722QualType ASTContext::getBaseElementType(const ArrayType *AT) { 2723 QualType ElemTy = AT->getElementType(); 2724 2725 if (const ArrayType *AT = getAsArrayType(ElemTy)) 2726 return getBaseElementType(AT); 2727 2728 return ElemTy; 2729} 2730 2731/// getConstantArrayElementCount - Returns number of constant array elements. 2732uint64_t 2733ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 2734 uint64_t ElementCount = 1; 2735 do { 2736 ElementCount *= CA->getSize().getZExtValue(); 2737 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 2738 } while (CA); 2739 return ElementCount; 2740} 2741 2742/// getFloatingRank - Return a relative rank for floating point types. 2743/// This routine will assert if passed a built-in type that isn't a float. 2744static FloatingRank getFloatingRank(QualType T) { 2745 if (const ComplexType *CT = T->getAs<ComplexType>()) 2746 return getFloatingRank(CT->getElementType()); 2747 2748 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 2749 switch (T->getAs<BuiltinType>()->getKind()) { 2750 default: assert(0 && "getFloatingRank(): not a floating type"); 2751 case BuiltinType::Float: return FloatRank; 2752 case BuiltinType::Double: return DoubleRank; 2753 case BuiltinType::LongDouble: return LongDoubleRank; 2754 } 2755} 2756 2757/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 2758/// point or a complex type (based on typeDomain/typeSize). 2759/// 'typeDomain' is a real floating point or complex type. 2760/// 'typeSize' is a real floating point or complex type. 2761QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 2762 QualType Domain) const { 2763 FloatingRank EltRank = getFloatingRank(Size); 2764 if (Domain->isComplexType()) { 2765 switch (EltRank) { 2766 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2767 case FloatRank: return FloatComplexTy; 2768 case DoubleRank: return DoubleComplexTy; 2769 case LongDoubleRank: return LongDoubleComplexTy; 2770 } 2771 } 2772 2773 assert(Domain->isRealFloatingType() && "Unknown domain!"); 2774 switch (EltRank) { 2775 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2776 case FloatRank: return FloatTy; 2777 case DoubleRank: return DoubleTy; 2778 case LongDoubleRank: return LongDoubleTy; 2779 } 2780} 2781 2782/// getFloatingTypeOrder - Compare the rank of the two specified floating 2783/// point types, ignoring the domain of the type (i.e. 'double' == 2784/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 2785/// LHS < RHS, return -1. 2786int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 2787 FloatingRank LHSR = getFloatingRank(LHS); 2788 FloatingRank RHSR = getFloatingRank(RHS); 2789 2790 if (LHSR == RHSR) 2791 return 0; 2792 if (LHSR > RHSR) 2793 return 1; 2794 return -1; 2795} 2796 2797/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 2798/// routine will assert if passed a built-in type that isn't an integer or enum, 2799/// or if it is not canonicalized. 2800unsigned ASTContext::getIntegerRank(Type *T) { 2801 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 2802 if (EnumType* ET = dyn_cast<EnumType>(T)) 2803 T = ET->getDecl()->getPromotionType().getTypePtr(); 2804 2805 if (T->isSpecificBuiltinType(BuiltinType::WChar)) 2806 T = getFromTargetType(Target.getWCharType()).getTypePtr(); 2807 2808 if (T->isSpecificBuiltinType(BuiltinType::Char16)) 2809 T = getFromTargetType(Target.getChar16Type()).getTypePtr(); 2810 2811 if (T->isSpecificBuiltinType(BuiltinType::Char32)) 2812 T = getFromTargetType(Target.getChar32Type()).getTypePtr(); 2813 2814 switch (cast<BuiltinType>(T)->getKind()) { 2815 default: assert(0 && "getIntegerRank(): not a built-in integer"); 2816 case BuiltinType::Bool: 2817 return 1 + (getIntWidth(BoolTy) << 3); 2818 case BuiltinType::Char_S: 2819 case BuiltinType::Char_U: 2820 case BuiltinType::SChar: 2821 case BuiltinType::UChar: 2822 return 2 + (getIntWidth(CharTy) << 3); 2823 case BuiltinType::Short: 2824 case BuiltinType::UShort: 2825 return 3 + (getIntWidth(ShortTy) << 3); 2826 case BuiltinType::Int: 2827 case BuiltinType::UInt: 2828 return 4 + (getIntWidth(IntTy) << 3); 2829 case BuiltinType::Long: 2830 case BuiltinType::ULong: 2831 return 5 + (getIntWidth(LongTy) << 3); 2832 case BuiltinType::LongLong: 2833 case BuiltinType::ULongLong: 2834 return 6 + (getIntWidth(LongLongTy) << 3); 2835 case BuiltinType::Int128: 2836 case BuiltinType::UInt128: 2837 return 7 + (getIntWidth(Int128Ty) << 3); 2838 } 2839} 2840 2841/// \brief Whether this is a promotable bitfield reference according 2842/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 2843/// 2844/// \returns the type this bit-field will promote to, or NULL if no 2845/// promotion occurs. 2846QualType ASTContext::isPromotableBitField(Expr *E) { 2847 if (E->isTypeDependent() || E->isValueDependent()) 2848 return QualType(); 2849 2850 FieldDecl *Field = E->getBitField(); 2851 if (!Field) 2852 return QualType(); 2853 2854 QualType FT = Field->getType(); 2855 2856 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this); 2857 uint64_t BitWidth = BitWidthAP.getZExtValue(); 2858 uint64_t IntSize = getTypeSize(IntTy); 2859 // GCC extension compatibility: if the bit-field size is less than or equal 2860 // to the size of int, it gets promoted no matter what its type is. 2861 // For instance, unsigned long bf : 4 gets promoted to signed int. 2862 if (BitWidth < IntSize) 2863 return IntTy; 2864 2865 if (BitWidth == IntSize) 2866 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 2867 2868 // Types bigger than int are not subject to promotions, and therefore act 2869 // like the base type. 2870 // FIXME: This doesn't quite match what gcc does, but what gcc does here 2871 // is ridiculous. 2872 return QualType(); 2873} 2874 2875/// getPromotedIntegerType - Returns the type that Promotable will 2876/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 2877/// integer type. 2878QualType ASTContext::getPromotedIntegerType(QualType Promotable) { 2879 assert(!Promotable.isNull()); 2880 assert(Promotable->isPromotableIntegerType()); 2881 if (const EnumType *ET = Promotable->getAs<EnumType>()) 2882 return ET->getDecl()->getPromotionType(); 2883 if (Promotable->isSignedIntegerType()) 2884 return IntTy; 2885 uint64_t PromotableSize = getTypeSize(Promotable); 2886 uint64_t IntSize = getTypeSize(IntTy); 2887 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 2888 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 2889} 2890 2891/// getIntegerTypeOrder - Returns the highest ranked integer type: 2892/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 2893/// LHS < RHS, return -1. 2894int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 2895 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 2896 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 2897 if (LHSC == RHSC) return 0; 2898 2899 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 2900 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 2901 2902 unsigned LHSRank = getIntegerRank(LHSC); 2903 unsigned RHSRank = getIntegerRank(RHSC); 2904 2905 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 2906 if (LHSRank == RHSRank) return 0; 2907 return LHSRank > RHSRank ? 1 : -1; 2908 } 2909 2910 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 2911 if (LHSUnsigned) { 2912 // If the unsigned [LHS] type is larger, return it. 2913 if (LHSRank >= RHSRank) 2914 return 1; 2915 2916 // If the signed type can represent all values of the unsigned type, it 2917 // wins. Because we are dealing with 2's complement and types that are 2918 // powers of two larger than each other, this is always safe. 2919 return -1; 2920 } 2921 2922 // If the unsigned [RHS] type is larger, return it. 2923 if (RHSRank >= LHSRank) 2924 return -1; 2925 2926 // If the signed type can represent all values of the unsigned type, it 2927 // wins. Because we are dealing with 2's complement and types that are 2928 // powers of two larger than each other, this is always safe. 2929 return 1; 2930} 2931 2932static RecordDecl * 2933CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC, 2934 SourceLocation L, IdentifierInfo *Id) { 2935 if (Ctx.getLangOptions().CPlusPlus) 2936 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id); 2937 else 2938 return RecordDecl::Create(Ctx, TK, DC, L, Id); 2939} 2940 2941// getCFConstantStringType - Return the type used for constant CFStrings. 2942QualType ASTContext::getCFConstantStringType() { 2943 if (!CFConstantStringTypeDecl) { 2944 CFConstantStringTypeDecl = 2945 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 2946 &Idents.get("NSConstantString")); 2947 CFConstantStringTypeDecl->startDefinition(); 2948 2949 QualType FieldTypes[4]; 2950 2951 // const int *isa; 2952 FieldTypes[0] = getPointerType(IntTy.withConst()); 2953 // int flags; 2954 FieldTypes[1] = IntTy; 2955 // const char *str; 2956 FieldTypes[2] = getPointerType(CharTy.withConst()); 2957 // long length; 2958 FieldTypes[3] = LongTy; 2959 2960 // Create fields 2961 for (unsigned i = 0; i < 4; ++i) { 2962 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 2963 SourceLocation(), 0, 2964 FieldTypes[i], /*TInfo=*/0, 2965 /*BitWidth=*/0, 2966 /*Mutable=*/false); 2967 Field->setAccess(AS_public); 2968 CFConstantStringTypeDecl->addDecl(Field); 2969 } 2970 2971 CFConstantStringTypeDecl->completeDefinition(); 2972 } 2973 2974 return getTagDeclType(CFConstantStringTypeDecl); 2975} 2976 2977void ASTContext::setCFConstantStringType(QualType T) { 2978 const RecordType *Rec = T->getAs<RecordType>(); 2979 assert(Rec && "Invalid CFConstantStringType"); 2980 CFConstantStringTypeDecl = Rec->getDecl(); 2981} 2982 2983// getNSConstantStringType - Return the type used for constant NSStrings. 2984QualType ASTContext::getNSConstantStringType() { 2985 if (!NSConstantStringTypeDecl) { 2986 NSConstantStringTypeDecl = 2987 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 2988 &Idents.get("__builtin_NSString")); 2989 NSConstantStringTypeDecl->startDefinition(); 2990 2991 QualType FieldTypes[3]; 2992 2993 // const int *isa; 2994 FieldTypes[0] = getPointerType(IntTy.withConst()); 2995 // const char *str; 2996 FieldTypes[1] = getPointerType(CharTy.withConst()); 2997 // unsigned int length; 2998 FieldTypes[2] = UnsignedIntTy; 2999 3000 // Create fields 3001 for (unsigned i = 0; i < 3; ++i) { 3002 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl, 3003 SourceLocation(), 0, 3004 FieldTypes[i], /*TInfo=*/0, 3005 /*BitWidth=*/0, 3006 /*Mutable=*/false); 3007 Field->setAccess(AS_public); 3008 NSConstantStringTypeDecl->addDecl(Field); 3009 } 3010 3011 NSConstantStringTypeDecl->completeDefinition(); 3012 } 3013 3014 return getTagDeclType(NSConstantStringTypeDecl); 3015} 3016 3017void ASTContext::setNSConstantStringType(QualType T) { 3018 const RecordType *Rec = T->getAs<RecordType>(); 3019 assert(Rec && "Invalid NSConstantStringType"); 3020 NSConstantStringTypeDecl = Rec->getDecl(); 3021} 3022 3023QualType ASTContext::getObjCFastEnumerationStateType() { 3024 if (!ObjCFastEnumerationStateTypeDecl) { 3025 ObjCFastEnumerationStateTypeDecl = 3026 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3027 &Idents.get("__objcFastEnumerationState")); 3028 ObjCFastEnumerationStateTypeDecl->startDefinition(); 3029 3030 QualType FieldTypes[] = { 3031 UnsignedLongTy, 3032 getPointerType(ObjCIdTypedefType), 3033 getPointerType(UnsignedLongTy), 3034 getConstantArrayType(UnsignedLongTy, 3035 llvm::APInt(32, 5), ArrayType::Normal, 0) 3036 }; 3037 3038 for (size_t i = 0; i < 4; ++i) { 3039 FieldDecl *Field = FieldDecl::Create(*this, 3040 ObjCFastEnumerationStateTypeDecl, 3041 SourceLocation(), 0, 3042 FieldTypes[i], /*TInfo=*/0, 3043 /*BitWidth=*/0, 3044 /*Mutable=*/false); 3045 Field->setAccess(AS_public); 3046 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 3047 } 3048 if (getLangOptions().CPlusPlus) 3049 if (CXXRecordDecl *CXXRD = 3050 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl)) 3051 CXXRD->setEmpty(false); 3052 3053 ObjCFastEnumerationStateTypeDecl->completeDefinition(); 3054 } 3055 3056 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 3057} 3058 3059QualType ASTContext::getBlockDescriptorType() { 3060 if (BlockDescriptorType) 3061 return getTagDeclType(BlockDescriptorType); 3062 3063 RecordDecl *T; 3064 // FIXME: Needs the FlagAppleBlock bit. 3065 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3066 &Idents.get("__block_descriptor")); 3067 T->startDefinition(); 3068 3069 QualType FieldTypes[] = { 3070 UnsignedLongTy, 3071 UnsignedLongTy, 3072 }; 3073 3074 const char *FieldNames[] = { 3075 "reserved", 3076 "Size" 3077 }; 3078 3079 for (size_t i = 0; i < 2; ++i) { 3080 FieldDecl *Field = FieldDecl::Create(*this, 3081 T, 3082 SourceLocation(), 3083 &Idents.get(FieldNames[i]), 3084 FieldTypes[i], /*TInfo=*/0, 3085 /*BitWidth=*/0, 3086 /*Mutable=*/false); 3087 Field->setAccess(AS_public); 3088 T->addDecl(Field); 3089 } 3090 3091 T->completeDefinition(); 3092 3093 BlockDescriptorType = T; 3094 3095 return getTagDeclType(BlockDescriptorType); 3096} 3097 3098void ASTContext::setBlockDescriptorType(QualType T) { 3099 const RecordType *Rec = T->getAs<RecordType>(); 3100 assert(Rec && "Invalid BlockDescriptorType"); 3101 BlockDescriptorType = Rec->getDecl(); 3102} 3103 3104QualType ASTContext::getBlockDescriptorExtendedType() { 3105 if (BlockDescriptorExtendedType) 3106 return getTagDeclType(BlockDescriptorExtendedType); 3107 3108 RecordDecl *T; 3109 // FIXME: Needs the FlagAppleBlock bit. 3110 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3111 &Idents.get("__block_descriptor_withcopydispose")); 3112 T->startDefinition(); 3113 3114 QualType FieldTypes[] = { 3115 UnsignedLongTy, 3116 UnsignedLongTy, 3117 getPointerType(VoidPtrTy), 3118 getPointerType(VoidPtrTy) 3119 }; 3120 3121 const char *FieldNames[] = { 3122 "reserved", 3123 "Size", 3124 "CopyFuncPtr", 3125 "DestroyFuncPtr" 3126 }; 3127 3128 for (size_t i = 0; i < 4; ++i) { 3129 FieldDecl *Field = FieldDecl::Create(*this, 3130 T, 3131 SourceLocation(), 3132 &Idents.get(FieldNames[i]), 3133 FieldTypes[i], /*TInfo=*/0, 3134 /*BitWidth=*/0, 3135 /*Mutable=*/false); 3136 Field->setAccess(AS_public); 3137 T->addDecl(Field); 3138 } 3139 3140 T->completeDefinition(); 3141 3142 BlockDescriptorExtendedType = T; 3143 3144 return getTagDeclType(BlockDescriptorExtendedType); 3145} 3146 3147void ASTContext::setBlockDescriptorExtendedType(QualType T) { 3148 const RecordType *Rec = T->getAs<RecordType>(); 3149 assert(Rec && "Invalid BlockDescriptorType"); 3150 BlockDescriptorExtendedType = Rec->getDecl(); 3151} 3152 3153bool ASTContext::BlockRequiresCopying(QualType Ty) { 3154 if (Ty->isBlockPointerType()) 3155 return true; 3156 if (isObjCNSObjectType(Ty)) 3157 return true; 3158 if (Ty->isObjCObjectPointerType()) 3159 return true; 3160 return false; 3161} 3162 3163QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) { 3164 // type = struct __Block_byref_1_X { 3165 // void *__isa; 3166 // struct __Block_byref_1_X *__forwarding; 3167 // unsigned int __flags; 3168 // unsigned int __size; 3169 // void *__copy_helper; // as needed 3170 // void *__destroy_help // as needed 3171 // int X; 3172 // } * 3173 3174 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 3175 3176 // FIXME: Move up 3177 llvm::SmallString<36> Name; 3178 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 3179 ++UniqueBlockByRefTypeID << '_' << DeclName; 3180 RecordDecl *T; 3181 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3182 &Idents.get(Name.str())); 3183 T->startDefinition(); 3184 QualType Int32Ty = IntTy; 3185 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 3186 QualType FieldTypes[] = { 3187 getPointerType(VoidPtrTy), 3188 getPointerType(getTagDeclType(T)), 3189 Int32Ty, 3190 Int32Ty, 3191 getPointerType(VoidPtrTy), 3192 getPointerType(VoidPtrTy), 3193 Ty 3194 }; 3195 3196 const char *FieldNames[] = { 3197 "__isa", 3198 "__forwarding", 3199 "__flags", 3200 "__size", 3201 "__copy_helper", 3202 "__destroy_helper", 3203 DeclName, 3204 }; 3205 3206 for (size_t i = 0; i < 7; ++i) { 3207 if (!HasCopyAndDispose && i >=4 && i <= 5) 3208 continue; 3209 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3210 &Idents.get(FieldNames[i]), 3211 FieldTypes[i], /*TInfo=*/0, 3212 /*BitWidth=*/0, /*Mutable=*/false); 3213 Field->setAccess(AS_public); 3214 T->addDecl(Field); 3215 } 3216 3217 T->completeDefinition(); 3218 3219 return getPointerType(getTagDeclType(T)); 3220} 3221 3222 3223QualType ASTContext::getBlockParmType( 3224 bool BlockHasCopyDispose, 3225 llvm::SmallVectorImpl<const Expr *> &Layout) { 3226 3227 // FIXME: Move up 3228 llvm::SmallString<36> Name; 3229 llvm::raw_svector_ostream(Name) << "__block_literal_" 3230 << ++UniqueBlockParmTypeID; 3231 RecordDecl *T; 3232 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3233 &Idents.get(Name.str())); 3234 T->startDefinition(); 3235 QualType FieldTypes[] = { 3236 getPointerType(VoidPtrTy), 3237 IntTy, 3238 IntTy, 3239 getPointerType(VoidPtrTy), 3240 (BlockHasCopyDispose ? 3241 getPointerType(getBlockDescriptorExtendedType()) : 3242 getPointerType(getBlockDescriptorType())) 3243 }; 3244 3245 const char *FieldNames[] = { 3246 "__isa", 3247 "__flags", 3248 "__reserved", 3249 "__FuncPtr", 3250 "__descriptor" 3251 }; 3252 3253 for (size_t i = 0; i < 5; ++i) { 3254 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3255 &Idents.get(FieldNames[i]), 3256 FieldTypes[i], /*TInfo=*/0, 3257 /*BitWidth=*/0, /*Mutable=*/false); 3258 Field->setAccess(AS_public); 3259 T->addDecl(Field); 3260 } 3261 3262 for (unsigned i = 0; i < Layout.size(); ++i) { 3263 const Expr *E = Layout[i]; 3264 3265 QualType FieldType = E->getType(); 3266 IdentifierInfo *FieldName = 0; 3267 if (isa<CXXThisExpr>(E)) { 3268 FieldName = &Idents.get("this"); 3269 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) { 3270 const ValueDecl *D = BDRE->getDecl(); 3271 FieldName = D->getIdentifier(); 3272 if (BDRE->isByRef()) 3273 FieldType = BuildByRefType(D->getNameAsCString(), FieldType); 3274 } else { 3275 // Padding. 3276 assert(isa<ConstantArrayType>(FieldType) && 3277 isa<DeclRefExpr>(E) && 3278 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() && 3279 "doesn't match characteristics of padding decl"); 3280 } 3281 3282 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3283 FieldName, FieldType, /*TInfo=*/0, 3284 /*BitWidth=*/0, /*Mutable=*/false); 3285 Field->setAccess(AS_public); 3286 T->addDecl(Field); 3287 } 3288 3289 T->completeDefinition(); 3290 3291 return getPointerType(getTagDeclType(T)); 3292} 3293 3294void ASTContext::setObjCFastEnumerationStateType(QualType T) { 3295 const RecordType *Rec = T->getAs<RecordType>(); 3296 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 3297 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 3298} 3299 3300// This returns true if a type has been typedefed to BOOL: 3301// typedef <type> BOOL; 3302static bool isTypeTypedefedAsBOOL(QualType T) { 3303 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 3304 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 3305 return II->isStr("BOOL"); 3306 3307 return false; 3308} 3309 3310/// getObjCEncodingTypeSize returns size of type for objective-c encoding 3311/// purpose. 3312CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) { 3313 CharUnits sz = getTypeSizeInChars(type); 3314 3315 // Make all integer and enum types at least as large as an int 3316 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 3317 sz = std::max(sz, getTypeSizeInChars(IntTy)); 3318 // Treat arrays as pointers, since that's how they're passed in. 3319 else if (type->isArrayType()) 3320 sz = getTypeSizeInChars(VoidPtrTy); 3321 return sz; 3322} 3323 3324static inline 3325std::string charUnitsToString(const CharUnits &CU) { 3326 return llvm::itostr(CU.getQuantity()); 3327} 3328 3329/// getObjCEncodingForBlockDecl - Return the encoded type for this block 3330/// declaration. 3331void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr, 3332 std::string& S) { 3333 const BlockDecl *Decl = Expr->getBlockDecl(); 3334 QualType BlockTy = 3335 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 3336 // Encode result type. 3337 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 3338 // Compute size of all parameters. 3339 // Start with computing size of a pointer in number of bytes. 3340 // FIXME: There might(should) be a better way of doing this computation! 3341 SourceLocation Loc; 3342 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3343 CharUnits ParmOffset = PtrSize; 3344 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 3345 E = Decl->param_end(); PI != E; ++PI) { 3346 QualType PType = (*PI)->getType(); 3347 CharUnits sz = getObjCEncodingTypeSize(PType); 3348 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 3349 ParmOffset += sz; 3350 } 3351 // Size of the argument frame 3352 S += charUnitsToString(ParmOffset); 3353 // Block pointer and offset. 3354 S += "@?0"; 3355 ParmOffset = PtrSize; 3356 3357 // Argument types. 3358 ParmOffset = PtrSize; 3359 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 3360 Decl->param_end(); PI != E; ++PI) { 3361 ParmVarDecl *PVDecl = *PI; 3362 QualType PType = PVDecl->getOriginalType(); 3363 if (const ArrayType *AT = 3364 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3365 // Use array's original type only if it has known number of 3366 // elements. 3367 if (!isa<ConstantArrayType>(AT)) 3368 PType = PVDecl->getType(); 3369 } else if (PType->isFunctionType()) 3370 PType = PVDecl->getType(); 3371 getObjCEncodingForType(PType, S); 3372 S += charUnitsToString(ParmOffset); 3373 ParmOffset += getObjCEncodingTypeSize(PType); 3374 } 3375} 3376 3377/// getObjCEncodingForMethodDecl - Return the encoded type for this method 3378/// declaration. 3379void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 3380 std::string& S) { 3381 // FIXME: This is not very efficient. 3382 // Encode type qualifer, 'in', 'inout', etc. for the return type. 3383 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 3384 // Encode result type. 3385 getObjCEncodingForType(Decl->getResultType(), S); 3386 // Compute size of all parameters. 3387 // Start with computing size of a pointer in number of bytes. 3388 // FIXME: There might(should) be a better way of doing this computation! 3389 SourceLocation Loc; 3390 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3391 // The first two arguments (self and _cmd) are pointers; account for 3392 // their size. 3393 CharUnits ParmOffset = 2 * PtrSize; 3394 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3395 E = Decl->sel_param_end(); PI != E; ++PI) { 3396 QualType PType = (*PI)->getType(); 3397 CharUnits sz = getObjCEncodingTypeSize(PType); 3398 assert (sz.isPositive() && 3399 "getObjCEncodingForMethodDecl - Incomplete param type"); 3400 ParmOffset += sz; 3401 } 3402 S += charUnitsToString(ParmOffset); 3403 S += "@0:"; 3404 S += charUnitsToString(PtrSize); 3405 3406 // Argument types. 3407 ParmOffset = 2 * PtrSize; 3408 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3409 E = Decl->sel_param_end(); PI != E; ++PI) { 3410 ParmVarDecl *PVDecl = *PI; 3411 QualType PType = PVDecl->getOriginalType(); 3412 if (const ArrayType *AT = 3413 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3414 // Use array's original type only if it has known number of 3415 // elements. 3416 if (!isa<ConstantArrayType>(AT)) 3417 PType = PVDecl->getType(); 3418 } else if (PType->isFunctionType()) 3419 PType = PVDecl->getType(); 3420 // Process argument qualifiers for user supplied arguments; such as, 3421 // 'in', 'inout', etc. 3422 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 3423 getObjCEncodingForType(PType, S); 3424 S += charUnitsToString(ParmOffset); 3425 ParmOffset += getObjCEncodingTypeSize(PType); 3426 } 3427} 3428 3429/// getObjCEncodingForPropertyDecl - Return the encoded type for this 3430/// property declaration. If non-NULL, Container must be either an 3431/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 3432/// NULL when getting encodings for protocol properties. 3433/// Property attributes are stored as a comma-delimited C string. The simple 3434/// attributes readonly and bycopy are encoded as single characters. The 3435/// parametrized attributes, getter=name, setter=name, and ivar=name, are 3436/// encoded as single characters, followed by an identifier. Property types 3437/// are also encoded as a parametrized attribute. The characters used to encode 3438/// these attributes are defined by the following enumeration: 3439/// @code 3440/// enum PropertyAttributes { 3441/// kPropertyReadOnly = 'R', // property is read-only. 3442/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 3443/// kPropertyByref = '&', // property is a reference to the value last assigned 3444/// kPropertyDynamic = 'D', // property is dynamic 3445/// kPropertyGetter = 'G', // followed by getter selector name 3446/// kPropertySetter = 'S', // followed by setter selector name 3447/// kPropertyInstanceVariable = 'V' // followed by instance variable name 3448/// kPropertyType = 't' // followed by old-style type encoding. 3449/// kPropertyWeak = 'W' // 'weak' property 3450/// kPropertyStrong = 'P' // property GC'able 3451/// kPropertyNonAtomic = 'N' // property non-atomic 3452/// }; 3453/// @endcode 3454void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 3455 const Decl *Container, 3456 std::string& S) { 3457 // Collect information from the property implementation decl(s). 3458 bool Dynamic = false; 3459 ObjCPropertyImplDecl *SynthesizePID = 0; 3460 3461 // FIXME: Duplicated code due to poor abstraction. 3462 if (Container) { 3463 if (const ObjCCategoryImplDecl *CID = 3464 dyn_cast<ObjCCategoryImplDecl>(Container)) { 3465 for (ObjCCategoryImplDecl::propimpl_iterator 3466 i = CID->propimpl_begin(), e = CID->propimpl_end(); 3467 i != e; ++i) { 3468 ObjCPropertyImplDecl *PID = *i; 3469 if (PID->getPropertyDecl() == PD) { 3470 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3471 Dynamic = true; 3472 } else { 3473 SynthesizePID = PID; 3474 } 3475 } 3476 } 3477 } else { 3478 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 3479 for (ObjCCategoryImplDecl::propimpl_iterator 3480 i = OID->propimpl_begin(), e = OID->propimpl_end(); 3481 i != e; ++i) { 3482 ObjCPropertyImplDecl *PID = *i; 3483 if (PID->getPropertyDecl() == PD) { 3484 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3485 Dynamic = true; 3486 } else { 3487 SynthesizePID = PID; 3488 } 3489 } 3490 } 3491 } 3492 } 3493 3494 // FIXME: This is not very efficient. 3495 S = "T"; 3496 3497 // Encode result type. 3498 // GCC has some special rules regarding encoding of properties which 3499 // closely resembles encoding of ivars. 3500 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 3501 true /* outermost type */, 3502 true /* encoding for property */); 3503 3504 if (PD->isReadOnly()) { 3505 S += ",R"; 3506 } else { 3507 switch (PD->getSetterKind()) { 3508 case ObjCPropertyDecl::Assign: break; 3509 case ObjCPropertyDecl::Copy: S += ",C"; break; 3510 case ObjCPropertyDecl::Retain: S += ",&"; break; 3511 } 3512 } 3513 3514 // It really isn't clear at all what this means, since properties 3515 // are "dynamic by default". 3516 if (Dynamic) 3517 S += ",D"; 3518 3519 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 3520 S += ",N"; 3521 3522 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 3523 S += ",G"; 3524 S += PD->getGetterName().getAsString(); 3525 } 3526 3527 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 3528 S += ",S"; 3529 S += PD->getSetterName().getAsString(); 3530 } 3531 3532 if (SynthesizePID) { 3533 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 3534 S += ",V"; 3535 S += OID->getNameAsString(); 3536 } 3537 3538 // FIXME: OBJCGC: weak & strong 3539} 3540 3541/// getLegacyIntegralTypeEncoding - 3542/// Another legacy compatibility encoding: 32-bit longs are encoded as 3543/// 'l' or 'L' , but not always. For typedefs, we need to use 3544/// 'i' or 'I' instead if encoding a struct field, or a pointer! 3545/// 3546void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 3547 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 3548 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 3549 if (BT->getKind() == BuiltinType::ULong && 3550 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3551 PointeeTy = UnsignedIntTy; 3552 else 3553 if (BT->getKind() == BuiltinType::Long && 3554 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3555 PointeeTy = IntTy; 3556 } 3557 } 3558} 3559 3560void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 3561 const FieldDecl *Field) { 3562 // We follow the behavior of gcc, expanding structures which are 3563 // directly pointed to, and expanding embedded structures. Note that 3564 // these rules are sufficient to prevent recursive encoding of the 3565 // same type. 3566 getObjCEncodingForTypeImpl(T, S, true, true, Field, 3567 true /* outermost type */); 3568} 3569 3570static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 3571 switch (T->getAs<BuiltinType>()->getKind()) { 3572 default: assert(0 && "Unhandled builtin type kind"); 3573 case BuiltinType::Void: return 'v'; 3574 case BuiltinType::Bool: return 'B'; 3575 case BuiltinType::Char_U: 3576 case BuiltinType::UChar: return 'C'; 3577 case BuiltinType::UShort: return 'S'; 3578 case BuiltinType::UInt: return 'I'; 3579 case BuiltinType::ULong: 3580 return 3581 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q'; 3582 case BuiltinType::UInt128: return 'T'; 3583 case BuiltinType::ULongLong: return 'Q'; 3584 case BuiltinType::Char_S: 3585 case BuiltinType::SChar: return 'c'; 3586 case BuiltinType::Short: return 's'; 3587 case BuiltinType::WChar: 3588 case BuiltinType::Int: return 'i'; 3589 case BuiltinType::Long: 3590 return 3591 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q'; 3592 case BuiltinType::LongLong: return 'q'; 3593 case BuiltinType::Int128: return 't'; 3594 case BuiltinType::Float: return 'f'; 3595 case BuiltinType::Double: return 'd'; 3596 case BuiltinType::LongDouble: return 'd'; 3597 } 3598} 3599 3600static void EncodeBitField(const ASTContext *Context, std::string& S, 3601 QualType T, const FieldDecl *FD) { 3602 const Expr *E = FD->getBitWidth(); 3603 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 3604 ASTContext *Ctx = const_cast<ASTContext*>(Context); 3605 S += 'b'; 3606 // The NeXT runtime encodes bit fields as b followed by the number of bits. 3607 // The GNU runtime requires more information; bitfields are encoded as b, 3608 // then the offset (in bits) of the first element, then the type of the 3609 // bitfield, then the size in bits. For example, in this structure: 3610 // 3611 // struct 3612 // { 3613 // int integer; 3614 // int flags:2; 3615 // }; 3616 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 3617 // runtime, but b32i2 for the GNU runtime. The reason for this extra 3618 // information is not especially sensible, but we're stuck with it for 3619 // compatibility with GCC, although providing it breaks anything that 3620 // actually uses runtime introspection and wants to work on both runtimes... 3621 if (!Ctx->getLangOptions().NeXTRuntime) { 3622 const RecordDecl *RD = FD->getParent(); 3623 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 3624 // FIXME: This same linear search is also used in ExprConstant - it might 3625 // be better if the FieldDecl stored its offset. We'd be increasing the 3626 // size of the object slightly, but saving some time every time it is used. 3627 unsigned i = 0; 3628 for (RecordDecl::field_iterator Field = RD->field_begin(), 3629 FieldEnd = RD->field_end(); 3630 Field != FieldEnd; (void)++Field, ++i) { 3631 if (*Field == FD) 3632 break; 3633 } 3634 S += llvm::utostr(RL.getFieldOffset(i)); 3635 S += ObjCEncodingForPrimitiveKind(Context, T); 3636 } 3637 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 3638 S += llvm::utostr(N); 3639} 3640 3641// FIXME: Use SmallString for accumulating string. 3642void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 3643 bool ExpandPointedToStructures, 3644 bool ExpandStructures, 3645 const FieldDecl *FD, 3646 bool OutermostType, 3647 bool EncodingProperty) { 3648 if (T->getAs<BuiltinType>()) { 3649 if (FD && FD->isBitField()) 3650 return EncodeBitField(this, S, T, FD); 3651 S += ObjCEncodingForPrimitiveKind(this, T); 3652 return; 3653 } 3654 3655 if (const ComplexType *CT = T->getAs<ComplexType>()) { 3656 S += 'j'; 3657 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 3658 false); 3659 return; 3660 } 3661 3662 // encoding for pointer or r3eference types. 3663 QualType PointeeTy; 3664 if (const PointerType *PT = T->getAs<PointerType>()) { 3665 if (PT->isObjCSelType()) { 3666 S += ':'; 3667 return; 3668 } 3669 PointeeTy = PT->getPointeeType(); 3670 } 3671 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3672 PointeeTy = RT->getPointeeType(); 3673 if (!PointeeTy.isNull()) { 3674 bool isReadOnly = false; 3675 // For historical/compatibility reasons, the read-only qualifier of the 3676 // pointee gets emitted _before_ the '^'. The read-only qualifier of 3677 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 3678 // Also, do not emit the 'r' for anything but the outermost type! 3679 if (isa<TypedefType>(T.getTypePtr())) { 3680 if (OutermostType && T.isConstQualified()) { 3681 isReadOnly = true; 3682 S += 'r'; 3683 } 3684 } else if (OutermostType) { 3685 QualType P = PointeeTy; 3686 while (P->getAs<PointerType>()) 3687 P = P->getAs<PointerType>()->getPointeeType(); 3688 if (P.isConstQualified()) { 3689 isReadOnly = true; 3690 S += 'r'; 3691 } 3692 } 3693 if (isReadOnly) { 3694 // Another legacy compatibility encoding. Some ObjC qualifier and type 3695 // combinations need to be rearranged. 3696 // Rewrite "in const" from "nr" to "rn" 3697 if (llvm::StringRef(S).endswith("nr")) 3698 S.replace(S.end()-2, S.end(), "rn"); 3699 } 3700 3701 if (PointeeTy->isCharType()) { 3702 // char pointer types should be encoded as '*' unless it is a 3703 // type that has been typedef'd to 'BOOL'. 3704 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 3705 S += '*'; 3706 return; 3707 } 3708 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 3709 // GCC binary compat: Need to convert "struct objc_class *" to "#". 3710 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 3711 S += '#'; 3712 return; 3713 } 3714 // GCC binary compat: Need to convert "struct objc_object *" to "@". 3715 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 3716 S += '@'; 3717 return; 3718 } 3719 // fall through... 3720 } 3721 S += '^'; 3722 getLegacyIntegralTypeEncoding(PointeeTy); 3723 3724 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 3725 NULL); 3726 return; 3727 } 3728 3729 if (const ArrayType *AT = 3730 // Ignore type qualifiers etc. 3731 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 3732 if (isa<IncompleteArrayType>(AT)) { 3733 // Incomplete arrays are encoded as a pointer to the array element. 3734 S += '^'; 3735 3736 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3737 false, ExpandStructures, FD); 3738 } else { 3739 S += '['; 3740 3741 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 3742 S += llvm::utostr(CAT->getSize().getZExtValue()); 3743 else { 3744 //Variable length arrays are encoded as a regular array with 0 elements. 3745 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 3746 S += '0'; 3747 } 3748 3749 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3750 false, ExpandStructures, FD); 3751 S += ']'; 3752 } 3753 return; 3754 } 3755 3756 if (T->getAs<FunctionType>()) { 3757 S += '?'; 3758 return; 3759 } 3760 3761 if (const RecordType *RTy = T->getAs<RecordType>()) { 3762 RecordDecl *RDecl = RTy->getDecl(); 3763 S += RDecl->isUnion() ? '(' : '{'; 3764 // Anonymous structures print as '?' 3765 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 3766 S += II->getName(); 3767 if (ClassTemplateSpecializationDecl *Spec 3768 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 3769 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 3770 std::string TemplateArgsStr 3771 = TemplateSpecializationType::PrintTemplateArgumentList( 3772 TemplateArgs.getFlatArgumentList(), 3773 TemplateArgs.flat_size(), 3774 (*this).PrintingPolicy); 3775 3776 S += TemplateArgsStr; 3777 } 3778 } else { 3779 S += '?'; 3780 } 3781 if (ExpandStructures) { 3782 S += '='; 3783 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 3784 FieldEnd = RDecl->field_end(); 3785 Field != FieldEnd; ++Field) { 3786 if (FD) { 3787 S += '"'; 3788 S += Field->getNameAsString(); 3789 S += '"'; 3790 } 3791 3792 // Special case bit-fields. 3793 if (Field->isBitField()) { 3794 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 3795 (*Field)); 3796 } else { 3797 QualType qt = Field->getType(); 3798 getLegacyIntegralTypeEncoding(qt); 3799 getObjCEncodingForTypeImpl(qt, S, false, true, 3800 FD); 3801 } 3802 } 3803 } 3804 S += RDecl->isUnion() ? ')' : '}'; 3805 return; 3806 } 3807 3808 if (T->isEnumeralType()) { 3809 if (FD && FD->isBitField()) 3810 EncodeBitField(this, S, T, FD); 3811 else 3812 S += 'i'; 3813 return; 3814 } 3815 3816 if (T->isBlockPointerType()) { 3817 S += "@?"; // Unlike a pointer-to-function, which is "^?". 3818 return; 3819 } 3820 3821 // Ignore protocol qualifiers when mangling at this level. 3822 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 3823 T = OT->getBaseType(); 3824 3825 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 3826 // @encode(class_name) 3827 ObjCInterfaceDecl *OI = OIT->getDecl(); 3828 S += '{'; 3829 const IdentifierInfo *II = OI->getIdentifier(); 3830 S += II->getName(); 3831 S += '='; 3832 llvm::SmallVector<FieldDecl*, 32> RecFields; 3833 CollectObjCIvars(OI, RecFields); 3834 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 3835 if (RecFields[i]->isBitField()) 3836 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 3837 RecFields[i]); 3838 else 3839 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 3840 FD); 3841 } 3842 S += '}'; 3843 return; 3844 } 3845 3846 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 3847 if (OPT->isObjCIdType()) { 3848 S += '@'; 3849 return; 3850 } 3851 3852 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 3853 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 3854 // Since this is a binary compatibility issue, need to consult with runtime 3855 // folks. Fortunately, this is a *very* obsure construct. 3856 S += '#'; 3857 return; 3858 } 3859 3860 if (OPT->isObjCQualifiedIdType()) { 3861 getObjCEncodingForTypeImpl(getObjCIdType(), S, 3862 ExpandPointedToStructures, 3863 ExpandStructures, FD); 3864 if (FD || EncodingProperty) { 3865 // Note that we do extended encoding of protocol qualifer list 3866 // Only when doing ivar or property encoding. 3867 S += '"'; 3868 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 3869 E = OPT->qual_end(); I != E; ++I) { 3870 S += '<'; 3871 S += (*I)->getNameAsString(); 3872 S += '>'; 3873 } 3874 S += '"'; 3875 } 3876 return; 3877 } 3878 3879 QualType PointeeTy = OPT->getPointeeType(); 3880 if (!EncodingProperty && 3881 isa<TypedefType>(PointeeTy.getTypePtr())) { 3882 // Another historical/compatibility reason. 3883 // We encode the underlying type which comes out as 3884 // {...}; 3885 S += '^'; 3886 getObjCEncodingForTypeImpl(PointeeTy, S, 3887 false, ExpandPointedToStructures, 3888 NULL); 3889 return; 3890 } 3891 3892 S += '@'; 3893 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) { 3894 S += '"'; 3895 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 3896 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 3897 E = OPT->qual_end(); I != E; ++I) { 3898 S += '<'; 3899 S += (*I)->getNameAsString(); 3900 S += '>'; 3901 } 3902 S += '"'; 3903 } 3904 return; 3905 } 3906 3907 // gcc just blithely ignores member pointers. 3908 // TODO: maybe there should be a mangling for these 3909 if (T->getAs<MemberPointerType>()) 3910 return; 3911 3912 assert(0 && "@encode for type not implemented!"); 3913} 3914 3915void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 3916 std::string& S) const { 3917 if (QT & Decl::OBJC_TQ_In) 3918 S += 'n'; 3919 if (QT & Decl::OBJC_TQ_Inout) 3920 S += 'N'; 3921 if (QT & Decl::OBJC_TQ_Out) 3922 S += 'o'; 3923 if (QT & Decl::OBJC_TQ_Bycopy) 3924 S += 'O'; 3925 if (QT & Decl::OBJC_TQ_Byref) 3926 S += 'R'; 3927 if (QT & Decl::OBJC_TQ_Oneway) 3928 S += 'V'; 3929} 3930 3931void ASTContext::setBuiltinVaListType(QualType T) { 3932 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 3933 3934 BuiltinVaListType = T; 3935} 3936 3937void ASTContext::setObjCIdType(QualType T) { 3938 ObjCIdTypedefType = T; 3939} 3940 3941void ASTContext::setObjCSelType(QualType T) { 3942 ObjCSelTypedefType = T; 3943} 3944 3945void ASTContext::setObjCProtoType(QualType QT) { 3946 ObjCProtoType = QT; 3947} 3948 3949void ASTContext::setObjCClassType(QualType T) { 3950 ObjCClassTypedefType = T; 3951} 3952 3953void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 3954 assert(ObjCConstantStringType.isNull() && 3955 "'NSConstantString' type already set!"); 3956 3957 ObjCConstantStringType = getObjCInterfaceType(Decl); 3958} 3959 3960/// \brief Retrieve the template name that corresponds to a non-empty 3961/// lookup. 3962TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 3963 UnresolvedSetIterator End) { 3964 unsigned size = End - Begin; 3965 assert(size > 1 && "set is not overloaded!"); 3966 3967 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 3968 size * sizeof(FunctionTemplateDecl*)); 3969 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 3970 3971 NamedDecl **Storage = OT->getStorage(); 3972 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 3973 NamedDecl *D = *I; 3974 assert(isa<FunctionTemplateDecl>(D) || 3975 (isa<UsingShadowDecl>(D) && 3976 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 3977 *Storage++ = D; 3978 } 3979 3980 return TemplateName(OT); 3981} 3982 3983/// \brief Retrieve the template name that represents a qualified 3984/// template name such as \c std::vector. 3985TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 3986 bool TemplateKeyword, 3987 TemplateDecl *Template) { 3988 // FIXME: Canonicalization? 3989 llvm::FoldingSetNodeID ID; 3990 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 3991 3992 void *InsertPos = 0; 3993 QualifiedTemplateName *QTN = 3994 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 3995 if (!QTN) { 3996 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 3997 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 3998 } 3999 4000 return TemplateName(QTN); 4001} 4002 4003/// \brief Retrieve the template name that represents a dependent 4004/// template name such as \c MetaFun::template apply. 4005TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4006 const IdentifierInfo *Name) { 4007 assert((!NNS || NNS->isDependent()) && 4008 "Nested name specifier must be dependent"); 4009 4010 llvm::FoldingSetNodeID ID; 4011 DependentTemplateName::Profile(ID, NNS, Name); 4012 4013 void *InsertPos = 0; 4014 DependentTemplateName *QTN = 4015 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4016 4017 if (QTN) 4018 return TemplateName(QTN); 4019 4020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4021 if (CanonNNS == NNS) { 4022 QTN = new (*this,4) DependentTemplateName(NNS, Name); 4023 } else { 4024 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 4025 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 4026 DependentTemplateName *CheckQTN = 4027 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4028 assert(!CheckQTN && "Dependent type name canonicalization broken"); 4029 (void)CheckQTN; 4030 } 4031 4032 DependentTemplateNames.InsertNode(QTN, InsertPos); 4033 return TemplateName(QTN); 4034} 4035 4036/// \brief Retrieve the template name that represents a dependent 4037/// template name such as \c MetaFun::template operator+. 4038TemplateName 4039ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4040 OverloadedOperatorKind Operator) { 4041 assert((!NNS || NNS->isDependent()) && 4042 "Nested name specifier must be dependent"); 4043 4044 llvm::FoldingSetNodeID ID; 4045 DependentTemplateName::Profile(ID, NNS, Operator); 4046 4047 void *InsertPos = 0; 4048 DependentTemplateName *QTN 4049 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4050 4051 if (QTN) 4052 return TemplateName(QTN); 4053 4054 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4055 if (CanonNNS == NNS) { 4056 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 4057 } else { 4058 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 4059 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 4060 4061 DependentTemplateName *CheckQTN 4062 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4063 assert(!CheckQTN && "Dependent template name canonicalization broken"); 4064 (void)CheckQTN; 4065 } 4066 4067 DependentTemplateNames.InsertNode(QTN, InsertPos); 4068 return TemplateName(QTN); 4069} 4070 4071/// getFromTargetType - Given one of the integer types provided by 4072/// TargetInfo, produce the corresponding type. The unsigned @p Type 4073/// is actually a value of type @c TargetInfo::IntType. 4074CanQualType ASTContext::getFromTargetType(unsigned Type) const { 4075 switch (Type) { 4076 case TargetInfo::NoInt: return CanQualType(); 4077 case TargetInfo::SignedShort: return ShortTy; 4078 case TargetInfo::UnsignedShort: return UnsignedShortTy; 4079 case TargetInfo::SignedInt: return IntTy; 4080 case TargetInfo::UnsignedInt: return UnsignedIntTy; 4081 case TargetInfo::SignedLong: return LongTy; 4082 case TargetInfo::UnsignedLong: return UnsignedLongTy; 4083 case TargetInfo::SignedLongLong: return LongLongTy; 4084 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 4085 } 4086 4087 assert(false && "Unhandled TargetInfo::IntType value"); 4088 return CanQualType(); 4089} 4090 4091//===----------------------------------------------------------------------===// 4092// Type Predicates. 4093//===----------------------------------------------------------------------===// 4094 4095/// isObjCNSObjectType - Return true if this is an NSObject object using 4096/// NSObject attribute on a c-style pointer type. 4097/// FIXME - Make it work directly on types. 4098/// FIXME: Move to Type. 4099/// 4100bool ASTContext::isObjCNSObjectType(QualType Ty) const { 4101 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 4102 if (TypedefDecl *TD = TDT->getDecl()) 4103 if (TD->getAttr<ObjCNSObjectAttr>()) 4104 return true; 4105 } 4106 return false; 4107} 4108 4109/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 4110/// garbage collection attribute. 4111/// 4112Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 4113 Qualifiers::GC GCAttrs = Qualifiers::GCNone; 4114 if (getLangOptions().ObjC1 && 4115 getLangOptions().getGCMode() != LangOptions::NonGC) { 4116 GCAttrs = Ty.getObjCGCAttr(); 4117 // Default behavious under objective-c's gc is for objective-c pointers 4118 // (or pointers to them) be treated as though they were declared 4119 // as __strong. 4120 if (GCAttrs == Qualifiers::GCNone) { 4121 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4122 GCAttrs = Qualifiers::Strong; 4123 else if (Ty->isPointerType()) 4124 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 4125 } 4126 // Non-pointers have none gc'able attribute regardless of the attribute 4127 // set on them. 4128 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType()) 4129 return Qualifiers::GCNone; 4130 } 4131 return GCAttrs; 4132} 4133 4134//===----------------------------------------------------------------------===// 4135// Type Compatibility Testing 4136//===----------------------------------------------------------------------===// 4137 4138/// areCompatVectorTypes - Return true if the two specified vector types are 4139/// compatible. 4140static bool areCompatVectorTypes(const VectorType *LHS, 4141 const VectorType *RHS) { 4142 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 4143 return LHS->getElementType() == RHS->getElementType() && 4144 LHS->getNumElements() == RHS->getNumElements(); 4145} 4146 4147//===----------------------------------------------------------------------===// 4148// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 4149//===----------------------------------------------------------------------===// 4150 4151/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 4152/// inheritance hierarchy of 'rProto'. 4153bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 4154 ObjCProtocolDecl *rProto) { 4155 if (lProto == rProto) 4156 return true; 4157 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 4158 E = rProto->protocol_end(); PI != E; ++PI) 4159 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 4160 return true; 4161 return false; 4162} 4163 4164/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 4165/// return true if lhs's protocols conform to rhs's protocol; false 4166/// otherwise. 4167bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 4168 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 4169 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 4170 return false; 4171} 4172 4173/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 4174/// ObjCQualifiedIDType. 4175bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 4176 bool compare) { 4177 // Allow id<P..> and an 'id' or void* type in all cases. 4178 if (lhs->isVoidPointerType() || 4179 lhs->isObjCIdType() || lhs->isObjCClassType()) 4180 return true; 4181 else if (rhs->isVoidPointerType() || 4182 rhs->isObjCIdType() || rhs->isObjCClassType()) 4183 return true; 4184 4185 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 4186 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 4187 4188 if (!rhsOPT) return false; 4189 4190 if (rhsOPT->qual_empty()) { 4191 // If the RHS is a unqualified interface pointer "NSString*", 4192 // make sure we check the class hierarchy. 4193 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4194 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4195 E = lhsQID->qual_end(); I != E; ++I) { 4196 // when comparing an id<P> on lhs with a static type on rhs, 4197 // see if static class implements all of id's protocols, directly or 4198 // through its super class and categories. 4199 if (!rhsID->ClassImplementsProtocol(*I, true)) 4200 return false; 4201 } 4202 } 4203 // If there are no qualifiers and no interface, we have an 'id'. 4204 return true; 4205 } 4206 // Both the right and left sides have qualifiers. 4207 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4208 E = lhsQID->qual_end(); I != E; ++I) { 4209 ObjCProtocolDecl *lhsProto = *I; 4210 bool match = false; 4211 4212 // when comparing an id<P> on lhs with a static type on rhs, 4213 // see if static class implements all of id's protocols, directly or 4214 // through its super class and categories. 4215 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 4216 E = rhsOPT->qual_end(); J != E; ++J) { 4217 ObjCProtocolDecl *rhsProto = *J; 4218 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4219 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4220 match = true; 4221 break; 4222 } 4223 } 4224 // If the RHS is a qualified interface pointer "NSString<P>*", 4225 // make sure we check the class hierarchy. 4226 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4227 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4228 E = lhsQID->qual_end(); I != E; ++I) { 4229 // when comparing an id<P> on lhs with a static type on rhs, 4230 // see if static class implements all of id's protocols, directly or 4231 // through its super class and categories. 4232 if (rhsID->ClassImplementsProtocol(*I, true)) { 4233 match = true; 4234 break; 4235 } 4236 } 4237 } 4238 if (!match) 4239 return false; 4240 } 4241 4242 return true; 4243 } 4244 4245 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 4246 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 4247 4248 if (const ObjCObjectPointerType *lhsOPT = 4249 lhs->getAsObjCInterfacePointerType()) { 4250 if (lhsOPT->qual_empty()) { 4251 bool match = false; 4252 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 4253 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(), 4254 E = rhsQID->qual_end(); I != E; ++I) { 4255 // when comparing an id<P> on lhs with a static type on rhs, 4256 // see if static class implements all of id's protocols, directly or 4257 // through its super class and categories. 4258 if (lhsID->ClassImplementsProtocol(*I, true)) { 4259 match = true; 4260 break; 4261 } 4262 } 4263 if (!match) 4264 return false; 4265 } 4266 return true; 4267 } 4268 // Both the right and left sides have qualifiers. 4269 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 4270 E = lhsOPT->qual_end(); I != E; ++I) { 4271 ObjCProtocolDecl *lhsProto = *I; 4272 bool match = false; 4273 4274 // when comparing an id<P> on lhs with a static type on rhs, 4275 // see if static class implements all of id's protocols, directly or 4276 // through its super class and categories. 4277 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 4278 E = rhsQID->qual_end(); J != E; ++J) { 4279 ObjCProtocolDecl *rhsProto = *J; 4280 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4281 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4282 match = true; 4283 break; 4284 } 4285 } 4286 if (!match) 4287 return false; 4288 } 4289 return true; 4290 } 4291 return false; 4292} 4293 4294/// canAssignObjCInterfaces - Return true if the two interface types are 4295/// compatible for assignment from RHS to LHS. This handles validation of any 4296/// protocol qualifiers on the LHS or RHS. 4297/// 4298bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 4299 const ObjCObjectPointerType *RHSOPT) { 4300 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4301 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4302 4303 // If either type represents the built-in 'id' or 'Class' types, return true. 4304 if (LHS->isObjCUnqualifiedIdOrClass() || 4305 RHS->isObjCUnqualifiedIdOrClass()) 4306 return true; 4307 4308 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 4309 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4310 QualType(RHSOPT,0), 4311 false); 4312 4313 // If we have 2 user-defined types, fall into that path. 4314 if (LHS->getInterface() && RHS->getInterface()) 4315 return canAssignObjCInterfaces(LHS, RHS); 4316 4317 return false; 4318} 4319 4320/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 4321/// for providing type-safty for objective-c pointers used to pass/return 4322/// arguments in block literals. When passed as arguments, passing 'A*' where 4323/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 4324/// not OK. For the return type, the opposite is not OK. 4325bool ASTContext::canAssignObjCInterfacesInBlockPointer( 4326 const ObjCObjectPointerType *LHSOPT, 4327 const ObjCObjectPointerType *RHSOPT) { 4328 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 4329 return true; 4330 4331 if (LHSOPT->isObjCBuiltinType()) { 4332 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 4333 } 4334 4335 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 4336 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4337 QualType(RHSOPT,0), 4338 false); 4339 4340 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 4341 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 4342 if (LHS && RHS) { // We have 2 user-defined types. 4343 if (LHS != RHS) { 4344 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 4345 return false; 4346 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 4347 return true; 4348 } 4349 else 4350 return true; 4351 } 4352 return false; 4353} 4354 4355/// getIntersectionOfProtocols - This routine finds the intersection of set 4356/// of protocols inherited from two distinct objective-c pointer objects. 4357/// It is used to build composite qualifier list of the composite type of 4358/// the conditional expression involving two objective-c pointer objects. 4359static 4360void getIntersectionOfProtocols(ASTContext &Context, 4361 const ObjCObjectPointerType *LHSOPT, 4362 const ObjCObjectPointerType *RHSOPT, 4363 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 4364 4365 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4366 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4367 assert(LHS->getInterface() && "LHS must have an interface base"); 4368 assert(RHS->getInterface() && "RHS must have an interface base"); 4369 4370 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 4371 unsigned LHSNumProtocols = LHS->getNumProtocols(); 4372 if (LHSNumProtocols > 0) 4373 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 4374 else { 4375 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 4376 Context.CollectInheritedProtocols(LHS->getInterface(), 4377 LHSInheritedProtocols); 4378 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 4379 LHSInheritedProtocols.end()); 4380 } 4381 4382 unsigned RHSNumProtocols = RHS->getNumProtocols(); 4383 if (RHSNumProtocols > 0) { 4384 ObjCProtocolDecl **RHSProtocols = 4385 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 4386 for (unsigned i = 0; i < RHSNumProtocols; ++i) 4387 if (InheritedProtocolSet.count(RHSProtocols[i])) 4388 IntersectionOfProtocols.push_back(RHSProtocols[i]); 4389 } 4390 else { 4391 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 4392 Context.CollectInheritedProtocols(RHS->getInterface(), 4393 RHSInheritedProtocols); 4394 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 4395 RHSInheritedProtocols.begin(), 4396 E = RHSInheritedProtocols.end(); I != E; ++I) 4397 if (InheritedProtocolSet.count((*I))) 4398 IntersectionOfProtocols.push_back((*I)); 4399 } 4400} 4401 4402/// areCommonBaseCompatible - Returns common base class of the two classes if 4403/// one found. Note that this is O'2 algorithm. But it will be called as the 4404/// last type comparison in a ?-exp of ObjC pointer types before a 4405/// warning is issued. So, its invokation is extremely rare. 4406QualType ASTContext::areCommonBaseCompatible( 4407 const ObjCObjectPointerType *Lptr, 4408 const ObjCObjectPointerType *Rptr) { 4409 const ObjCObjectType *LHS = Lptr->getObjectType(); 4410 const ObjCObjectType *RHS = Rptr->getObjectType(); 4411 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 4412 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 4413 if (!LDecl || !RDecl) 4414 return QualType(); 4415 4416 while ((LDecl = LDecl->getSuperClass())) { 4417 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 4418 if (canAssignObjCInterfaces(LHS, RHS)) { 4419 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols; 4420 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 4421 4422 QualType Result = QualType(LHS, 0); 4423 if (!Protocols.empty()) 4424 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 4425 Result = getObjCObjectPointerType(Result); 4426 return Result; 4427 } 4428 } 4429 4430 return QualType(); 4431} 4432 4433bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 4434 const ObjCObjectType *RHS) { 4435 assert(LHS->getInterface() && "LHS is not an interface type"); 4436 assert(RHS->getInterface() && "RHS is not an interface type"); 4437 4438 // Verify that the base decls are compatible: the RHS must be a subclass of 4439 // the LHS. 4440 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 4441 return false; 4442 4443 // RHS must have a superset of the protocols in the LHS. If the LHS is not 4444 // protocol qualified at all, then we are good. 4445 if (LHS->getNumProtocols() == 0) 4446 return true; 4447 4448 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 4449 // isn't a superset. 4450 if (RHS->getNumProtocols() == 0) 4451 return true; // FIXME: should return false! 4452 4453 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 4454 LHSPE = LHS->qual_end(); 4455 LHSPI != LHSPE; LHSPI++) { 4456 bool RHSImplementsProtocol = false; 4457 4458 // If the RHS doesn't implement the protocol on the left, the types 4459 // are incompatible. 4460 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 4461 RHSPE = RHS->qual_end(); 4462 RHSPI != RHSPE; RHSPI++) { 4463 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 4464 RHSImplementsProtocol = true; 4465 break; 4466 } 4467 } 4468 // FIXME: For better diagnostics, consider passing back the protocol name. 4469 if (!RHSImplementsProtocol) 4470 return false; 4471 } 4472 // The RHS implements all protocols listed on the LHS. 4473 return true; 4474} 4475 4476bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 4477 // get the "pointed to" types 4478 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 4479 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 4480 4481 if (!LHSOPT || !RHSOPT) 4482 return false; 4483 4484 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 4485 canAssignObjCInterfaces(RHSOPT, LHSOPT); 4486} 4487 4488/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 4489/// both shall have the identically qualified version of a compatible type. 4490/// C99 6.2.7p1: Two types have compatible types if their types are the 4491/// same. See 6.7.[2,3,5] for additional rules. 4492bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 4493 if (getLangOptions().CPlusPlus) 4494 return hasSameType(LHS, RHS); 4495 4496 return !mergeTypes(LHS, RHS).isNull(); 4497} 4498 4499bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 4500 return !mergeTypes(LHS, RHS, true).isNull(); 4501} 4502 4503QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 4504 bool OfBlockPointer) { 4505 const FunctionType *lbase = lhs->getAs<FunctionType>(); 4506 const FunctionType *rbase = rhs->getAs<FunctionType>(); 4507 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 4508 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 4509 bool allLTypes = true; 4510 bool allRTypes = true; 4511 4512 // Check return type 4513 QualType retType; 4514 if (OfBlockPointer) 4515 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true); 4516 else 4517 retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 4518 if (retType.isNull()) return QualType(); 4519 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 4520 allLTypes = false; 4521 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 4522 allRTypes = false; 4523 // FIXME: double check this 4524 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 4525 // rbase->getRegParmAttr() != 0 && 4526 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 4527 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 4528 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 4529 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() : 4530 lbaseInfo.getRegParm(); 4531 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 4532 if (NoReturn != lbaseInfo.getNoReturn() || 4533 RegParm != lbaseInfo.getRegParm()) 4534 allLTypes = false; 4535 if (NoReturn != rbaseInfo.getNoReturn() || 4536 RegParm != rbaseInfo.getRegParm()) 4537 allRTypes = false; 4538 CallingConv lcc = lbaseInfo.getCC(); 4539 CallingConv rcc = rbaseInfo.getCC(); 4540 // Compatible functions must have compatible calling conventions 4541 if (!isSameCallConv(lcc, rcc)) 4542 return QualType(); 4543 4544 if (lproto && rproto) { // two C99 style function prototypes 4545 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 4546 "C++ shouldn't be here"); 4547 unsigned lproto_nargs = lproto->getNumArgs(); 4548 unsigned rproto_nargs = rproto->getNumArgs(); 4549 4550 // Compatible functions must have the same number of arguments 4551 if (lproto_nargs != rproto_nargs) 4552 return QualType(); 4553 4554 // Variadic and non-variadic functions aren't compatible 4555 if (lproto->isVariadic() != rproto->isVariadic()) 4556 return QualType(); 4557 4558 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 4559 return QualType(); 4560 4561 // Check argument compatibility 4562 llvm::SmallVector<QualType, 10> types; 4563 for (unsigned i = 0; i < lproto_nargs; i++) { 4564 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 4565 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 4566 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer); 4567 if (argtype.isNull()) return QualType(); 4568 types.push_back(argtype); 4569 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 4570 allLTypes = false; 4571 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 4572 allRTypes = false; 4573 } 4574 if (allLTypes) return lhs; 4575 if (allRTypes) return rhs; 4576 return getFunctionType(retType, types.begin(), types.size(), 4577 lproto->isVariadic(), lproto->getTypeQuals(), 4578 false, false, 0, 0, 4579 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4580 } 4581 4582 if (lproto) allRTypes = false; 4583 if (rproto) allLTypes = false; 4584 4585 const FunctionProtoType *proto = lproto ? lproto : rproto; 4586 if (proto) { 4587 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 4588 if (proto->isVariadic()) return QualType(); 4589 // Check that the types are compatible with the types that 4590 // would result from default argument promotions (C99 6.7.5.3p15). 4591 // The only types actually affected are promotable integer 4592 // types and floats, which would be passed as a different 4593 // type depending on whether the prototype is visible. 4594 unsigned proto_nargs = proto->getNumArgs(); 4595 for (unsigned i = 0; i < proto_nargs; ++i) { 4596 QualType argTy = proto->getArgType(i); 4597 4598 // Look at the promotion type of enum types, since that is the type used 4599 // to pass enum values. 4600 if (const EnumType *Enum = argTy->getAs<EnumType>()) 4601 argTy = Enum->getDecl()->getPromotionType(); 4602 4603 if (argTy->isPromotableIntegerType() || 4604 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 4605 return QualType(); 4606 } 4607 4608 if (allLTypes) return lhs; 4609 if (allRTypes) return rhs; 4610 return getFunctionType(retType, proto->arg_type_begin(), 4611 proto->getNumArgs(), proto->isVariadic(), 4612 proto->getTypeQuals(), 4613 false, false, 0, 0, 4614 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4615 } 4616 4617 if (allLTypes) return lhs; 4618 if (allRTypes) return rhs; 4619 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc); 4620 return getFunctionNoProtoType(retType, Info); 4621} 4622 4623QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 4624 bool OfBlockPointer) { 4625 // C++ [expr]: If an expression initially has the type "reference to T", the 4626 // type is adjusted to "T" prior to any further analysis, the expression 4627 // designates the object or function denoted by the reference, and the 4628 // expression is an lvalue unless the reference is an rvalue reference and 4629 // the expression is a function call (possibly inside parentheses). 4630 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 4631 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 4632 4633 QualType LHSCan = getCanonicalType(LHS), 4634 RHSCan = getCanonicalType(RHS); 4635 4636 // If two types are identical, they are compatible. 4637 if (LHSCan == RHSCan) 4638 return LHS; 4639 4640 // If the qualifiers are different, the types aren't compatible... mostly. 4641 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 4642 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 4643 if (LQuals != RQuals) { 4644 // If any of these qualifiers are different, we have a type 4645 // mismatch. 4646 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 4647 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 4648 return QualType(); 4649 4650 // Exactly one GC qualifier difference is allowed: __strong is 4651 // okay if the other type has no GC qualifier but is an Objective 4652 // C object pointer (i.e. implicitly strong by default). We fix 4653 // this by pretending that the unqualified type was actually 4654 // qualified __strong. 4655 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 4656 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 4657 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 4658 4659 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 4660 return QualType(); 4661 4662 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 4663 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 4664 } 4665 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 4666 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 4667 } 4668 return QualType(); 4669 } 4670 4671 // Okay, qualifiers are equal. 4672 4673 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 4674 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 4675 4676 // We want to consider the two function types to be the same for these 4677 // comparisons, just force one to the other. 4678 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 4679 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 4680 4681 // Same as above for arrays 4682 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 4683 LHSClass = Type::ConstantArray; 4684 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 4685 RHSClass = Type::ConstantArray; 4686 4687 // ObjCInterfaces are just specialized ObjCObjects. 4688 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 4689 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 4690 4691 // Canonicalize ExtVector -> Vector. 4692 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 4693 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 4694 4695 // If the canonical type classes don't match. 4696 if (LHSClass != RHSClass) { 4697 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 4698 // a signed integer type, or an unsigned integer type. 4699 // Compatibility is based on the underlying type, not the promotion 4700 // type. 4701 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 4702 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 4703 return RHS; 4704 } 4705 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 4706 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 4707 return LHS; 4708 } 4709 4710 return QualType(); 4711 } 4712 4713 // The canonical type classes match. 4714 switch (LHSClass) { 4715#define TYPE(Class, Base) 4716#define ABSTRACT_TYPE(Class, Base) 4717#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 4718#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 4719#define DEPENDENT_TYPE(Class, Base) case Type::Class: 4720#include "clang/AST/TypeNodes.def" 4721 assert(false && "Non-canonical and dependent types shouldn't get here"); 4722 return QualType(); 4723 4724 case Type::LValueReference: 4725 case Type::RValueReference: 4726 case Type::MemberPointer: 4727 assert(false && "C++ should never be in mergeTypes"); 4728 return QualType(); 4729 4730 case Type::ObjCInterface: 4731 case Type::IncompleteArray: 4732 case Type::VariableArray: 4733 case Type::FunctionProto: 4734 case Type::ExtVector: 4735 assert(false && "Types are eliminated above"); 4736 return QualType(); 4737 4738 case Type::Pointer: 4739 { 4740 // Merge two pointer types, while trying to preserve typedef info 4741 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 4742 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 4743 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 4744 if (ResultType.isNull()) return QualType(); 4745 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 4746 return LHS; 4747 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 4748 return RHS; 4749 return getPointerType(ResultType); 4750 } 4751 case Type::BlockPointer: 4752 { 4753 // Merge two block pointer types, while trying to preserve typedef info 4754 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 4755 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 4756 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer); 4757 if (ResultType.isNull()) return QualType(); 4758 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 4759 return LHS; 4760 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 4761 return RHS; 4762 return getBlockPointerType(ResultType); 4763 } 4764 case Type::ConstantArray: 4765 { 4766 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 4767 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 4768 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 4769 return QualType(); 4770 4771 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 4772 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 4773 QualType ResultType = mergeTypes(LHSElem, RHSElem); 4774 if (ResultType.isNull()) return QualType(); 4775 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 4776 return LHS; 4777 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 4778 return RHS; 4779 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 4780 ArrayType::ArraySizeModifier(), 0); 4781 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 4782 ArrayType::ArraySizeModifier(), 0); 4783 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 4784 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 4785 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 4786 return LHS; 4787 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 4788 return RHS; 4789 if (LVAT) { 4790 // FIXME: This isn't correct! But tricky to implement because 4791 // the array's size has to be the size of LHS, but the type 4792 // has to be different. 4793 return LHS; 4794 } 4795 if (RVAT) { 4796 // FIXME: This isn't correct! But tricky to implement because 4797 // the array's size has to be the size of RHS, but the type 4798 // has to be different. 4799 return RHS; 4800 } 4801 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 4802 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 4803 return getIncompleteArrayType(ResultType, 4804 ArrayType::ArraySizeModifier(), 0); 4805 } 4806 case Type::FunctionNoProto: 4807 return mergeFunctionTypes(LHS, RHS, OfBlockPointer); 4808 case Type::Record: 4809 case Type::Enum: 4810 return QualType(); 4811 case Type::Builtin: 4812 // Only exactly equal builtin types are compatible, which is tested above. 4813 return QualType(); 4814 case Type::Complex: 4815 // Distinct complex types are incompatible. 4816 return QualType(); 4817 case Type::Vector: 4818 // FIXME: The merged type should be an ExtVector! 4819 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 4820 RHSCan->getAs<VectorType>())) 4821 return LHS; 4822 return QualType(); 4823 case Type::ObjCObject: { 4824 // Check if the types are assignment compatible. 4825 // FIXME: This should be type compatibility, e.g. whether 4826 // "LHS x; RHS x;" at global scope is legal. 4827 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 4828 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 4829 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 4830 return LHS; 4831 4832 return QualType(); 4833 } 4834 case Type::ObjCObjectPointer: { 4835 if (OfBlockPointer) { 4836 if (canAssignObjCInterfacesInBlockPointer( 4837 LHS->getAs<ObjCObjectPointerType>(), 4838 RHS->getAs<ObjCObjectPointerType>())) 4839 return LHS; 4840 return QualType(); 4841 } 4842 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 4843 RHS->getAs<ObjCObjectPointerType>())) 4844 return LHS; 4845 4846 return QualType(); 4847 } 4848 } 4849 4850 return QualType(); 4851} 4852 4853/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 4854/// 'RHS' attributes and returns the merged version; including for function 4855/// return types. 4856QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 4857 QualType LHSCan = getCanonicalType(LHS), 4858 RHSCan = getCanonicalType(RHS); 4859 // If two types are identical, they are compatible. 4860 if (LHSCan == RHSCan) 4861 return LHS; 4862 if (RHSCan->isFunctionType()) { 4863 if (!LHSCan->isFunctionType()) 4864 return QualType(); 4865 QualType OldReturnType = 4866 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 4867 QualType NewReturnType = 4868 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 4869 QualType ResReturnType = 4870 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 4871 if (ResReturnType.isNull()) 4872 return QualType(); 4873 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 4874 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 4875 // In either case, use OldReturnType to build the new function type. 4876 const FunctionType *F = LHS->getAs<FunctionType>(); 4877 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 4878 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS); 4879 QualType ResultType 4880 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 4881 FPT->getNumArgs(), FPT->isVariadic(), 4882 FPT->getTypeQuals(), 4883 FPT->hasExceptionSpec(), 4884 FPT->hasAnyExceptionSpec(), 4885 FPT->getNumExceptions(), 4886 FPT->exception_begin(), 4887 Info); 4888 return ResultType; 4889 } 4890 } 4891 return QualType(); 4892 } 4893 4894 // If the qualifiers are different, the types can still be merged. 4895 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 4896 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 4897 if (LQuals != RQuals) { 4898 // If any of these qualifiers are different, we have a type mismatch. 4899 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 4900 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 4901 return QualType(); 4902 4903 // Exactly one GC qualifier difference is allowed: __strong is 4904 // okay if the other type has no GC qualifier but is an Objective 4905 // C object pointer (i.e. implicitly strong by default). We fix 4906 // this by pretending that the unqualified type was actually 4907 // qualified __strong. 4908 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 4909 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 4910 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 4911 4912 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 4913 return QualType(); 4914 4915 if (GC_L == Qualifiers::Strong) 4916 return LHS; 4917 if (GC_R == Qualifiers::Strong) 4918 return RHS; 4919 return QualType(); 4920 } 4921 4922 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 4923 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 4924 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 4925 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 4926 if (ResQT == LHSBaseQT) 4927 return LHS; 4928 if (ResQT == RHSBaseQT) 4929 return RHS; 4930 } 4931 return QualType(); 4932} 4933 4934//===----------------------------------------------------------------------===// 4935// Integer Predicates 4936//===----------------------------------------------------------------------===// 4937 4938unsigned ASTContext::getIntWidth(QualType T) { 4939 if (T->isBooleanType()) 4940 return 1; 4941 if (EnumType *ET = dyn_cast<EnumType>(T)) 4942 T = ET->getDecl()->getIntegerType(); 4943 // For builtin types, just use the standard type sizing method 4944 return (unsigned)getTypeSize(T); 4945} 4946 4947QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 4948 assert(T->isSignedIntegerType() && "Unexpected type"); 4949 4950 // Turn <4 x signed int> -> <4 x unsigned int> 4951 if (const VectorType *VTy = T->getAs<VectorType>()) 4952 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 4953 VTy->getNumElements(), VTy->getAltiVecSpecific()); 4954 4955 // For enums, we return the unsigned version of the base type. 4956 if (const EnumType *ETy = T->getAs<EnumType>()) 4957 T = ETy->getDecl()->getIntegerType(); 4958 4959 const BuiltinType *BTy = T->getAs<BuiltinType>(); 4960 assert(BTy && "Unexpected signed integer type"); 4961 switch (BTy->getKind()) { 4962 case BuiltinType::Char_S: 4963 case BuiltinType::SChar: 4964 return UnsignedCharTy; 4965 case BuiltinType::Short: 4966 return UnsignedShortTy; 4967 case BuiltinType::Int: 4968 return UnsignedIntTy; 4969 case BuiltinType::Long: 4970 return UnsignedLongTy; 4971 case BuiltinType::LongLong: 4972 return UnsignedLongLongTy; 4973 case BuiltinType::Int128: 4974 return UnsignedInt128Ty; 4975 default: 4976 assert(0 && "Unexpected signed integer type"); 4977 return QualType(); 4978 } 4979} 4980 4981ExternalASTSource::~ExternalASTSource() { } 4982 4983void ExternalASTSource::PrintStats() { } 4984 4985 4986//===----------------------------------------------------------------------===// 4987// Builtin Type Computation 4988//===----------------------------------------------------------------------===// 4989 4990/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 4991/// pointer over the consumed characters. This returns the resultant type. 4992static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, 4993 ASTContext::GetBuiltinTypeError &Error, 4994 bool AllowTypeModifiers = true) { 4995 // Modifiers. 4996 int HowLong = 0; 4997 bool Signed = false, Unsigned = false; 4998 4999 // Read the modifiers first. 5000 bool Done = false; 5001 while (!Done) { 5002 switch (*Str++) { 5003 default: Done = true; --Str; break; 5004 case 'S': 5005 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 5006 assert(!Signed && "Can't use 'S' modifier multiple times!"); 5007 Signed = true; 5008 break; 5009 case 'U': 5010 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 5011 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 5012 Unsigned = true; 5013 break; 5014 case 'L': 5015 assert(HowLong <= 2 && "Can't have LLLL modifier"); 5016 ++HowLong; 5017 break; 5018 } 5019 } 5020 5021 QualType Type; 5022 5023 // Read the base type. 5024 switch (*Str++) { 5025 default: assert(0 && "Unknown builtin type letter!"); 5026 case 'v': 5027 assert(HowLong == 0 && !Signed && !Unsigned && 5028 "Bad modifiers used with 'v'!"); 5029 Type = Context.VoidTy; 5030 break; 5031 case 'f': 5032 assert(HowLong == 0 && !Signed && !Unsigned && 5033 "Bad modifiers used with 'f'!"); 5034 Type = Context.FloatTy; 5035 break; 5036 case 'd': 5037 assert(HowLong < 2 && !Signed && !Unsigned && 5038 "Bad modifiers used with 'd'!"); 5039 if (HowLong) 5040 Type = Context.LongDoubleTy; 5041 else 5042 Type = Context.DoubleTy; 5043 break; 5044 case 's': 5045 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 5046 if (Unsigned) 5047 Type = Context.UnsignedShortTy; 5048 else 5049 Type = Context.ShortTy; 5050 break; 5051 case 'i': 5052 if (HowLong == 3) 5053 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 5054 else if (HowLong == 2) 5055 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 5056 else if (HowLong == 1) 5057 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 5058 else 5059 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 5060 break; 5061 case 'c': 5062 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 5063 if (Signed) 5064 Type = Context.SignedCharTy; 5065 else if (Unsigned) 5066 Type = Context.UnsignedCharTy; 5067 else 5068 Type = Context.CharTy; 5069 break; 5070 case 'b': // boolean 5071 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 5072 Type = Context.BoolTy; 5073 break; 5074 case 'z': // size_t. 5075 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 5076 Type = Context.getSizeType(); 5077 break; 5078 case 'F': 5079 Type = Context.getCFConstantStringType(); 5080 break; 5081 case 'a': 5082 Type = Context.getBuiltinVaListType(); 5083 assert(!Type.isNull() && "builtin va list type not initialized!"); 5084 break; 5085 case 'A': 5086 // This is a "reference" to a va_list; however, what exactly 5087 // this means depends on how va_list is defined. There are two 5088 // different kinds of va_list: ones passed by value, and ones 5089 // passed by reference. An example of a by-value va_list is 5090 // x86, where va_list is a char*. An example of by-ref va_list 5091 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 5092 // we want this argument to be a char*&; for x86-64, we want 5093 // it to be a __va_list_tag*. 5094 Type = Context.getBuiltinVaListType(); 5095 assert(!Type.isNull() && "builtin va list type not initialized!"); 5096 if (Type->isArrayType()) { 5097 Type = Context.getArrayDecayedType(Type); 5098 } else { 5099 Type = Context.getLValueReferenceType(Type); 5100 } 5101 break; 5102 case 'V': { 5103 char *End; 5104 unsigned NumElements = strtoul(Str, &End, 10); 5105 assert(End != Str && "Missing vector size"); 5106 5107 Str = End; 5108 5109 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 5110 // FIXME: Don't know what to do about AltiVec. 5111 Type = Context.getVectorType(ElementType, NumElements, 5112 VectorType::NotAltiVec); 5113 break; 5114 } 5115 case 'X': { 5116 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 5117 Type = Context.getComplexType(ElementType); 5118 break; 5119 } 5120 case 'P': 5121 Type = Context.getFILEType(); 5122 if (Type.isNull()) { 5123 Error = ASTContext::GE_Missing_stdio; 5124 return QualType(); 5125 } 5126 break; 5127 case 'J': 5128 if (Signed) 5129 Type = Context.getsigjmp_bufType(); 5130 else 5131 Type = Context.getjmp_bufType(); 5132 5133 if (Type.isNull()) { 5134 Error = ASTContext::GE_Missing_setjmp; 5135 return QualType(); 5136 } 5137 break; 5138 } 5139 5140 if (!AllowTypeModifiers) 5141 return Type; 5142 5143 Done = false; 5144 while (!Done) { 5145 switch (char c = *Str++) { 5146 default: Done = true; --Str; break; 5147 case '*': 5148 case '&': 5149 { 5150 // Both pointers and references can have their pointee types 5151 // qualified with an address space. 5152 char *End; 5153 unsigned AddrSpace = strtoul(Str, &End, 10); 5154 if (End != Str && AddrSpace != 0) { 5155 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 5156 Str = End; 5157 } 5158 } 5159 if (c == '*') 5160 Type = Context.getPointerType(Type); 5161 else 5162 Type = Context.getLValueReferenceType(Type); 5163 break; 5164 // FIXME: There's no way to have a built-in with an rvalue ref arg. 5165 case 'C': 5166 Type = Type.withConst(); 5167 break; 5168 case 'D': 5169 Type = Context.getVolatileType(Type); 5170 break; 5171 } 5172 } 5173 5174 return Type; 5175} 5176 5177/// GetBuiltinType - Return the type for the specified builtin. 5178QualType ASTContext::GetBuiltinType(unsigned id, 5179 GetBuiltinTypeError &Error) { 5180 const char *TypeStr = BuiltinInfo.GetTypeString(id); 5181 5182 llvm::SmallVector<QualType, 8> ArgTypes; 5183 5184 Error = GE_None; 5185 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error); 5186 if (Error != GE_None) 5187 return QualType(); 5188 while (TypeStr[0] && TypeStr[0] != '.') { 5189 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error); 5190 if (Error != GE_None) 5191 return QualType(); 5192 5193 // Do array -> pointer decay. The builtin should use the decayed type. 5194 if (Ty->isArrayType()) 5195 Ty = getArrayDecayedType(Ty); 5196 5197 ArgTypes.push_back(Ty); 5198 } 5199 5200 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 5201 "'.' should only occur at end of builtin type list!"); 5202 5203 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". 5204 if (ArgTypes.size() == 0 && TypeStr[0] == '.') 5205 return getFunctionNoProtoType(ResType); 5206 5207 // FIXME: Should we create noreturn types? 5208 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), 5209 TypeStr[0] == '.', 0, false, false, 0, 0, 5210 FunctionType::ExtInfo()); 5211} 5212 5213QualType 5214ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 5215 // Perform the usual unary conversions. We do this early so that 5216 // integral promotions to "int" can allow us to exit early, in the 5217 // lhs == rhs check. Also, for conversion purposes, we ignore any 5218 // qualifiers. For example, "const float" and "float" are 5219 // equivalent. 5220 if (lhs->isPromotableIntegerType()) 5221 lhs = getPromotedIntegerType(lhs); 5222 else 5223 lhs = lhs.getUnqualifiedType(); 5224 if (rhs->isPromotableIntegerType()) 5225 rhs = getPromotedIntegerType(rhs); 5226 else 5227 rhs = rhs.getUnqualifiedType(); 5228 5229 // If both types are identical, no conversion is needed. 5230 if (lhs == rhs) 5231 return lhs; 5232 5233 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 5234 // The caller can deal with this (e.g. pointer + int). 5235 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 5236 return lhs; 5237 5238 // At this point, we have two different arithmetic types. 5239 5240 // Handle complex types first (C99 6.3.1.8p1). 5241 if (lhs->isComplexType() || rhs->isComplexType()) { 5242 // if we have an integer operand, the result is the complex type. 5243 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 5244 // convert the rhs to the lhs complex type. 5245 return lhs; 5246 } 5247 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 5248 // convert the lhs to the rhs complex type. 5249 return rhs; 5250 } 5251 // This handles complex/complex, complex/float, or float/complex. 5252 // When both operands are complex, the shorter operand is converted to the 5253 // type of the longer, and that is the type of the result. This corresponds 5254 // to what is done when combining two real floating-point operands. 5255 // The fun begins when size promotion occur across type domains. 5256 // From H&S 6.3.4: When one operand is complex and the other is a real 5257 // floating-point type, the less precise type is converted, within it's 5258 // real or complex domain, to the precision of the other type. For example, 5259 // when combining a "long double" with a "double _Complex", the 5260 // "double _Complex" is promoted to "long double _Complex". 5261 int result = getFloatingTypeOrder(lhs, rhs); 5262 5263 if (result > 0) { // The left side is bigger, convert rhs. 5264 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs); 5265 } else if (result < 0) { // The right side is bigger, convert lhs. 5266 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs); 5267 } 5268 // At this point, lhs and rhs have the same rank/size. Now, make sure the 5269 // domains match. This is a requirement for our implementation, C99 5270 // does not require this promotion. 5271 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 5272 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 5273 return rhs; 5274 } else { // handle "_Complex double, double". 5275 return lhs; 5276 } 5277 } 5278 return lhs; // The domain/size match exactly. 5279 } 5280 // Now handle "real" floating types (i.e. float, double, long double). 5281 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 5282 // if we have an integer operand, the result is the real floating type. 5283 if (rhs->isIntegerType()) { 5284 // convert rhs to the lhs floating point type. 5285 return lhs; 5286 } 5287 if (rhs->isComplexIntegerType()) { 5288 // convert rhs to the complex floating point type. 5289 return getComplexType(lhs); 5290 } 5291 if (lhs->isIntegerType()) { 5292 // convert lhs to the rhs floating point type. 5293 return rhs; 5294 } 5295 if (lhs->isComplexIntegerType()) { 5296 // convert lhs to the complex floating point type. 5297 return getComplexType(rhs); 5298 } 5299 // We have two real floating types, float/complex combos were handled above. 5300 // Convert the smaller operand to the bigger result. 5301 int result = getFloatingTypeOrder(lhs, rhs); 5302 if (result > 0) // convert the rhs 5303 return lhs; 5304 assert(result < 0 && "illegal float comparison"); 5305 return rhs; // convert the lhs 5306 } 5307 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 5308 // Handle GCC complex int extension. 5309 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 5310 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 5311 5312 if (lhsComplexInt && rhsComplexInt) { 5313 if (getIntegerTypeOrder(lhsComplexInt->getElementType(), 5314 rhsComplexInt->getElementType()) >= 0) 5315 return lhs; // convert the rhs 5316 return rhs; 5317 } else if (lhsComplexInt && rhs->isIntegerType()) { 5318 // convert the rhs to the lhs complex type. 5319 return lhs; 5320 } else if (rhsComplexInt && lhs->isIntegerType()) { 5321 // convert the lhs to the rhs complex type. 5322 return rhs; 5323 } 5324 } 5325 // Finally, we have two differing integer types. 5326 // The rules for this case are in C99 6.3.1.8 5327 int compare = getIntegerTypeOrder(lhs, rhs); 5328 bool lhsSigned = lhs->isSignedIntegerType(), 5329 rhsSigned = rhs->isSignedIntegerType(); 5330 QualType destType; 5331 if (lhsSigned == rhsSigned) { 5332 // Same signedness; use the higher-ranked type 5333 destType = compare >= 0 ? lhs : rhs; 5334 } else if (compare != (lhsSigned ? 1 : -1)) { 5335 // The unsigned type has greater than or equal rank to the 5336 // signed type, so use the unsigned type 5337 destType = lhsSigned ? rhs : lhs; 5338 } else if (getIntWidth(lhs) != getIntWidth(rhs)) { 5339 // The two types are different widths; if we are here, that 5340 // means the signed type is larger than the unsigned type, so 5341 // use the signed type. 5342 destType = lhsSigned ? lhs : rhs; 5343 } else { 5344 // The signed type is higher-ranked than the unsigned type, 5345 // but isn't actually any bigger (like unsigned int and long 5346 // on most 32-bit systems). Use the unsigned type corresponding 5347 // to the signed type. 5348 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 5349 } 5350 return destType; 5351} 5352