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