ASTContext.cpp revision 687abffee40d0459fe5eecf3e5ee6e60be69d93c
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/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExternalASTSource.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Basic/TargetInfo.h" 23#include "llvm/ADT/StringExtras.h" 24#include "llvm/Support/MathExtras.h" 25#include "llvm/Support/MemoryBuffer.h" 26using namespace clang; 27 28enum FloatingRank { 29 FloatRank, DoubleRank, LongDoubleRank 30}; 31 32ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 33 TargetInfo &t, 34 IdentifierTable &idents, SelectorTable &sels, 35 bool FreeMem, unsigned size_reserve, 36 bool InitializeBuiltins) : 37 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), 38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts), 39 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels), 40 ExternalSource(0) { 41 if (size_reserve > 0) Types.reserve(size_reserve); 42 InitBuiltinTypes(); 43 TUDecl = TranslationUnitDecl::Create(*this); 44 BuiltinInfo.InitializeTargetBuiltins(Target); 45 if (InitializeBuiltins) 46 this->InitializeBuiltins(idents); 47 PrintingPolicy.CPlusPlus = LangOpts.CPlusPlus; 48} 49 50ASTContext::~ASTContext() { 51 // Deallocate all the types. 52 while (!Types.empty()) { 53 Types.back()->Destroy(*this); 54 Types.pop_back(); 55 } 56 57 { 58 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 59 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); 60 while (I != E) { 61 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 62 delete R; 63 } 64 } 65 66 { 67 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator 68 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); 69 while (I != E) { 70 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second); 71 delete R; 72 } 73 } 74 75 // Destroy nested-name-specifiers. 76 for (llvm::FoldingSet<NestedNameSpecifier>::iterator 77 NNS = NestedNameSpecifiers.begin(), 78 NNSEnd = NestedNameSpecifiers.end(); 79 NNS != NNSEnd; 80 /* Increment in loop */) 81 (*NNS++).Destroy(*this); 82 83 if (GlobalNestedNameSpecifier) 84 GlobalNestedNameSpecifier->Destroy(*this); 85 86 TUDecl->Destroy(*this); 87} 88 89void ASTContext::InitializeBuiltins(IdentifierTable &idents) { 90 BuiltinInfo.InitializeBuiltins(idents, LangOpts.NoBuiltin); 91} 92 93void 94ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 95 ExternalSource.reset(Source.take()); 96} 97 98void ASTContext::PrintStats() const { 99 fprintf(stderr, "*** AST Context Stats:\n"); 100 fprintf(stderr, " %d types total.\n", (int)Types.size()); 101 102 unsigned counts[] = { 103#define TYPE(Name, Parent) 0, 104#define ABSTRACT_TYPE(Name, Parent) 105#include "clang/AST/TypeNodes.def" 106 0 // Extra 107 }; 108 109 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 110 Type *T = Types[i]; 111 counts[(unsigned)T->getTypeClass()]++; 112 } 113 114 unsigned Idx = 0; 115 unsigned TotalBytes = 0; 116#define TYPE(Name, Parent) \ 117 if (counts[Idx]) \ 118 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 119 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 120 ++Idx; 121#define ABSTRACT_TYPE(Name, Parent) 122#include "clang/AST/TypeNodes.def" 123 124 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 125 126 if (ExternalSource.get()) { 127 fprintf(stderr, "\n"); 128 ExternalSource->PrintStats(); 129 } 130} 131 132 133void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { 134 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr()); 135} 136 137void ASTContext::InitBuiltinTypes() { 138 assert(VoidTy.isNull() && "Context reinitialized?"); 139 140 // C99 6.2.5p19. 141 InitBuiltinType(VoidTy, BuiltinType::Void); 142 143 // C99 6.2.5p2. 144 InitBuiltinType(BoolTy, BuiltinType::Bool); 145 // C99 6.2.5p3. 146 if (LangOpts.CharIsSigned) 147 InitBuiltinType(CharTy, BuiltinType::Char_S); 148 else 149 InitBuiltinType(CharTy, BuiltinType::Char_U); 150 // C99 6.2.5p4. 151 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 152 InitBuiltinType(ShortTy, BuiltinType::Short); 153 InitBuiltinType(IntTy, BuiltinType::Int); 154 InitBuiltinType(LongTy, BuiltinType::Long); 155 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 156 157 // C99 6.2.5p6. 158 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 159 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 160 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 161 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 162 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 163 164 // C99 6.2.5p10. 165 InitBuiltinType(FloatTy, BuiltinType::Float); 166 InitBuiltinType(DoubleTy, BuiltinType::Double); 167 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 168 169 // GNU extension, 128-bit integers. 170 InitBuiltinType(Int128Ty, BuiltinType::Int128); 171 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 172 173 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 174 InitBuiltinType(WCharTy, BuiltinType::WChar); 175 else // C99 176 WCharTy = getFromTargetType(Target.getWCharType()); 177 178 // Placeholder type for functions. 179 InitBuiltinType(OverloadTy, BuiltinType::Overload); 180 181 // Placeholder type for type-dependent expressions whose type is 182 // completely unknown. No code should ever check a type against 183 // DependentTy and users should never see it; however, it is here to 184 // help diagnose failures to properly check for type-dependent 185 // expressions. 186 InitBuiltinType(DependentTy, BuiltinType::Dependent); 187 188 // C99 6.2.5p11. 189 FloatComplexTy = getComplexType(FloatTy); 190 DoubleComplexTy = getComplexType(DoubleTy); 191 LongDoubleComplexTy = getComplexType(LongDoubleTy); 192 193 BuiltinVaListType = QualType(); 194 ObjCIdType = QualType(); 195 IdStructType = 0; 196 ObjCClassType = QualType(); 197 ClassStructType = 0; 198 199 ObjCConstantStringType = QualType(); 200 201 // void * type 202 VoidPtrTy = getPointerType(VoidTy); 203 204 // nullptr type (C++0x 2.14.7) 205 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 206} 207 208//===----------------------------------------------------------------------===// 209// Type Sizing and Analysis 210//===----------------------------------------------------------------------===// 211 212/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 213/// scalar floating point type. 214const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 215 const BuiltinType *BT = T->getAsBuiltinType(); 216 assert(BT && "Not a floating point type!"); 217 switch (BT->getKind()) { 218 default: assert(0 && "Not a floating point type!"); 219 case BuiltinType::Float: return Target.getFloatFormat(); 220 case BuiltinType::Double: return Target.getDoubleFormat(); 221 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 222 } 223} 224 225/// getDeclAlign - Return a conservative estimate of the alignment of the 226/// specified decl. Note that bitfields do not have a valid alignment, so 227/// this method will assert on them. 228unsigned ASTContext::getDeclAlignInBytes(const Decl *D) { 229 unsigned Align = Target.getCharWidth(); 230 231 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) 232 Align = std::max(Align, AA->getAlignment()); 233 234 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 235 QualType T = VD->getType(); 236 if (const ReferenceType* RT = T->getAsReferenceType()) { 237 unsigned AS = RT->getPointeeType().getAddressSpace(); 238 Align = Target.getPointerAlign(AS); 239 } else if (!T->isIncompleteType() && !T->isFunctionType()) { 240 // Incomplete or function types default to 1. 241 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 242 T = cast<ArrayType>(T)->getElementType(); 243 244 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 245 } 246 } 247 248 return Align / Target.getCharWidth(); 249} 250 251/// getTypeSize - Return the size of the specified type, in bits. This method 252/// does not work on incomplete types. 253std::pair<uint64_t, unsigned> 254ASTContext::getTypeInfo(const Type *T) { 255 uint64_t Width=0; 256 unsigned Align=8; 257 switch (T->getTypeClass()) { 258#define TYPE(Class, Base) 259#define ABSTRACT_TYPE(Class, Base) 260#define NON_CANONICAL_TYPE(Class, Base) 261#define DEPENDENT_TYPE(Class, Base) case Type::Class: 262#include "clang/AST/TypeNodes.def" 263 assert(false && "Should not see dependent types"); 264 break; 265 266 case Type::FunctionNoProto: 267 case Type::FunctionProto: 268 // GCC extension: alignof(function) = 32 bits 269 Width = 0; 270 Align = 32; 271 break; 272 273 case Type::IncompleteArray: 274 case Type::VariableArray: 275 Width = 0; 276 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 277 break; 278 279 case Type::ConstantArray: { 280 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 281 282 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 283 Width = EltInfo.first*CAT->getSize().getZExtValue(); 284 Align = EltInfo.second; 285 break; 286 } 287 case Type::ExtVector: 288 case Type::Vector: { 289 std::pair<uint64_t, unsigned> EltInfo = 290 getTypeInfo(cast<VectorType>(T)->getElementType()); 291 Width = EltInfo.first*cast<VectorType>(T)->getNumElements(); 292 Align = Width; 293 // If the alignment is not a power of 2, round up to the next power of 2. 294 // This happens for non-power-of-2 length vectors. 295 // FIXME: this should probably be a target property. 296 Align = 1 << llvm::Log2_32_Ceil(Align); 297 break; 298 } 299 300 case Type::Builtin: 301 switch (cast<BuiltinType>(T)->getKind()) { 302 default: assert(0 && "Unknown builtin type!"); 303 case BuiltinType::Void: 304 // GCC extension: alignof(void) = 8 bits. 305 Width = 0; 306 Align = 8; 307 break; 308 309 case BuiltinType::Bool: 310 Width = Target.getBoolWidth(); 311 Align = Target.getBoolAlign(); 312 break; 313 case BuiltinType::Char_S: 314 case BuiltinType::Char_U: 315 case BuiltinType::UChar: 316 case BuiltinType::SChar: 317 Width = Target.getCharWidth(); 318 Align = Target.getCharAlign(); 319 break; 320 case BuiltinType::WChar: 321 Width = Target.getWCharWidth(); 322 Align = Target.getWCharAlign(); 323 break; 324 case BuiltinType::UShort: 325 case BuiltinType::Short: 326 Width = Target.getShortWidth(); 327 Align = Target.getShortAlign(); 328 break; 329 case BuiltinType::UInt: 330 case BuiltinType::Int: 331 Width = Target.getIntWidth(); 332 Align = Target.getIntAlign(); 333 break; 334 case BuiltinType::ULong: 335 case BuiltinType::Long: 336 Width = Target.getLongWidth(); 337 Align = Target.getLongAlign(); 338 break; 339 case BuiltinType::ULongLong: 340 case BuiltinType::LongLong: 341 Width = Target.getLongLongWidth(); 342 Align = Target.getLongLongAlign(); 343 break; 344 case BuiltinType::Int128: 345 case BuiltinType::UInt128: 346 Width = 128; 347 Align = 128; // int128_t is 128-bit aligned on all targets. 348 break; 349 case BuiltinType::Float: 350 Width = Target.getFloatWidth(); 351 Align = Target.getFloatAlign(); 352 break; 353 case BuiltinType::Double: 354 Width = Target.getDoubleWidth(); 355 Align = Target.getDoubleAlign(); 356 break; 357 case BuiltinType::LongDouble: 358 Width = Target.getLongDoubleWidth(); 359 Align = Target.getLongDoubleAlign(); 360 break; 361 case BuiltinType::NullPtr: 362 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 363 Align = Target.getPointerAlign(0); // == sizeof(void*) 364 break; 365 } 366 break; 367 case Type::FixedWidthInt: 368 // FIXME: This isn't precisely correct; the width/alignment should depend 369 // on the available types for the target 370 Width = cast<FixedWidthIntType>(T)->getWidth(); 371 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8); 372 Align = Width; 373 break; 374 case Type::ExtQual: 375 // FIXME: Pointers into different addr spaces could have different sizes and 376 // alignment requirements: getPointerInfo should take an AddrSpace. 377 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0)); 378 case Type::ObjCQualifiedId: 379 case Type::ObjCQualifiedInterface: 380 Width = Target.getPointerWidth(0); 381 Align = Target.getPointerAlign(0); 382 break; 383 case Type::BlockPointer: { 384 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 385 Width = Target.getPointerWidth(AS); 386 Align = Target.getPointerAlign(AS); 387 break; 388 } 389 case Type::Pointer: { 390 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 391 Width = Target.getPointerWidth(AS); 392 Align = Target.getPointerAlign(AS); 393 break; 394 } 395 case Type::LValueReference: 396 case Type::RValueReference: 397 // "When applied to a reference or a reference type, the result is the size 398 // of the referenced type." C++98 5.3.3p2: expr.sizeof. 399 // FIXME: This is wrong for struct layout: a reference in a struct has 400 // pointer size. 401 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType()); 402 case Type::MemberPointer: { 403 // FIXME: This is ABI dependent. We use the Itanium C++ ABI. 404 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers 405 // If we ever want to support other ABIs this needs to be abstracted. 406 407 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 408 std::pair<uint64_t, unsigned> PtrDiffInfo = 409 getTypeInfo(getPointerDiffType()); 410 Width = PtrDiffInfo.first; 411 if (Pointee->isFunctionType()) 412 Width *= 2; 413 Align = PtrDiffInfo.second; 414 break; 415 } 416 case Type::Complex: { 417 // Complex types have the same alignment as their elements, but twice the 418 // size. 419 std::pair<uint64_t, unsigned> EltInfo = 420 getTypeInfo(cast<ComplexType>(T)->getElementType()); 421 Width = EltInfo.first*2; 422 Align = EltInfo.second; 423 break; 424 } 425 case Type::ObjCInterface: { 426 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 427 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 428 Width = Layout.getSize(); 429 Align = Layout.getAlignment(); 430 break; 431 } 432 case Type::Record: 433 case Type::Enum: { 434 const TagType *TT = cast<TagType>(T); 435 436 if (TT->getDecl()->isInvalidDecl()) { 437 Width = 1; 438 Align = 1; 439 break; 440 } 441 442 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 443 return getTypeInfo(ET->getDecl()->getIntegerType()); 444 445 const RecordType *RT = cast<RecordType>(TT); 446 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 447 Width = Layout.getSize(); 448 Align = Layout.getAlignment(); 449 break; 450 } 451 452 case Type::Typedef: { 453 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 454 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) { 455 Align = Aligned->getAlignment(); 456 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr()); 457 } else 458 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 459 break; 460 } 461 462 case Type::TypeOfExpr: 463 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 464 .getTypePtr()); 465 466 case Type::TypeOf: 467 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 468 469 case Type::QualifiedName: 470 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr()); 471 472 case Type::TemplateSpecialization: 473 assert(getCanonicalType(T) != T && 474 "Cannot request the size of a dependent type"); 475 // FIXME: this is likely to be wrong once we support template 476 // aliases, since a template alias could refer to a typedef that 477 // has an __aligned__ attribute on it. 478 return getTypeInfo(getCanonicalType(T)); 479 } 480 481 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 482 return std::make_pair(Width, Align); 483} 484 485/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 486/// type for the current target in bits. This can be different than the ABI 487/// alignment in cases where it is beneficial for performance to overalign 488/// a data type. 489unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 490 unsigned ABIAlign = getTypeAlign(T); 491 492 // Double and long long should be naturally aligned if possible. 493 if (const ComplexType* CT = T->getAsComplexType()) 494 T = CT->getElementType().getTypePtr(); 495 if (T->isSpecificBuiltinType(BuiltinType::Double) || 496 T->isSpecificBuiltinType(BuiltinType::LongLong)) 497 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 498 499 return ABIAlign; 500} 501 502 503/// LayoutField - Field layout. 504void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo, 505 bool IsUnion, unsigned StructPacking, 506 ASTContext &Context) { 507 unsigned FieldPacking = StructPacking; 508 uint64_t FieldOffset = IsUnion ? 0 : Size; 509 uint64_t FieldSize; 510 unsigned FieldAlign; 511 512 // FIXME: Should this override struct packing? Probably we want to 513 // take the minimum? 514 if (const PackedAttr *PA = FD->getAttr<PackedAttr>()) 515 FieldPacking = PA->getAlignment(); 516 517 if (const Expr *BitWidthExpr = FD->getBitWidth()) { 518 // TODO: Need to check this algorithm on other targets! 519 // (tested on Linux-X86) 520 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue(); 521 522 std::pair<uint64_t, unsigned> FieldInfo = 523 Context.getTypeInfo(FD->getType()); 524 uint64_t TypeSize = FieldInfo.first; 525 526 // Determine the alignment of this bitfield. The packing 527 // attributes define a maximum and the alignment attribute defines 528 // a minimum. 529 // FIXME: What is the right behavior when the specified alignment 530 // is smaller than the specified packing? 531 FieldAlign = FieldInfo.second; 532 if (FieldPacking) 533 FieldAlign = std::min(FieldAlign, FieldPacking); 534 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 535 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 536 537 // Check if we need to add padding to give the field the correct 538 // alignment. 539 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 540 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 541 542 // Padding members don't affect overall alignment 543 if (!FD->getIdentifier()) 544 FieldAlign = 1; 545 } else { 546 if (FD->getType()->isIncompleteArrayType()) { 547 // This is a flexible array member; we can't directly 548 // query getTypeInfo about these, so we figure it out here. 549 // Flexible array members don't have any size, but they 550 // have to be aligned appropriately for their element type. 551 FieldSize = 0; 552 const ArrayType* ATy = Context.getAsArrayType(FD->getType()); 553 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 554 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) { 555 unsigned AS = RT->getPointeeType().getAddressSpace(); 556 FieldSize = Context.Target.getPointerWidth(AS); 557 FieldAlign = Context.Target.getPointerAlign(AS); 558 } else { 559 std::pair<uint64_t, unsigned> FieldInfo = 560 Context.getTypeInfo(FD->getType()); 561 FieldSize = FieldInfo.first; 562 FieldAlign = FieldInfo.second; 563 } 564 565 // Determine the alignment of this bitfield. The packing 566 // attributes define a maximum and the alignment attribute defines 567 // a minimum. Additionally, the packing alignment must be at least 568 // a byte for non-bitfields. 569 // 570 // FIXME: What is the right behavior when the specified alignment 571 // is smaller than the specified packing? 572 if (FieldPacking) 573 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking)); 574 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 575 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 576 577 // Round up the current record size to the field's alignment boundary. 578 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 579 } 580 581 // Place this field at the current location. 582 FieldOffsets[FieldNo] = FieldOffset; 583 584 // Reserve space for this field. 585 if (IsUnion) { 586 Size = std::max(Size, FieldSize); 587 } else { 588 Size = FieldOffset + FieldSize; 589 } 590 591 // Remember the next available offset. 592 NextOffset = Size; 593 594 // Remember max struct/class alignment. 595 Alignment = std::max(Alignment, FieldAlign); 596} 597 598static void CollectLocalObjCIvars(ASTContext *Ctx, 599 const ObjCInterfaceDecl *OI, 600 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 601 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 602 E = OI->ivar_end(); I != E; ++I) { 603 ObjCIvarDecl *IVDecl = *I; 604 if (!IVDecl->isInvalidDecl()) 605 Fields.push_back(cast<FieldDecl>(IVDecl)); 606 } 607} 608 609void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI, 610 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 611 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 612 CollectObjCIvars(SuperClass, Fields); 613 CollectLocalObjCIvars(this, OI, Fields); 614} 615 616/// ShallowCollectObjCIvars - 617/// Collect all ivars, including those synthesized, in the current class. 618/// 619void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 620 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars, 621 bool CollectSynthesized) { 622 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 623 E = OI->ivar_end(); I != E; ++I) { 624 Ivars.push_back(*I); 625 } 626 if (CollectSynthesized) 627 CollectSynthesizedIvars(OI, Ivars); 628} 629 630void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD, 631 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 632 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this), 633 E = PD->prop_end(*this); I != E; ++I) 634 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 635 Ivars.push_back(Ivar); 636 637 // Also look into nested protocols. 638 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), 639 E = PD->protocol_end(); P != E; ++P) 640 CollectProtocolSynthesizedIvars(*P, Ivars); 641} 642 643/// CollectSynthesizedIvars - 644/// This routine collect synthesized ivars for the designated class. 645/// 646void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI, 647 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 648 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this), 649 E = OI->prop_end(*this); I != E; ++I) { 650 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) 651 Ivars.push_back(Ivar); 652 } 653 // Also look into interface's protocol list for properties declared 654 // in the protocol and whose ivars are synthesized. 655 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 656 PE = OI->protocol_end(); P != PE; ++P) { 657 ObjCProtocolDecl *PD = (*P); 658 CollectProtocolSynthesizedIvars(PD, Ivars); 659 } 660} 661 662unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) { 663 unsigned count = 0; 664 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this), 665 E = PD->prop_end(*this); I != E; ++I) 666 if ((*I)->getPropertyIvarDecl()) 667 ++count; 668 669 // Also look into nested protocols. 670 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(), 671 E = PD->protocol_end(); P != E; ++P) 672 count += CountProtocolSynthesizedIvars(*P); 673 return count; 674} 675 676unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) 677{ 678 unsigned count = 0; 679 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this), 680 E = OI->prop_end(*this); I != E; ++I) { 681 if ((*I)->getPropertyIvarDecl()) 682 ++count; 683 } 684 // Also look into interface's protocol list for properties declared 685 // in the protocol and whose ivars are synthesized. 686 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 687 PE = OI->protocol_end(); P != PE; ++P) { 688 ObjCProtocolDecl *PD = (*P); 689 count += CountProtocolSynthesizedIvars(PD); 690 } 691 return count; 692} 693 694/// getInterfaceLayoutImpl - Get or compute information about the 695/// layout of the given interface. 696/// 697/// \param Impl - If given, also include the layout of the interface's 698/// implementation. This may differ by including synthesized ivars. 699const ASTRecordLayout & 700ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 701 const ObjCImplementationDecl *Impl) { 702 assert(!D->isForwardDecl() && "Invalid interface decl!"); 703 704 // Look up this layout, if already laid out, return what we have. 705 ObjCContainerDecl *Key = 706 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 707 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 708 return *Entry; 709 710 unsigned FieldCount = D->ivar_size(); 711 // Add in synthesized ivar count if laying out an implementation. 712 if (Impl) { 713 unsigned SynthCount = CountSynthesizedIvars(D); 714 FieldCount += SynthCount; 715 // If there aren't any sythesized ivars then reuse the interface 716 // entry. Note we can't cache this because we simply free all 717 // entries later; however we shouldn't look up implementations 718 // frequently. 719 if (SynthCount == 0) 720 return getObjCLayout(D, 0); 721 } 722 723 ASTRecordLayout *NewEntry = NULL; 724 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 725 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD); 726 unsigned Alignment = SL.getAlignment(); 727 728 // We start laying out ivars not at the end of the superclass 729 // structure, but at the next byte following the last field. 730 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8); 731 732 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment); 733 NewEntry->InitializeLayout(FieldCount); 734 } else { 735 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(); 736 NewEntry->InitializeLayout(FieldCount); 737 } 738 739 unsigned StructPacking = 0; 740 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 741 StructPacking = PA->getAlignment(); 742 743 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 744 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 745 AA->getAlignment())); 746 747 // Layout each ivar sequentially. 748 unsigned i = 0; 749 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars; 750 ShallowCollectObjCIvars(D, Ivars, Impl); 751 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) 752 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this); 753 754 // Finally, round the size of the total struct up to the alignment of the 755 // struct itself. 756 NewEntry->FinalizeLayout(); 757 return *NewEntry; 758} 759 760const ASTRecordLayout & 761ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 762 return getObjCLayout(D, 0); 763} 764 765const ASTRecordLayout & 766ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 767 return getObjCLayout(D->getClassInterface(), D); 768} 769 770/// getASTRecordLayout - Get or compute information about the layout of the 771/// specified record (struct/union/class), which indicates its size and field 772/// position information. 773const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 774 D = D->getDefinition(*this); 775 assert(D && "Cannot get layout of forward declarations!"); 776 777 // Look up this layout, if already laid out, return what we have. 778 const ASTRecordLayout *&Entry = ASTRecordLayouts[D]; 779 if (Entry) return *Entry; 780 781 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 782 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 783 ASTRecordLayout *NewEntry = new ASTRecordLayout(); 784 Entry = NewEntry; 785 786 // FIXME: Avoid linear walk through the fields, if possible. 787 NewEntry->InitializeLayout(std::distance(D->field_begin(*this), 788 D->field_end(*this))); 789 bool IsUnion = D->isUnion(); 790 791 unsigned StructPacking = 0; 792 if (const PackedAttr *PA = D->getAttr<PackedAttr>()) 793 StructPacking = PA->getAlignment(); 794 795 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 796 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 797 AA->getAlignment())); 798 799 // Layout each field, for now, just sequentially, respecting alignment. In 800 // the future, this will need to be tweakable by targets. 801 unsigned FieldIdx = 0; 802 for (RecordDecl::field_iterator Field = D->field_begin(*this), 803 FieldEnd = D->field_end(*this); 804 Field != FieldEnd; (void)++Field, ++FieldIdx) 805 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this); 806 807 // Finally, round the size of the total struct up to the alignment of the 808 // struct itself. 809 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus); 810 return *NewEntry; 811} 812 813//===----------------------------------------------------------------------===// 814// Type creation/memoization methods 815//===----------------------------------------------------------------------===// 816 817QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 818 QualType CanT = getCanonicalType(T); 819 if (CanT.getAddressSpace() == AddressSpace) 820 return T; 821 822 // If we are composing extended qualifiers together, merge together into one 823 // ExtQualType node. 824 unsigned CVRQuals = T.getCVRQualifiers(); 825 QualType::GCAttrTypes GCAttr = QualType::GCNone; 826 Type *TypeNode = T.getTypePtr(); 827 828 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 829 // If this type already has an address space specified, it cannot get 830 // another one. 831 assert(EQT->getAddressSpace() == 0 && 832 "Type cannot be in multiple addr spaces!"); 833 GCAttr = EQT->getObjCGCAttr(); 834 TypeNode = EQT->getBaseType(); 835 } 836 837 // Check if we've already instantiated this type. 838 llvm::FoldingSetNodeID ID; 839 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 840 void *InsertPos = 0; 841 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 842 return QualType(EXTQy, CVRQuals); 843 844 // If the base type isn't canonical, this won't be a canonical type either, 845 // so fill in the canonical type field. 846 QualType Canonical; 847 if (!TypeNode->isCanonical()) { 848 Canonical = getAddrSpaceQualType(CanT, AddressSpace); 849 850 // Update InsertPos, the previous call could have invalidated it. 851 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 852 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 853 } 854 ExtQualType *New = 855 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 856 ExtQualTypes.InsertNode(New, InsertPos); 857 Types.push_back(New); 858 return QualType(New, CVRQuals); 859} 860 861QualType ASTContext::getObjCGCQualType(QualType T, 862 QualType::GCAttrTypes GCAttr) { 863 QualType CanT = getCanonicalType(T); 864 if (CanT.getObjCGCAttr() == GCAttr) 865 return T; 866 867 if (T->isPointerType()) { 868 QualType Pointee = T->getAsPointerType()->getPointeeType(); 869 if (Pointee->isPointerType()) { 870 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 871 return getPointerType(ResultType); 872 } 873 } 874 // If we are composing extended qualifiers together, merge together into one 875 // ExtQualType node. 876 unsigned CVRQuals = T.getCVRQualifiers(); 877 Type *TypeNode = T.getTypePtr(); 878 unsigned AddressSpace = 0; 879 880 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) { 881 // If this type already has an address space specified, it cannot get 882 // another one. 883 assert(EQT->getObjCGCAttr() == QualType::GCNone && 884 "Type cannot be in multiple addr spaces!"); 885 AddressSpace = EQT->getAddressSpace(); 886 TypeNode = EQT->getBaseType(); 887 } 888 889 // Check if we've already instantiated an gc qual'd type of this type. 890 llvm::FoldingSetNodeID ID; 891 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr); 892 void *InsertPos = 0; 893 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 894 return QualType(EXTQy, CVRQuals); 895 896 // If the base type isn't canonical, this won't be a canonical type either, 897 // so fill in the canonical type field. 898 // FIXME: Isn't this also not canonical if the base type is a array 899 // or pointer type? I can't find any documentation for objc_gc, though... 900 QualType Canonical; 901 if (!T->isCanonical()) { 902 Canonical = getObjCGCQualType(CanT, GCAttr); 903 904 // Update InsertPos, the previous call could have invalidated it. 905 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos); 906 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 907 } 908 ExtQualType *New = 909 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr); 910 ExtQualTypes.InsertNode(New, InsertPos); 911 Types.push_back(New); 912 return QualType(New, CVRQuals); 913} 914 915/// getComplexType - Return the uniqued reference to the type for a complex 916/// number with the specified element type. 917QualType ASTContext::getComplexType(QualType T) { 918 // Unique pointers, to guarantee there is only one pointer of a particular 919 // structure. 920 llvm::FoldingSetNodeID ID; 921 ComplexType::Profile(ID, T); 922 923 void *InsertPos = 0; 924 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 925 return QualType(CT, 0); 926 927 // If the pointee type isn't canonical, this won't be a canonical type either, 928 // so fill in the canonical type field. 929 QualType Canonical; 930 if (!T->isCanonical()) { 931 Canonical = getComplexType(getCanonicalType(T)); 932 933 // Get the new insert position for the node we care about. 934 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 935 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 936 } 937 ComplexType *New = new (*this,8) ComplexType(T, Canonical); 938 Types.push_back(New); 939 ComplexTypes.InsertNode(New, InsertPos); 940 return QualType(New, 0); 941} 942 943QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) { 944 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ? 945 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes; 946 FixedWidthIntType *&Entry = Map[Width]; 947 if (!Entry) 948 Entry = new FixedWidthIntType(Width, Signed); 949 return QualType(Entry, 0); 950} 951 952/// getPointerType - Return the uniqued reference to the type for a pointer to 953/// the specified type. 954QualType ASTContext::getPointerType(QualType T) { 955 // Unique pointers, to guarantee there is only one pointer of a particular 956 // structure. 957 llvm::FoldingSetNodeID ID; 958 PointerType::Profile(ID, T); 959 960 void *InsertPos = 0; 961 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 962 return QualType(PT, 0); 963 964 // If the pointee type isn't canonical, this won't be a canonical type either, 965 // so fill in the canonical type field. 966 QualType Canonical; 967 if (!T->isCanonical()) { 968 Canonical = getPointerType(getCanonicalType(T)); 969 970 // Get the new insert position for the node we care about. 971 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 972 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 973 } 974 PointerType *New = new (*this,8) PointerType(T, Canonical); 975 Types.push_back(New); 976 PointerTypes.InsertNode(New, InsertPos); 977 return QualType(New, 0); 978} 979 980/// getBlockPointerType - Return the uniqued reference to the type for 981/// a pointer to the specified block. 982QualType ASTContext::getBlockPointerType(QualType T) { 983 assert(T->isFunctionType() && "block of function types only"); 984 // Unique pointers, to guarantee there is only one block of a particular 985 // structure. 986 llvm::FoldingSetNodeID ID; 987 BlockPointerType::Profile(ID, T); 988 989 void *InsertPos = 0; 990 if (BlockPointerType *PT = 991 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 992 return QualType(PT, 0); 993 994 // If the block pointee type isn't canonical, this won't be a canonical 995 // type either so fill in the canonical type field. 996 QualType Canonical; 997 if (!T->isCanonical()) { 998 Canonical = getBlockPointerType(getCanonicalType(T)); 999 1000 // Get the new insert position for the node we care about. 1001 BlockPointerType *NewIP = 1002 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1003 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1004 } 1005 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical); 1006 Types.push_back(New); 1007 BlockPointerTypes.InsertNode(New, InsertPos); 1008 return QualType(New, 0); 1009} 1010 1011/// getLValueReferenceType - Return the uniqued reference to the type for an 1012/// lvalue reference to the specified type. 1013QualType ASTContext::getLValueReferenceType(QualType T) { 1014 // Unique pointers, to guarantee there is only one pointer of a particular 1015 // structure. 1016 llvm::FoldingSetNodeID ID; 1017 ReferenceType::Profile(ID, T); 1018 1019 void *InsertPos = 0; 1020 if (LValueReferenceType *RT = 1021 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1022 return QualType(RT, 0); 1023 1024 // If the referencee type isn't canonical, this won't be a canonical type 1025 // either, so fill in the canonical type field. 1026 QualType Canonical; 1027 if (!T->isCanonical()) { 1028 Canonical = getLValueReferenceType(getCanonicalType(T)); 1029 1030 // Get the new insert position for the node we care about. 1031 LValueReferenceType *NewIP = 1032 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1033 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1034 } 1035 1036 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical); 1037 Types.push_back(New); 1038 LValueReferenceTypes.InsertNode(New, InsertPos); 1039 return QualType(New, 0); 1040} 1041 1042/// getRValueReferenceType - Return the uniqued reference to the type for an 1043/// rvalue reference to the specified type. 1044QualType ASTContext::getRValueReferenceType(QualType T) { 1045 // Unique pointers, to guarantee there is only one pointer of a particular 1046 // structure. 1047 llvm::FoldingSetNodeID ID; 1048 ReferenceType::Profile(ID, T); 1049 1050 void *InsertPos = 0; 1051 if (RValueReferenceType *RT = 1052 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1053 return QualType(RT, 0); 1054 1055 // If the referencee type isn't canonical, this won't be a canonical type 1056 // either, so fill in the canonical type field. 1057 QualType Canonical; 1058 if (!T->isCanonical()) { 1059 Canonical = getRValueReferenceType(getCanonicalType(T)); 1060 1061 // Get the new insert position for the node we care about. 1062 RValueReferenceType *NewIP = 1063 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1064 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1065 } 1066 1067 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical); 1068 Types.push_back(New); 1069 RValueReferenceTypes.InsertNode(New, InsertPos); 1070 return QualType(New, 0); 1071} 1072 1073/// getMemberPointerType - Return the uniqued reference to the type for a 1074/// member pointer to the specified type, in the specified class. 1075QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) 1076{ 1077 // Unique pointers, to guarantee there is only one pointer of a particular 1078 // structure. 1079 llvm::FoldingSetNodeID ID; 1080 MemberPointerType::Profile(ID, T, Cls); 1081 1082 void *InsertPos = 0; 1083 if (MemberPointerType *PT = 1084 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1085 return QualType(PT, 0); 1086 1087 // If the pointee or class type isn't canonical, this won't be a canonical 1088 // type either, so fill in the canonical type field. 1089 QualType Canonical; 1090 if (!T->isCanonical()) { 1091 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1092 1093 // Get the new insert position for the node we care about. 1094 MemberPointerType *NewIP = 1095 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1096 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1097 } 1098 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical); 1099 Types.push_back(New); 1100 MemberPointerTypes.InsertNode(New, InsertPos); 1101 return QualType(New, 0); 1102} 1103 1104/// getConstantArrayType - Return the unique reference to the type for an 1105/// array of the specified element type. 1106QualType ASTContext::getConstantArrayType(QualType EltTy, 1107 const llvm::APInt &ArySizeIn, 1108 ArrayType::ArraySizeModifier ASM, 1109 unsigned EltTypeQuals) { 1110 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) && 1111 "Constant array of VLAs is illegal!"); 1112 1113 // Convert the array size into a canonical width matching the pointer size for 1114 // the target. 1115 llvm::APInt ArySize(ArySizeIn); 1116 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1117 1118 llvm::FoldingSetNodeID ID; 1119 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1120 1121 void *InsertPos = 0; 1122 if (ConstantArrayType *ATP = 1123 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1124 return QualType(ATP, 0); 1125 1126 // If the element type isn't canonical, this won't be a canonical type either, 1127 // so fill in the canonical type field. 1128 QualType Canonical; 1129 if (!EltTy->isCanonical()) { 1130 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1131 ASM, EltTypeQuals); 1132 // Get the new insert position for the node we care about. 1133 ConstantArrayType *NewIP = 1134 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1135 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1136 } 1137 1138 ConstantArrayType *New = 1139 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1140 ConstantArrayTypes.InsertNode(New, InsertPos); 1141 Types.push_back(New); 1142 return QualType(New, 0); 1143} 1144 1145/// getVariableArrayType - Returns a non-unique reference to the type for a 1146/// variable array of the specified element type. 1147QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 1148 ArrayType::ArraySizeModifier ASM, 1149 unsigned EltTypeQuals) { 1150 // Since we don't unique expressions, it isn't possible to unique VLA's 1151 // that have an expression provided for their size. 1152 1153 VariableArrayType *New = 1154 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals); 1155 1156 VariableArrayTypes.push_back(New); 1157 Types.push_back(New); 1158 return QualType(New, 0); 1159} 1160 1161/// getDependentSizedArrayType - Returns a non-unique reference to 1162/// the type for a dependently-sized array of the specified element 1163/// type. FIXME: We will need these to be uniqued, or at least 1164/// comparable, at some point. 1165QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts, 1166 ArrayType::ArraySizeModifier ASM, 1167 unsigned EltTypeQuals) { 1168 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) && 1169 "Size must be type- or value-dependent!"); 1170 1171 // Since we don't unique expressions, it isn't possible to unique 1172 // dependently-sized array types. 1173 1174 DependentSizedArrayType *New = 1175 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts, 1176 ASM, EltTypeQuals); 1177 1178 DependentSizedArrayTypes.push_back(New); 1179 Types.push_back(New); 1180 return QualType(New, 0); 1181} 1182 1183QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1184 ArrayType::ArraySizeModifier ASM, 1185 unsigned EltTypeQuals) { 1186 llvm::FoldingSetNodeID ID; 1187 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1188 1189 void *InsertPos = 0; 1190 if (IncompleteArrayType *ATP = 1191 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1192 return QualType(ATP, 0); 1193 1194 // If the element type isn't canonical, this won't be a canonical type 1195 // either, so fill in the canonical type field. 1196 QualType Canonical; 1197 1198 if (!EltTy->isCanonical()) { 1199 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1200 ASM, EltTypeQuals); 1201 1202 // Get the new insert position for the node we care about. 1203 IncompleteArrayType *NewIP = 1204 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1205 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1206 } 1207 1208 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical, 1209 ASM, EltTypeQuals); 1210 1211 IncompleteArrayTypes.InsertNode(New, InsertPos); 1212 Types.push_back(New); 1213 return QualType(New, 0); 1214} 1215 1216/// getVectorType - Return the unique reference to a vector type of 1217/// the specified element type and size. VectorType must be a built-in type. 1218QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { 1219 BuiltinType *baseType; 1220 1221 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1222 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 1223 1224 // Check if we've already instantiated a vector of this type. 1225 llvm::FoldingSetNodeID ID; 1226 VectorType::Profile(ID, vecType, NumElts, Type::Vector); 1227 void *InsertPos = 0; 1228 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1229 return QualType(VTP, 0); 1230 1231 // If the element type isn't canonical, this won't be a canonical type either, 1232 // so fill in the canonical type field. 1233 QualType Canonical; 1234 if (!vecType->isCanonical()) { 1235 Canonical = getVectorType(getCanonicalType(vecType), NumElts); 1236 1237 // Get the new insert position for the node we care about. 1238 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1239 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1240 } 1241 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical); 1242 VectorTypes.InsertNode(New, InsertPos); 1243 Types.push_back(New); 1244 return QualType(New, 0); 1245} 1246 1247/// getExtVectorType - Return the unique reference to an extended vector type of 1248/// the specified element type and size. VectorType must be a built-in type. 1249QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1250 BuiltinType *baseType; 1251 1252 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1253 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1254 1255 // Check if we've already instantiated a vector of this type. 1256 llvm::FoldingSetNodeID ID; 1257 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); 1258 void *InsertPos = 0; 1259 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1260 return QualType(VTP, 0); 1261 1262 // If the element type isn't canonical, this won't be a canonical type either, 1263 // so fill in the canonical type field. 1264 QualType Canonical; 1265 if (!vecType->isCanonical()) { 1266 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1267 1268 // Get the new insert position for the node we care about. 1269 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1270 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1271 } 1272 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical); 1273 VectorTypes.InsertNode(New, InsertPos); 1274 Types.push_back(New); 1275 return QualType(New, 0); 1276} 1277 1278/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1279/// 1280QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) { 1281 // Unique functions, to guarantee there is only one function of a particular 1282 // structure. 1283 llvm::FoldingSetNodeID ID; 1284 FunctionNoProtoType::Profile(ID, ResultTy); 1285 1286 void *InsertPos = 0; 1287 if (FunctionNoProtoType *FT = 1288 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1289 return QualType(FT, 0); 1290 1291 QualType Canonical; 1292 if (!ResultTy->isCanonical()) { 1293 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy)); 1294 1295 // Get the new insert position for the node we care about. 1296 FunctionNoProtoType *NewIP = 1297 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1298 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1299 } 1300 1301 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical); 1302 Types.push_back(New); 1303 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1304 return QualType(New, 0); 1305} 1306 1307/// getFunctionType - Return a normal function type with a typed argument 1308/// list. isVariadic indicates whether the argument list includes '...'. 1309QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1310 unsigned NumArgs, bool isVariadic, 1311 unsigned TypeQuals, bool hasExceptionSpec, 1312 bool hasAnyExceptionSpec, unsigned NumExs, 1313 const QualType *ExArray) { 1314 // Unique functions, to guarantee there is only one function of a particular 1315 // structure. 1316 llvm::FoldingSetNodeID ID; 1317 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1318 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1319 NumExs, ExArray); 1320 1321 void *InsertPos = 0; 1322 if (FunctionProtoType *FTP = 1323 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1324 return QualType(FTP, 0); 1325 1326 // Determine whether the type being created is already canonical or not. 1327 bool isCanonical = ResultTy->isCanonical(); 1328 if (hasExceptionSpec) 1329 isCanonical = false; 1330 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1331 if (!ArgArray[i]->isCanonical()) 1332 isCanonical = false; 1333 1334 // If this type isn't canonical, get the canonical version of it. 1335 // The exception spec is not part of the canonical type. 1336 QualType Canonical; 1337 if (!isCanonical) { 1338 llvm::SmallVector<QualType, 16> CanonicalArgs; 1339 CanonicalArgs.reserve(NumArgs); 1340 for (unsigned i = 0; i != NumArgs; ++i) 1341 CanonicalArgs.push_back(getCanonicalType(ArgArray[i])); 1342 1343 Canonical = getFunctionType(getCanonicalType(ResultTy), 1344 CanonicalArgs.data(), NumArgs, 1345 isVariadic, TypeQuals); 1346 1347 // Get the new insert position for the node we care about. 1348 FunctionProtoType *NewIP = 1349 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1351 } 1352 1353 // FunctionProtoType objects are allocated with extra bytes after them 1354 // for two variable size arrays (for parameter and exception types) at the 1355 // end of them. 1356 FunctionProtoType *FTP = 1357 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1358 NumArgs*sizeof(QualType) + 1359 NumExs*sizeof(QualType), 8); 1360 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1361 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1362 ExArray, NumExs, Canonical); 1363 Types.push_back(FTP); 1364 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1365 return QualType(FTP, 0); 1366} 1367 1368/// getTypeDeclType - Return the unique reference to the type for the 1369/// specified type declaration. 1370QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) { 1371 assert(Decl && "Passed null for Decl param"); 1372 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1373 1374 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1375 return getTypedefType(Typedef); 1376 else if (isa<TemplateTypeParmDecl>(Decl)) { 1377 assert(false && "Template type parameter types are always available."); 1378 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl)) 1379 return getObjCInterfaceType(ObjCInterface); 1380 1381 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1382 if (PrevDecl) 1383 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1384 else 1385 Decl->TypeForDecl = new (*this,8) RecordType(Record); 1386 } 1387 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1388 if (PrevDecl) 1389 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1390 else 1391 Decl->TypeForDecl = new (*this,8) EnumType(Enum); 1392 } 1393 else 1394 assert(false && "TypeDecl without a type?"); 1395 1396 if (!PrevDecl) Types.push_back(Decl->TypeForDecl); 1397 return QualType(Decl->TypeForDecl, 0); 1398} 1399 1400/// getTypedefType - Return the unique reference to the type for the 1401/// specified typename decl. 1402QualType ASTContext::getTypedefType(TypedefDecl *Decl) { 1403 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1404 1405 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 1406 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical); 1407 Types.push_back(Decl->TypeForDecl); 1408 return QualType(Decl->TypeForDecl, 0); 1409} 1410 1411/// getObjCInterfaceType - Return the unique reference to the type for the 1412/// specified ObjC interface decl. 1413QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 1414 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1415 1416 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl); 1417 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID); 1418 Types.push_back(Decl->TypeForDecl); 1419 return QualType(Decl->TypeForDecl, 0); 1420} 1421 1422/// \brief Retrieve the template type parameter type for a template 1423/// parameter with the given depth, index, and (optionally) name. 1424QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1425 IdentifierInfo *Name) { 1426 llvm::FoldingSetNodeID ID; 1427 TemplateTypeParmType::Profile(ID, Depth, Index, Name); 1428 void *InsertPos = 0; 1429 TemplateTypeParmType *TypeParm 1430 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1431 1432 if (TypeParm) 1433 return QualType(TypeParm, 0); 1434 1435 if (Name) 1436 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name, 1437 getTemplateTypeParmType(Depth, Index)); 1438 else 1439 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index); 1440 1441 Types.push_back(TypeParm); 1442 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1443 1444 return QualType(TypeParm, 0); 1445} 1446 1447QualType 1448ASTContext::getTemplateSpecializationType(TemplateName Template, 1449 const TemplateArgument *Args, 1450 unsigned NumArgs, 1451 QualType Canon) { 1452 if (!Canon.isNull()) 1453 Canon = getCanonicalType(Canon); 1454 1455 llvm::FoldingSetNodeID ID; 1456 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs); 1457 1458 void *InsertPos = 0; 1459 TemplateSpecializationType *Spec 1460 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 1461 1462 if (Spec) 1463 return QualType(Spec, 0); 1464 1465 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 1466 sizeof(TemplateArgument) * NumArgs), 1467 8); 1468 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon); 1469 Types.push_back(Spec); 1470 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 1471 1472 return QualType(Spec, 0); 1473} 1474 1475QualType 1476ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS, 1477 QualType NamedType) { 1478 llvm::FoldingSetNodeID ID; 1479 QualifiedNameType::Profile(ID, NNS, NamedType); 1480 1481 void *InsertPos = 0; 1482 QualifiedNameType *T 1483 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); 1484 if (T) 1485 return QualType(T, 0); 1486 1487 T = new (*this) QualifiedNameType(NNS, NamedType, 1488 getCanonicalType(NamedType)); 1489 Types.push_back(T); 1490 QualifiedNameTypes.InsertNode(T, InsertPos); 1491 return QualType(T, 0); 1492} 1493 1494QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1495 const IdentifierInfo *Name, 1496 QualType Canon) { 1497 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1498 1499 if (Canon.isNull()) { 1500 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1501 if (CanonNNS != NNS) 1502 Canon = getTypenameType(CanonNNS, Name); 1503 } 1504 1505 llvm::FoldingSetNodeID ID; 1506 TypenameType::Profile(ID, NNS, Name); 1507 1508 void *InsertPos = 0; 1509 TypenameType *T 1510 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1511 if (T) 1512 return QualType(T, 0); 1513 1514 T = new (*this) TypenameType(NNS, Name, Canon); 1515 Types.push_back(T); 1516 TypenameTypes.InsertNode(T, InsertPos); 1517 return QualType(T, 0); 1518} 1519 1520QualType 1521ASTContext::getTypenameType(NestedNameSpecifier *NNS, 1522 const TemplateSpecializationType *TemplateId, 1523 QualType Canon) { 1524 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 1525 1526 if (Canon.isNull()) { 1527 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 1528 QualType CanonType = getCanonicalType(QualType(TemplateId, 0)); 1529 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) { 1530 const TemplateSpecializationType *CanonTemplateId 1531 = CanonType->getAsTemplateSpecializationType(); 1532 assert(CanonTemplateId && 1533 "Canonical type must also be a template specialization type"); 1534 Canon = getTypenameType(CanonNNS, CanonTemplateId); 1535 } 1536 } 1537 1538 llvm::FoldingSetNodeID ID; 1539 TypenameType::Profile(ID, NNS, TemplateId); 1540 1541 void *InsertPos = 0; 1542 TypenameType *T 1543 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos); 1544 if (T) 1545 return QualType(T, 0); 1546 1547 T = new (*this) TypenameType(NNS, TemplateId, Canon); 1548 Types.push_back(T); 1549 TypenameTypes.InsertNode(T, InsertPos); 1550 return QualType(T, 0); 1551} 1552 1553/// CmpProtocolNames - Comparison predicate for sorting protocols 1554/// alphabetically. 1555static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 1556 const ObjCProtocolDecl *RHS) { 1557 return LHS->getDeclName() < RHS->getDeclName(); 1558} 1559 1560static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, 1561 unsigned &NumProtocols) { 1562 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 1563 1564 // Sort protocols, keyed by name. 1565 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 1566 1567 // Remove duplicates. 1568 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 1569 NumProtocols = ProtocolsEnd-Protocols; 1570} 1571 1572 1573/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for 1574/// the given interface decl and the conforming protocol list. 1575QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl, 1576 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 1577 // Sort the protocol list alphabetically to canonicalize it. 1578 SortAndUniqueProtocols(Protocols, NumProtocols); 1579 1580 llvm::FoldingSetNodeID ID; 1581 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 1582 1583 void *InsertPos = 0; 1584 if (ObjCQualifiedInterfaceType *QT = 1585 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1586 return QualType(QT, 0); 1587 1588 // No Match; 1589 ObjCQualifiedInterfaceType *QType = 1590 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols); 1591 1592 Types.push_back(QType); 1593 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos); 1594 return QualType(QType, 0); 1595} 1596 1597/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl 1598/// and the conforming protocol list. 1599QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols, 1600 unsigned NumProtocols) { 1601 // Sort the protocol list alphabetically to canonicalize it. 1602 SortAndUniqueProtocols(Protocols, NumProtocols); 1603 1604 llvm::FoldingSetNodeID ID; 1605 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols); 1606 1607 void *InsertPos = 0; 1608 if (ObjCQualifiedIdType *QT = 1609 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos)) 1610 return QualType(QT, 0); 1611 1612 // No Match; 1613 ObjCQualifiedIdType *QType = 1614 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols); 1615 Types.push_back(QType); 1616 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos); 1617 return QualType(QType, 0); 1618} 1619 1620/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 1621/// TypeOfExprType AST's (since expression's are never shared). For example, 1622/// multiple declarations that refer to "typeof(x)" all contain different 1623/// DeclRefExpr's. This doesn't effect the type checker, since it operates 1624/// on canonical type's (which are always unique). 1625QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 1626 QualType Canonical = getCanonicalType(tofExpr->getType()); 1627 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical); 1628 Types.push_back(toe); 1629 return QualType(toe, 0); 1630} 1631 1632/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 1633/// TypeOfType AST's. The only motivation to unique these nodes would be 1634/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 1635/// an issue. This doesn't effect the type checker, since it operates 1636/// on canonical type's (which are always unique). 1637QualType ASTContext::getTypeOfType(QualType tofType) { 1638 QualType Canonical = getCanonicalType(tofType); 1639 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical); 1640 Types.push_back(tot); 1641 return QualType(tot, 0); 1642} 1643 1644/// getTagDeclType - Return the unique reference to the type for the 1645/// specified TagDecl (struct/union/class/enum) decl. 1646QualType ASTContext::getTagDeclType(TagDecl *Decl) { 1647 assert (Decl); 1648 return getTypeDeclType(Decl); 1649} 1650 1651/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 1652/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 1653/// needs to agree with the definition in <stddef.h>. 1654QualType ASTContext::getSizeType() const { 1655 return getFromTargetType(Target.getSizeType()); 1656} 1657 1658/// getSignedWCharType - Return the type of "signed wchar_t". 1659/// Used when in C++, as a GCC extension. 1660QualType ASTContext::getSignedWCharType() const { 1661 // FIXME: derive from "Target" ? 1662 return WCharTy; 1663} 1664 1665/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 1666/// Used when in C++, as a GCC extension. 1667QualType ASTContext::getUnsignedWCharType() const { 1668 // FIXME: derive from "Target" ? 1669 return UnsignedIntTy; 1670} 1671 1672/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 1673/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1674QualType ASTContext::getPointerDiffType() const { 1675 return getFromTargetType(Target.getPtrDiffType(0)); 1676} 1677 1678//===----------------------------------------------------------------------===// 1679// Type Operators 1680//===----------------------------------------------------------------------===// 1681 1682/// getCanonicalType - Return the canonical (structural) type corresponding to 1683/// the specified potentially non-canonical type. The non-canonical version 1684/// of a type may have many "decorated" versions of types. Decorators can 1685/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 1686/// to be free of any of these, allowing two canonical types to be compared 1687/// for exact equality with a simple pointer comparison. 1688QualType ASTContext::getCanonicalType(QualType T) { 1689 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); 1690 1691 // If the result has type qualifiers, make sure to canonicalize them as well. 1692 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); 1693 if (TypeQuals == 0) return CanType; 1694 1695 // If the type qualifiers are on an array type, get the canonical type of the 1696 // array with the qualifiers applied to the element type. 1697 ArrayType *AT = dyn_cast<ArrayType>(CanType); 1698 if (!AT) 1699 return CanType.getQualifiedType(TypeQuals); 1700 1701 // Get the canonical version of the element with the extra qualifiers on it. 1702 // This can recursively sink qualifiers through multiple levels of arrays. 1703 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); 1704 NewEltTy = getCanonicalType(NewEltTy); 1705 1706 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1707 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(), 1708 CAT->getIndexTypeQualifier()); 1709 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 1710 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 1711 IAT->getIndexTypeQualifier()); 1712 1713 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 1714 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(), 1715 DSAT->getSizeModifier(), 1716 DSAT->getIndexTypeQualifier()); 1717 1718 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1719 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1720 VAT->getSizeModifier(), 1721 VAT->getIndexTypeQualifier()); 1722} 1723 1724Decl *ASTContext::getCanonicalDecl(Decl *D) { 1725 if (!D) 1726 return 0; 1727 1728 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) { 1729 QualType T = getTagDeclType(Tag); 1730 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType) 1731 ->getDecl()); 1732 } 1733 1734 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) { 1735 while (Template->getPreviousDeclaration()) 1736 Template = Template->getPreviousDeclaration(); 1737 return Template; 1738 } 1739 1740 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 1741 while (Function->getPreviousDeclaration()) 1742 Function = Function->getPreviousDeclaration(); 1743 return const_cast<FunctionDecl *>(Function); 1744 } 1745 1746 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 1747 while (Var->getPreviousDeclaration()) 1748 Var = Var->getPreviousDeclaration(); 1749 return const_cast<VarDecl *>(Var); 1750 } 1751 1752 return D; 1753} 1754 1755TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 1756 // If this template name refers to a template, the canonical 1757 // template name merely stores the template itself. 1758 if (TemplateDecl *Template = Name.getAsTemplateDecl()) 1759 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template))); 1760 1761 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 1762 assert(DTN && "Non-dependent template names must refer to template decls."); 1763 return DTN->CanonicalTemplateName; 1764} 1765 1766NestedNameSpecifier * 1767ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 1768 if (!NNS) 1769 return 0; 1770 1771 switch (NNS->getKind()) { 1772 case NestedNameSpecifier::Identifier: 1773 // Canonicalize the prefix but keep the identifier the same. 1774 return NestedNameSpecifier::Create(*this, 1775 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 1776 NNS->getAsIdentifier()); 1777 1778 case NestedNameSpecifier::Namespace: 1779 // A namespace is canonical; build a nested-name-specifier with 1780 // this namespace and no prefix. 1781 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 1782 1783 case NestedNameSpecifier::TypeSpec: 1784 case NestedNameSpecifier::TypeSpecWithTemplate: { 1785 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 1786 NestedNameSpecifier *Prefix = 0; 1787 1788 // FIXME: This isn't the right check! 1789 if (T->isDependentType()) 1790 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix()); 1791 1792 return NestedNameSpecifier::Create(*this, Prefix, 1793 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 1794 T.getTypePtr()); 1795 } 1796 1797 case NestedNameSpecifier::Global: 1798 // The global specifier is canonical and unique. 1799 return NNS; 1800 } 1801 1802 // Required to silence a GCC warning 1803 return 0; 1804} 1805 1806 1807const ArrayType *ASTContext::getAsArrayType(QualType T) { 1808 // Handle the non-qualified case efficiently. 1809 if (T.getCVRQualifiers() == 0) { 1810 // Handle the common positive case fast. 1811 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 1812 return AT; 1813 } 1814 1815 // Handle the common negative case fast, ignoring CVR qualifiers. 1816 QualType CType = T->getCanonicalTypeInternal(); 1817 1818 // Make sure to look through type qualifiers (like ExtQuals) for the negative 1819 // test. 1820 if (!isa<ArrayType>(CType) && 1821 !isa<ArrayType>(CType.getUnqualifiedType())) 1822 return 0; 1823 1824 // Apply any CVR qualifiers from the array type to the element type. This 1825 // implements C99 6.7.3p8: "If the specification of an array type includes 1826 // any type qualifiers, the element type is so qualified, not the array type." 1827 1828 // If we get here, we either have type qualifiers on the type, or we have 1829 // sugar such as a typedef in the way. If we have type qualifiers on the type 1830 // we must propagate them down into the elemeng type. 1831 unsigned CVRQuals = T.getCVRQualifiers(); 1832 unsigned AddrSpace = 0; 1833 Type *Ty = T.getTypePtr(); 1834 1835 // Rip through ExtQualType's and typedefs to get to a concrete type. 1836 while (1) { 1837 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) { 1838 AddrSpace = EXTQT->getAddressSpace(); 1839 Ty = EXTQT->getBaseType(); 1840 } else { 1841 T = Ty->getDesugaredType(); 1842 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0) 1843 break; 1844 CVRQuals |= T.getCVRQualifiers(); 1845 Ty = T.getTypePtr(); 1846 } 1847 } 1848 1849 // If we have a simple case, just return now. 1850 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 1851 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) 1852 return ATy; 1853 1854 // Otherwise, we have an array and we have qualifiers on it. Push the 1855 // qualifiers into the array element type and return a new array type. 1856 // Get the canonical version of the element with the extra qualifiers on it. 1857 // This can recursively sink qualifiers through multiple levels of arrays. 1858 QualType NewEltTy = ATy->getElementType(); 1859 if (AddrSpace) 1860 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace); 1861 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); 1862 1863 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 1864 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 1865 CAT->getSizeModifier(), 1866 CAT->getIndexTypeQualifier())); 1867 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 1868 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 1869 IAT->getSizeModifier(), 1870 IAT->getIndexTypeQualifier())); 1871 1872 if (const DependentSizedArrayType *DSAT 1873 = dyn_cast<DependentSizedArrayType>(ATy)) 1874 return cast<ArrayType>( 1875 getDependentSizedArrayType(NewEltTy, 1876 DSAT->getSizeExpr(), 1877 DSAT->getSizeModifier(), 1878 DSAT->getIndexTypeQualifier())); 1879 1880 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 1881 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1882 VAT->getSizeModifier(), 1883 VAT->getIndexTypeQualifier())); 1884} 1885 1886 1887/// getArrayDecayedType - Return the properly qualified result of decaying the 1888/// specified array type to a pointer. This operation is non-trivial when 1889/// handling typedefs etc. The canonical type of "T" must be an array type, 1890/// this returns a pointer to a properly qualified element of the array. 1891/// 1892/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 1893QualType ASTContext::getArrayDecayedType(QualType Ty) { 1894 // Get the element type with 'getAsArrayType' so that we don't lose any 1895 // typedefs in the element type of the array. This also handles propagation 1896 // of type qualifiers from the array type into the element type if present 1897 // (C99 6.7.3p8). 1898 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 1899 assert(PrettyArrayType && "Not an array type!"); 1900 1901 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 1902 1903 // int x[restrict 4] -> int *restrict 1904 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier()); 1905} 1906 1907QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) { 1908 QualType ElemTy = VAT->getElementType(); 1909 1910 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy)) 1911 return getBaseElementType(VAT); 1912 1913 return ElemTy; 1914} 1915 1916/// getFloatingRank - Return a relative rank for floating point types. 1917/// This routine will assert if passed a built-in type that isn't a float. 1918static FloatingRank getFloatingRank(QualType T) { 1919 if (const ComplexType *CT = T->getAsComplexType()) 1920 return getFloatingRank(CT->getElementType()); 1921 1922 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type"); 1923 switch (T->getAsBuiltinType()->getKind()) { 1924 default: assert(0 && "getFloatingRank(): not a floating type"); 1925 case BuiltinType::Float: return FloatRank; 1926 case BuiltinType::Double: return DoubleRank; 1927 case BuiltinType::LongDouble: return LongDoubleRank; 1928 } 1929} 1930 1931/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 1932/// point or a complex type (based on typeDomain/typeSize). 1933/// 'typeDomain' is a real floating point or complex type. 1934/// 'typeSize' is a real floating point or complex type. 1935QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 1936 QualType Domain) const { 1937 FloatingRank EltRank = getFloatingRank(Size); 1938 if (Domain->isComplexType()) { 1939 switch (EltRank) { 1940 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1941 case FloatRank: return FloatComplexTy; 1942 case DoubleRank: return DoubleComplexTy; 1943 case LongDoubleRank: return LongDoubleComplexTy; 1944 } 1945 } 1946 1947 assert(Domain->isRealFloatingType() && "Unknown domain!"); 1948 switch (EltRank) { 1949 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1950 case FloatRank: return FloatTy; 1951 case DoubleRank: return DoubleTy; 1952 case LongDoubleRank: return LongDoubleTy; 1953 } 1954} 1955 1956/// getFloatingTypeOrder - Compare the rank of the two specified floating 1957/// point types, ignoring the domain of the type (i.e. 'double' == 1958/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 1959/// LHS < RHS, return -1. 1960int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 1961 FloatingRank LHSR = getFloatingRank(LHS); 1962 FloatingRank RHSR = getFloatingRank(RHS); 1963 1964 if (LHSR == RHSR) 1965 return 0; 1966 if (LHSR > RHSR) 1967 return 1; 1968 return -1; 1969} 1970 1971/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 1972/// routine will assert if passed a built-in type that isn't an integer or enum, 1973/// or if it is not canonicalized. 1974unsigned ASTContext::getIntegerRank(Type *T) { 1975 assert(T->isCanonical() && "T should be canonicalized"); 1976 if (EnumType* ET = dyn_cast<EnumType>(T)) 1977 T = ET->getDecl()->getIntegerType().getTypePtr(); 1978 1979 // There are two things which impact the integer rank: the width, and 1980 // the ordering of builtins. The builtin ordering is encoded in the 1981 // bottom three bits; the width is encoded in the bits above that. 1982 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 1983 return FWIT->getWidth() << 3; 1984 } 1985 1986 switch (cast<BuiltinType>(T)->getKind()) { 1987 default: assert(0 && "getIntegerRank(): not a built-in integer"); 1988 case BuiltinType::Bool: 1989 return 1 + (getIntWidth(BoolTy) << 3); 1990 case BuiltinType::Char_S: 1991 case BuiltinType::Char_U: 1992 case BuiltinType::SChar: 1993 case BuiltinType::UChar: 1994 return 2 + (getIntWidth(CharTy) << 3); 1995 case BuiltinType::Short: 1996 case BuiltinType::UShort: 1997 return 3 + (getIntWidth(ShortTy) << 3); 1998 case BuiltinType::Int: 1999 case BuiltinType::UInt: 2000 return 4 + (getIntWidth(IntTy) << 3); 2001 case BuiltinType::Long: 2002 case BuiltinType::ULong: 2003 return 5 + (getIntWidth(LongTy) << 3); 2004 case BuiltinType::LongLong: 2005 case BuiltinType::ULongLong: 2006 return 6 + (getIntWidth(LongLongTy) << 3); 2007 case BuiltinType::Int128: 2008 case BuiltinType::UInt128: 2009 return 7 + (getIntWidth(Int128Ty) << 3); 2010 } 2011} 2012 2013/// getIntegerTypeOrder - Returns the highest ranked integer type: 2014/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 2015/// LHS < RHS, return -1. 2016int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 2017 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 2018 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 2019 if (LHSC == RHSC) return 0; 2020 2021 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 2022 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 2023 2024 unsigned LHSRank = getIntegerRank(LHSC); 2025 unsigned RHSRank = getIntegerRank(RHSC); 2026 2027 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 2028 if (LHSRank == RHSRank) return 0; 2029 return LHSRank > RHSRank ? 1 : -1; 2030 } 2031 2032 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 2033 if (LHSUnsigned) { 2034 // If the unsigned [LHS] type is larger, return it. 2035 if (LHSRank >= RHSRank) 2036 return 1; 2037 2038 // If the signed type can represent all values of the unsigned type, it 2039 // wins. Because we are dealing with 2's complement and types that are 2040 // powers of two larger than each other, this is always safe. 2041 return -1; 2042 } 2043 2044 // If the unsigned [RHS] type is larger, return it. 2045 if (RHSRank >= LHSRank) 2046 return -1; 2047 2048 // If the signed type can represent all values of the unsigned type, it 2049 // wins. Because we are dealing with 2's complement and types that are 2050 // powers of two larger than each other, this is always safe. 2051 return 1; 2052} 2053 2054// getCFConstantStringType - Return the type used for constant CFStrings. 2055QualType ASTContext::getCFConstantStringType() { 2056 if (!CFConstantStringTypeDecl) { 2057 CFConstantStringTypeDecl = 2058 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2059 &Idents.get("NSConstantString")); 2060 QualType FieldTypes[4]; 2061 2062 // const int *isa; 2063 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); 2064 // int flags; 2065 FieldTypes[1] = IntTy; 2066 // const char *str; 2067 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); 2068 // long length; 2069 FieldTypes[3] = LongTy; 2070 2071 // Create fields 2072 for (unsigned i = 0; i < 4; ++i) { 2073 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 2074 SourceLocation(), 0, 2075 FieldTypes[i], /*BitWidth=*/0, 2076 /*Mutable=*/false); 2077 CFConstantStringTypeDecl->addDecl(*this, Field); 2078 } 2079 2080 CFConstantStringTypeDecl->completeDefinition(*this); 2081 } 2082 2083 return getTagDeclType(CFConstantStringTypeDecl); 2084} 2085 2086void ASTContext::setCFConstantStringType(QualType T) { 2087 const RecordType *Rec = T->getAsRecordType(); 2088 assert(Rec && "Invalid CFConstantStringType"); 2089 CFConstantStringTypeDecl = Rec->getDecl(); 2090} 2091 2092QualType ASTContext::getObjCFastEnumerationStateType() 2093{ 2094 if (!ObjCFastEnumerationStateTypeDecl) { 2095 ObjCFastEnumerationStateTypeDecl = 2096 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 2097 &Idents.get("__objcFastEnumerationState")); 2098 2099 QualType FieldTypes[] = { 2100 UnsignedLongTy, 2101 getPointerType(ObjCIdType), 2102 getPointerType(UnsignedLongTy), 2103 getConstantArrayType(UnsignedLongTy, 2104 llvm::APInt(32, 5), ArrayType::Normal, 0) 2105 }; 2106 2107 for (size_t i = 0; i < 4; ++i) { 2108 FieldDecl *Field = FieldDecl::Create(*this, 2109 ObjCFastEnumerationStateTypeDecl, 2110 SourceLocation(), 0, 2111 FieldTypes[i], /*BitWidth=*/0, 2112 /*Mutable=*/false); 2113 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field); 2114 } 2115 2116 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this); 2117 } 2118 2119 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 2120} 2121 2122void ASTContext::setObjCFastEnumerationStateType(QualType T) { 2123 const RecordType *Rec = T->getAsRecordType(); 2124 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 2125 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 2126} 2127 2128// This returns true if a type has been typedefed to BOOL: 2129// typedef <type> BOOL; 2130static bool isTypeTypedefedAsBOOL(QualType T) { 2131 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 2132 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 2133 return II->isStr("BOOL"); 2134 2135 return false; 2136} 2137 2138/// getObjCEncodingTypeSize returns size of type for objective-c encoding 2139/// purpose. 2140int ASTContext::getObjCEncodingTypeSize(QualType type) { 2141 uint64_t sz = getTypeSize(type); 2142 2143 // Make all integer and enum types at least as large as an int 2144 if (sz > 0 && type->isIntegralType()) 2145 sz = std::max(sz, getTypeSize(IntTy)); 2146 // Treat arrays as pointers, since that's how they're passed in. 2147 else if (type->isArrayType()) 2148 sz = getTypeSize(VoidPtrTy); 2149 return sz / getTypeSize(CharTy); 2150} 2151 2152/// getObjCEncodingForMethodDecl - Return the encoded type for this method 2153/// declaration. 2154void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 2155 std::string& S) { 2156 // FIXME: This is not very efficient. 2157 // Encode type qualifer, 'in', 'inout', etc. for the return type. 2158 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 2159 // Encode result type. 2160 getObjCEncodingForType(Decl->getResultType(), S); 2161 // Compute size of all parameters. 2162 // Start with computing size of a pointer in number of bytes. 2163 // FIXME: There might(should) be a better way of doing this computation! 2164 SourceLocation Loc; 2165 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy); 2166 // The first two arguments (self and _cmd) are pointers; account for 2167 // their size. 2168 int ParmOffset = 2 * PtrSize; 2169 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2170 E = Decl->param_end(); PI != E; ++PI) { 2171 QualType PType = (*PI)->getType(); 2172 int sz = getObjCEncodingTypeSize(PType); 2173 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type"); 2174 ParmOffset += sz; 2175 } 2176 S += llvm::utostr(ParmOffset); 2177 S += "@0:"; 2178 S += llvm::utostr(PtrSize); 2179 2180 // Argument types. 2181 ParmOffset = 2 * PtrSize; 2182 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 2183 E = Decl->param_end(); PI != E; ++PI) { 2184 ParmVarDecl *PVDecl = *PI; 2185 QualType PType = PVDecl->getOriginalType(); 2186 if (const ArrayType *AT = 2187 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 2188 // Use array's original type only if it has known number of 2189 // elements. 2190 if (!isa<ConstantArrayType>(AT)) 2191 PType = PVDecl->getType(); 2192 } else if (PType->isFunctionType()) 2193 PType = PVDecl->getType(); 2194 // Process argument qualifiers for user supplied arguments; such as, 2195 // 'in', 'inout', etc. 2196 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 2197 getObjCEncodingForType(PType, S); 2198 S += llvm::utostr(ParmOffset); 2199 ParmOffset += getObjCEncodingTypeSize(PType); 2200 } 2201} 2202 2203/// getObjCEncodingForPropertyDecl - Return the encoded type for this 2204/// property declaration. If non-NULL, Container must be either an 2205/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 2206/// NULL when getting encodings for protocol properties. 2207/// Property attributes are stored as a comma-delimited C string. The simple 2208/// attributes readonly and bycopy are encoded as single characters. The 2209/// parametrized attributes, getter=name, setter=name, and ivar=name, are 2210/// encoded as single characters, followed by an identifier. Property types 2211/// are also encoded as a parametrized attribute. The characters used to encode 2212/// these attributes are defined by the following enumeration: 2213/// @code 2214/// enum PropertyAttributes { 2215/// kPropertyReadOnly = 'R', // property is read-only. 2216/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 2217/// kPropertyByref = '&', // property is a reference to the value last assigned 2218/// kPropertyDynamic = 'D', // property is dynamic 2219/// kPropertyGetter = 'G', // followed by getter selector name 2220/// kPropertySetter = 'S', // followed by setter selector name 2221/// kPropertyInstanceVariable = 'V' // followed by instance variable name 2222/// kPropertyType = 't' // followed by old-style type encoding. 2223/// kPropertyWeak = 'W' // 'weak' property 2224/// kPropertyStrong = 'P' // property GC'able 2225/// kPropertyNonAtomic = 'N' // property non-atomic 2226/// }; 2227/// @endcode 2228void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 2229 const Decl *Container, 2230 std::string& S) { 2231 // Collect information from the property implementation decl(s). 2232 bool Dynamic = false; 2233 ObjCPropertyImplDecl *SynthesizePID = 0; 2234 2235 // FIXME: Duplicated code due to poor abstraction. 2236 if (Container) { 2237 if (const ObjCCategoryImplDecl *CID = 2238 dyn_cast<ObjCCategoryImplDecl>(Container)) { 2239 for (ObjCCategoryImplDecl::propimpl_iterator 2240 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this); 2241 i != e; ++i) { 2242 ObjCPropertyImplDecl *PID = *i; 2243 if (PID->getPropertyDecl() == PD) { 2244 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2245 Dynamic = true; 2246 } else { 2247 SynthesizePID = PID; 2248 } 2249 } 2250 } 2251 } else { 2252 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 2253 for (ObjCCategoryImplDecl::propimpl_iterator 2254 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this); 2255 i != e; ++i) { 2256 ObjCPropertyImplDecl *PID = *i; 2257 if (PID->getPropertyDecl() == PD) { 2258 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 2259 Dynamic = true; 2260 } else { 2261 SynthesizePID = PID; 2262 } 2263 } 2264 } 2265 } 2266 } 2267 2268 // FIXME: This is not very efficient. 2269 S = "T"; 2270 2271 // Encode result type. 2272 // GCC has some special rules regarding encoding of properties which 2273 // closely resembles encoding of ivars. 2274 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 2275 true /* outermost type */, 2276 true /* encoding for property */); 2277 2278 if (PD->isReadOnly()) { 2279 S += ",R"; 2280 } else { 2281 switch (PD->getSetterKind()) { 2282 case ObjCPropertyDecl::Assign: break; 2283 case ObjCPropertyDecl::Copy: S += ",C"; break; 2284 case ObjCPropertyDecl::Retain: S += ",&"; break; 2285 } 2286 } 2287 2288 // It really isn't clear at all what this means, since properties 2289 // are "dynamic by default". 2290 if (Dynamic) 2291 S += ",D"; 2292 2293 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 2294 S += ",N"; 2295 2296 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 2297 S += ",G"; 2298 S += PD->getGetterName().getAsString(); 2299 } 2300 2301 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 2302 S += ",S"; 2303 S += PD->getSetterName().getAsString(); 2304 } 2305 2306 if (SynthesizePID) { 2307 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 2308 S += ",V"; 2309 S += OID->getNameAsString(); 2310 } 2311 2312 // FIXME: OBJCGC: weak & strong 2313} 2314 2315/// getLegacyIntegralTypeEncoding - 2316/// Another legacy compatibility encoding: 32-bit longs are encoded as 2317/// 'l' or 'L' , but not always. For typedefs, we need to use 2318/// 'i' or 'I' instead if encoding a struct field, or a pointer! 2319/// 2320void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 2321 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) { 2322 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) { 2323 if (BT->getKind() == BuiltinType::ULong && 2324 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2325 PointeeTy = UnsignedIntTy; 2326 else 2327 if (BT->getKind() == BuiltinType::Long && 2328 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 2329 PointeeTy = IntTy; 2330 } 2331 } 2332} 2333 2334void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 2335 const FieldDecl *Field) { 2336 // We follow the behavior of gcc, expanding structures which are 2337 // directly pointed to, and expanding embedded structures. Note that 2338 // these rules are sufficient to prevent recursive encoding of the 2339 // same type. 2340 getObjCEncodingForTypeImpl(T, S, true, true, Field, 2341 true /* outermost type */); 2342} 2343 2344static void EncodeBitField(const ASTContext *Context, std::string& S, 2345 const FieldDecl *FD) { 2346 const Expr *E = FD->getBitWidth(); 2347 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 2348 ASTContext *Ctx = const_cast<ASTContext*>(Context); 2349 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 2350 S += 'b'; 2351 S += llvm::utostr(N); 2352} 2353 2354void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 2355 bool ExpandPointedToStructures, 2356 bool ExpandStructures, 2357 const FieldDecl *FD, 2358 bool OutermostType, 2359 bool EncodingProperty) { 2360 if (const BuiltinType *BT = T->getAsBuiltinType()) { 2361 if (FD && FD->isBitField()) { 2362 EncodeBitField(this, S, FD); 2363 } 2364 else { 2365 char encoding; 2366 switch (BT->getKind()) { 2367 default: assert(0 && "Unhandled builtin type kind"); 2368 case BuiltinType::Void: encoding = 'v'; break; 2369 case BuiltinType::Bool: encoding = 'B'; break; 2370 case BuiltinType::Char_U: 2371 case BuiltinType::UChar: encoding = 'C'; break; 2372 case BuiltinType::UShort: encoding = 'S'; break; 2373 case BuiltinType::UInt: encoding = 'I'; break; 2374 case BuiltinType::ULong: 2375 encoding = 2376 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; 2377 break; 2378 case BuiltinType::UInt128: encoding = 'T'; break; 2379 case BuiltinType::ULongLong: encoding = 'Q'; break; 2380 case BuiltinType::Char_S: 2381 case BuiltinType::SChar: encoding = 'c'; break; 2382 case BuiltinType::Short: encoding = 's'; break; 2383 case BuiltinType::Int: encoding = 'i'; break; 2384 case BuiltinType::Long: 2385 encoding = 2386 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q'; 2387 break; 2388 case BuiltinType::LongLong: encoding = 'q'; break; 2389 case BuiltinType::Int128: encoding = 't'; break; 2390 case BuiltinType::Float: encoding = 'f'; break; 2391 case BuiltinType::Double: encoding = 'd'; break; 2392 case BuiltinType::LongDouble: encoding = 'd'; break; 2393 } 2394 2395 S += encoding; 2396 } 2397 } else if (const ComplexType *CT = T->getAsComplexType()) { 2398 S += 'j'; 2399 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 2400 false); 2401 } else if (T->isObjCQualifiedIdType()) { 2402 getObjCEncodingForTypeImpl(getObjCIdType(), S, 2403 ExpandPointedToStructures, 2404 ExpandStructures, FD); 2405 if (FD || EncodingProperty) { 2406 // Note that we do extended encoding of protocol qualifer list 2407 // Only when doing ivar or property encoding. 2408 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType(); 2409 S += '"'; 2410 for (ObjCQualifiedIdType::qual_iterator I = QIDT->qual_begin(), 2411 E = QIDT->qual_end(); I != E; ++I) { 2412 S += '<'; 2413 S += (*I)->getNameAsString(); 2414 S += '>'; 2415 } 2416 S += '"'; 2417 } 2418 return; 2419 } 2420 else if (const PointerType *PT = T->getAsPointerType()) { 2421 QualType PointeeTy = PT->getPointeeType(); 2422 bool isReadOnly = false; 2423 // For historical/compatibility reasons, the read-only qualifier of the 2424 // pointee gets emitted _before_ the '^'. The read-only qualifier of 2425 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 2426 // Also, do not emit the 'r' for anything but the outermost type! 2427 if (dyn_cast<TypedefType>(T.getTypePtr())) { 2428 if (OutermostType && T.isConstQualified()) { 2429 isReadOnly = true; 2430 S += 'r'; 2431 } 2432 } 2433 else if (OutermostType) { 2434 QualType P = PointeeTy; 2435 while (P->getAsPointerType()) 2436 P = P->getAsPointerType()->getPointeeType(); 2437 if (P.isConstQualified()) { 2438 isReadOnly = true; 2439 S += 'r'; 2440 } 2441 } 2442 if (isReadOnly) { 2443 // Another legacy compatibility encoding. Some ObjC qualifier and type 2444 // combinations need to be rearranged. 2445 // Rewrite "in const" from "nr" to "rn" 2446 const char * s = S.c_str(); 2447 int len = S.length(); 2448 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') { 2449 std::string replace = "rn"; 2450 S.replace(S.end()-2, S.end(), replace); 2451 } 2452 } 2453 if (isObjCIdStructType(PointeeTy)) { 2454 S += '@'; 2455 return; 2456 } 2457 else if (PointeeTy->isObjCInterfaceType()) { 2458 if (!EncodingProperty && 2459 isa<TypedefType>(PointeeTy.getTypePtr())) { 2460 // Another historical/compatibility reason. 2461 // We encode the underlying type which comes out as 2462 // {...}; 2463 S += '^'; 2464 getObjCEncodingForTypeImpl(PointeeTy, S, 2465 false, ExpandPointedToStructures, 2466 NULL); 2467 return; 2468 } 2469 S += '@'; 2470 if (FD || EncodingProperty) { 2471 const ObjCInterfaceType *OIT = 2472 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType(); 2473 ObjCInterfaceDecl *OI = OIT->getDecl(); 2474 S += '"'; 2475 S += OI->getNameAsCString(); 2476 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(), 2477 E = OIT->qual_end(); I != E; ++I) { 2478 S += '<'; 2479 S += (*I)->getNameAsString(); 2480 S += '>'; 2481 } 2482 S += '"'; 2483 } 2484 return; 2485 } else if (isObjCClassStructType(PointeeTy)) { 2486 S += '#'; 2487 return; 2488 } else if (isObjCSelType(PointeeTy)) { 2489 S += ':'; 2490 return; 2491 } 2492 2493 if (PointeeTy->isCharType()) { 2494 // char pointer types should be encoded as '*' unless it is a 2495 // type that has been typedef'd to 'BOOL'. 2496 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 2497 S += '*'; 2498 return; 2499 } 2500 } 2501 2502 S += '^'; 2503 getLegacyIntegralTypeEncoding(PointeeTy); 2504 2505 getObjCEncodingForTypeImpl(PointeeTy, S, 2506 false, ExpandPointedToStructures, 2507 NULL); 2508 } else if (const ArrayType *AT = 2509 // Ignore type qualifiers etc. 2510 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 2511 if (isa<IncompleteArrayType>(AT)) { 2512 // Incomplete arrays are encoded as a pointer to the array element. 2513 S += '^'; 2514 2515 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2516 false, ExpandStructures, FD); 2517 } else { 2518 S += '['; 2519 2520 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2521 S += llvm::utostr(CAT->getSize().getZExtValue()); 2522 else { 2523 //Variable length arrays are encoded as a regular array with 0 elements. 2524 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 2525 S += '0'; 2526 } 2527 2528 getObjCEncodingForTypeImpl(AT->getElementType(), S, 2529 false, ExpandStructures, FD); 2530 S += ']'; 2531 } 2532 } else if (T->getAsFunctionType()) { 2533 S += '?'; 2534 } else if (const RecordType *RTy = T->getAsRecordType()) { 2535 RecordDecl *RDecl = RTy->getDecl(); 2536 S += RDecl->isUnion() ? '(' : '{'; 2537 // Anonymous structures print as '?' 2538 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 2539 S += II->getName(); 2540 } else { 2541 S += '?'; 2542 } 2543 if (ExpandStructures) { 2544 S += '='; 2545 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this), 2546 FieldEnd = RDecl->field_end(*this); 2547 Field != FieldEnd; ++Field) { 2548 if (FD) { 2549 S += '"'; 2550 S += Field->getNameAsString(); 2551 S += '"'; 2552 } 2553 2554 // Special case bit-fields. 2555 if (Field->isBitField()) { 2556 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 2557 (*Field)); 2558 } else { 2559 QualType qt = Field->getType(); 2560 getLegacyIntegralTypeEncoding(qt); 2561 getObjCEncodingForTypeImpl(qt, S, false, true, 2562 FD); 2563 } 2564 } 2565 } 2566 S += RDecl->isUnion() ? ')' : '}'; 2567 } else if (T->isEnumeralType()) { 2568 if (FD && FD->isBitField()) 2569 EncodeBitField(this, S, FD); 2570 else 2571 S += 'i'; 2572 } else if (T->isBlockPointerType()) { 2573 S += "@?"; // Unlike a pointer-to-function, which is "^?". 2574 } else if (T->isObjCInterfaceType()) { 2575 // @encode(class_name) 2576 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl(); 2577 S += '{'; 2578 const IdentifierInfo *II = OI->getIdentifier(); 2579 S += II->getName(); 2580 S += '='; 2581 llvm::SmallVector<FieldDecl*, 32> RecFields; 2582 CollectObjCIvars(OI, RecFields); 2583 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2584 if (RecFields[i]->isBitField()) 2585 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2586 RecFields[i]); 2587 else 2588 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 2589 FD); 2590 } 2591 S += '}'; 2592 } 2593 else 2594 assert(0 && "@encode for type not implemented!"); 2595} 2596 2597void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 2598 std::string& S) const { 2599 if (QT & Decl::OBJC_TQ_In) 2600 S += 'n'; 2601 if (QT & Decl::OBJC_TQ_Inout) 2602 S += 'N'; 2603 if (QT & Decl::OBJC_TQ_Out) 2604 S += 'o'; 2605 if (QT & Decl::OBJC_TQ_Bycopy) 2606 S += 'O'; 2607 if (QT & Decl::OBJC_TQ_Byref) 2608 S += 'R'; 2609 if (QT & Decl::OBJC_TQ_Oneway) 2610 S += 'V'; 2611} 2612 2613void ASTContext::setBuiltinVaListType(QualType T) 2614{ 2615 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 2616 2617 BuiltinVaListType = T; 2618} 2619 2620void ASTContext::setObjCIdType(QualType T) 2621{ 2622 ObjCIdType = T; 2623 2624 const TypedefType *TT = T->getAsTypedefType(); 2625 if (!TT) 2626 return; 2627 2628 TypedefDecl *TD = TT->getDecl(); 2629 2630 // typedef struct objc_object *id; 2631 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2632 // User error - caller will issue diagnostics. 2633 if (!ptr) 2634 return; 2635 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2636 // User error - caller will issue diagnostics. 2637 if (!rec) 2638 return; 2639 IdStructType = rec; 2640} 2641 2642void ASTContext::setObjCSelType(QualType T) 2643{ 2644 ObjCSelType = T; 2645 2646 const TypedefType *TT = T->getAsTypedefType(); 2647 if (!TT) 2648 return; 2649 TypedefDecl *TD = TT->getDecl(); 2650 2651 // typedef struct objc_selector *SEL; 2652 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2653 if (!ptr) 2654 return; 2655 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2656 if (!rec) 2657 return; 2658 SelStructType = rec; 2659} 2660 2661void ASTContext::setObjCProtoType(QualType QT) 2662{ 2663 ObjCProtoType = QT; 2664} 2665 2666void ASTContext::setObjCClassType(QualType T) 2667{ 2668 ObjCClassType = T; 2669 2670 const TypedefType *TT = T->getAsTypedefType(); 2671 if (!TT) 2672 return; 2673 TypedefDecl *TD = TT->getDecl(); 2674 2675 // typedef struct objc_class *Class; 2676 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 2677 assert(ptr && "'Class' incorrectly typed"); 2678 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 2679 assert(rec && "'Class' incorrectly typed"); 2680 ClassStructType = rec; 2681} 2682 2683void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 2684 assert(ObjCConstantStringType.isNull() && 2685 "'NSConstantString' type already set!"); 2686 2687 ObjCConstantStringType = getObjCInterfaceType(Decl); 2688} 2689 2690/// \brief Retrieve the template name that represents a qualified 2691/// template name such as \c std::vector. 2692TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 2693 bool TemplateKeyword, 2694 TemplateDecl *Template) { 2695 llvm::FoldingSetNodeID ID; 2696 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 2697 2698 void *InsertPos = 0; 2699 QualifiedTemplateName *QTN = 2700 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2701 if (!QTN) { 2702 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 2703 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 2704 } 2705 2706 return TemplateName(QTN); 2707} 2708 2709/// \brief Retrieve the template name that represents a dependent 2710/// template name such as \c MetaFun::template apply. 2711TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 2712 const IdentifierInfo *Name) { 2713 assert(NNS->isDependent() && "Nested name specifier must be dependent"); 2714 2715 llvm::FoldingSetNodeID ID; 2716 DependentTemplateName::Profile(ID, NNS, Name); 2717 2718 void *InsertPos = 0; 2719 DependentTemplateName *QTN = 2720 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 2721 2722 if (QTN) 2723 return TemplateName(QTN); 2724 2725 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2726 if (CanonNNS == NNS) { 2727 QTN = new (*this,4) DependentTemplateName(NNS, Name); 2728 } else { 2729 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 2730 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 2731 } 2732 2733 DependentTemplateNames.InsertNode(QTN, InsertPos); 2734 return TemplateName(QTN); 2735} 2736 2737/// getFromTargetType - Given one of the integer types provided by 2738/// TargetInfo, produce the corresponding type. The unsigned @p Type 2739/// is actually a value of type @c TargetInfo::IntType. 2740QualType ASTContext::getFromTargetType(unsigned Type) const { 2741 switch (Type) { 2742 case TargetInfo::NoInt: return QualType(); 2743 case TargetInfo::SignedShort: return ShortTy; 2744 case TargetInfo::UnsignedShort: return UnsignedShortTy; 2745 case TargetInfo::SignedInt: return IntTy; 2746 case TargetInfo::UnsignedInt: return UnsignedIntTy; 2747 case TargetInfo::SignedLong: return LongTy; 2748 case TargetInfo::UnsignedLong: return UnsignedLongTy; 2749 case TargetInfo::SignedLongLong: return LongLongTy; 2750 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 2751 } 2752 2753 assert(false && "Unhandled TargetInfo::IntType value"); 2754 return QualType(); 2755} 2756 2757//===----------------------------------------------------------------------===// 2758// Type Predicates. 2759//===----------------------------------------------------------------------===// 2760 2761/// isObjCNSObjectType - Return true if this is an NSObject object using 2762/// NSObject attribute on a c-style pointer type. 2763/// FIXME - Make it work directly on types. 2764/// 2765bool ASTContext::isObjCNSObjectType(QualType Ty) const { 2766 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 2767 if (TypedefDecl *TD = TDT->getDecl()) 2768 if (TD->getAttr<ObjCNSObjectAttr>()) 2769 return true; 2770 } 2771 return false; 2772} 2773 2774/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 2775/// to an object type. This includes "id" and "Class" (two 'special' pointers 2776/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 2777/// ID type). 2778bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 2779 if (Ty->isObjCQualifiedIdType()) 2780 return true; 2781 2782 // Blocks are objects. 2783 if (Ty->isBlockPointerType()) 2784 return true; 2785 2786 // All other object types are pointers. 2787 const PointerType *PT = Ty->getAsPointerType(); 2788 if (PT == 0) 2789 return false; 2790 2791 // If this a pointer to an interface (e.g. NSString*), it is ok. 2792 if (PT->getPointeeType()->isObjCInterfaceType() || 2793 // If is has NSObject attribute, OK as well. 2794 isObjCNSObjectType(Ty)) 2795 return true; 2796 2797 // Check to see if this is 'id' or 'Class', both of which are typedefs for 2798 // pointer types. This looks for the typedef specifically, not for the 2799 // underlying type. Iteratively strip off typedefs so that we can handle 2800 // typedefs of typedefs. 2801 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 2802 if (Ty.getUnqualifiedType() == getObjCIdType() || 2803 Ty.getUnqualifiedType() == getObjCClassType()) 2804 return true; 2805 2806 Ty = TDT->getDecl()->getUnderlyingType(); 2807 } 2808 2809 return false; 2810} 2811 2812/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 2813/// garbage collection attribute. 2814/// 2815QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 2816 QualType::GCAttrTypes GCAttrs = QualType::GCNone; 2817 if (getLangOptions().ObjC1 && 2818 getLangOptions().getGCMode() != LangOptions::NonGC) { 2819 GCAttrs = Ty.getObjCGCAttr(); 2820 // Default behavious under objective-c's gc is for objective-c pointers 2821 // (or pointers to them) be treated as though they were declared 2822 // as __strong. 2823 if (GCAttrs == QualType::GCNone) { 2824 if (isObjCObjectPointerType(Ty)) 2825 GCAttrs = QualType::Strong; 2826 else if (Ty->isPointerType()) 2827 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType()); 2828 } 2829 // Non-pointers have none gc'able attribute regardless of the attribute 2830 // set on them. 2831 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty)) 2832 return QualType::GCNone; 2833 } 2834 return GCAttrs; 2835} 2836 2837//===----------------------------------------------------------------------===// 2838// Type Compatibility Testing 2839//===----------------------------------------------------------------------===// 2840 2841/// typesAreBlockCompatible - This routine is called when comparing two 2842/// block types. Types must be strictly compatible here. For example, 2843/// C unfortunately doesn't produce an error for the following: 2844/// 2845/// int (*emptyArgFunc)(); 2846/// int (*intArgList)(int) = emptyArgFunc; 2847/// 2848/// For blocks, we will produce an error for the following (similar to C++): 2849/// 2850/// int (^emptyArgBlock)(); 2851/// int (^intArgBlock)(int) = emptyArgBlock; 2852/// 2853/// FIXME: When the dust settles on this integration, fold this into mergeTypes. 2854/// 2855bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) { 2856 return !mergeTypes(lhs, rhs).isNull(); 2857} 2858 2859/// areCompatVectorTypes - Return true if the two specified vector types are 2860/// compatible. 2861static bool areCompatVectorTypes(const VectorType *LHS, 2862 const VectorType *RHS) { 2863 assert(LHS->isCanonical() && RHS->isCanonical()); 2864 return LHS->getElementType() == RHS->getElementType() && 2865 LHS->getNumElements() == RHS->getNumElements(); 2866} 2867 2868/// canAssignObjCInterfaces - Return true if the two interface types are 2869/// compatible for assignment from RHS to LHS. This handles validation of any 2870/// protocol qualifiers on the LHS or RHS. 2871/// 2872bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 2873 const ObjCInterfaceType *RHS) { 2874 // Verify that the base decls are compatible: the RHS must be a subclass of 2875 // the LHS. 2876 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 2877 return false; 2878 2879 // RHS must have a superset of the protocols in the LHS. If the LHS is not 2880 // protocol qualified at all, then we are good. 2881 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 2882 return true; 2883 2884 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 2885 // isn't a superset. 2886 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 2887 return true; // FIXME: should return false! 2888 2889 // Finally, we must have two protocol-qualified interfaces. 2890 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 2891 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 2892 2893 // All LHS protocols must have a presence on the RHS. 2894 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?"); 2895 2896 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(), 2897 LHSPE = LHSP->qual_end(); 2898 LHSPI != LHSPE; LHSPI++) { 2899 bool RHSImplementsProtocol = false; 2900 2901 // If the RHS doesn't implement the protocol on the left, the types 2902 // are incompatible. 2903 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(), 2904 RHSPE = RHSP->qual_end(); 2905 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) { 2906 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) 2907 RHSImplementsProtocol = true; 2908 } 2909 // FIXME: For better diagnostics, consider passing back the protocol name. 2910 if (!RHSImplementsProtocol) 2911 return false; 2912 } 2913 // The RHS implements all protocols listed on the LHS. 2914 return true; 2915} 2916 2917bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 2918 // get the "pointed to" types 2919 const PointerType *LHSPT = LHS->getAsPointerType(); 2920 const PointerType *RHSPT = RHS->getAsPointerType(); 2921 2922 if (!LHSPT || !RHSPT) 2923 return false; 2924 2925 QualType lhptee = LHSPT->getPointeeType(); 2926 QualType rhptee = RHSPT->getPointeeType(); 2927 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2928 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2929 // ID acts sort of like void* for ObjC interfaces 2930 if (LHSIface && isObjCIdStructType(rhptee)) 2931 return true; 2932 if (RHSIface && isObjCIdStructType(lhptee)) 2933 return true; 2934 if (!LHSIface || !RHSIface) 2935 return false; 2936 return canAssignObjCInterfaces(LHSIface, RHSIface) || 2937 canAssignObjCInterfaces(RHSIface, LHSIface); 2938} 2939 2940/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 2941/// both shall have the identically qualified version of a compatible type. 2942/// C99 6.2.7p1: Two types have compatible types if their types are the 2943/// same. See 6.7.[2,3,5] for additional rules. 2944bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 2945 return !mergeTypes(LHS, RHS).isNull(); 2946} 2947 2948QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { 2949 const FunctionType *lbase = lhs->getAsFunctionType(); 2950 const FunctionType *rbase = rhs->getAsFunctionType(); 2951 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 2952 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 2953 bool allLTypes = true; 2954 bool allRTypes = true; 2955 2956 // Check return type 2957 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 2958 if (retType.isNull()) return QualType(); 2959 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 2960 allLTypes = false; 2961 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 2962 allRTypes = false; 2963 2964 if (lproto && rproto) { // two C99 style function prototypes 2965 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 2966 "C++ shouldn't be here"); 2967 unsigned lproto_nargs = lproto->getNumArgs(); 2968 unsigned rproto_nargs = rproto->getNumArgs(); 2969 2970 // Compatible functions must have the same number of arguments 2971 if (lproto_nargs != rproto_nargs) 2972 return QualType(); 2973 2974 // Variadic and non-variadic functions aren't compatible 2975 if (lproto->isVariadic() != rproto->isVariadic()) 2976 return QualType(); 2977 2978 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 2979 return QualType(); 2980 2981 // Check argument compatibility 2982 llvm::SmallVector<QualType, 10> types; 2983 for (unsigned i = 0; i < lproto_nargs; i++) { 2984 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 2985 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 2986 QualType argtype = mergeTypes(largtype, rargtype); 2987 if (argtype.isNull()) return QualType(); 2988 types.push_back(argtype); 2989 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 2990 allLTypes = false; 2991 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 2992 allRTypes = false; 2993 } 2994 if (allLTypes) return lhs; 2995 if (allRTypes) return rhs; 2996 return getFunctionType(retType, types.begin(), types.size(), 2997 lproto->isVariadic(), lproto->getTypeQuals()); 2998 } 2999 3000 if (lproto) allRTypes = false; 3001 if (rproto) allLTypes = false; 3002 3003 const FunctionProtoType *proto = lproto ? lproto : rproto; 3004 if (proto) { 3005 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 3006 if (proto->isVariadic()) return QualType(); 3007 // Check that the types are compatible with the types that 3008 // would result from default argument promotions (C99 6.7.5.3p15). 3009 // The only types actually affected are promotable integer 3010 // types and floats, which would be passed as a different 3011 // type depending on whether the prototype is visible. 3012 unsigned proto_nargs = proto->getNumArgs(); 3013 for (unsigned i = 0; i < proto_nargs; ++i) { 3014 QualType argTy = proto->getArgType(i); 3015 if (argTy->isPromotableIntegerType() || 3016 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 3017 return QualType(); 3018 } 3019 3020 if (allLTypes) return lhs; 3021 if (allRTypes) return rhs; 3022 return getFunctionType(retType, proto->arg_type_begin(), 3023 proto->getNumArgs(), lproto->isVariadic(), 3024 lproto->getTypeQuals()); 3025 } 3026 3027 if (allLTypes) return lhs; 3028 if (allRTypes) return rhs; 3029 return getFunctionNoProtoType(retType); 3030} 3031 3032QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { 3033 // C++ [expr]: If an expression initially has the type "reference to T", the 3034 // type is adjusted to "T" prior to any further analysis, the expression 3035 // designates the object or function denoted by the reference, and the 3036 // expression is an lvalue unless the reference is an rvalue reference and 3037 // the expression is a function call (possibly inside parentheses). 3038 // FIXME: C++ shouldn't be going through here! The rules are different 3039 // enough that they should be handled separately. 3040 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really* 3041 // shouldn't be going through here! 3042 if (const ReferenceType *RT = LHS->getAsReferenceType()) 3043 LHS = RT->getPointeeType(); 3044 if (const ReferenceType *RT = RHS->getAsReferenceType()) 3045 RHS = RT->getPointeeType(); 3046 3047 QualType LHSCan = getCanonicalType(LHS), 3048 RHSCan = getCanonicalType(RHS); 3049 3050 // If two types are identical, they are compatible. 3051 if (LHSCan == RHSCan) 3052 return LHS; 3053 3054 // If the qualifiers are different, the types aren't compatible 3055 // Note that we handle extended qualifiers later, in the 3056 // case for ExtQualType. 3057 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers()) 3058 return QualType(); 3059 3060 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 3061 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 3062 3063 // We want to consider the two function types to be the same for these 3064 // comparisons, just force one to the other. 3065 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 3066 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 3067 3068 // Strip off objc_gc attributes off the top level so they can be merged. 3069 // This is a complete mess, but the attribute itself doesn't make much sense. 3070 if (RHSClass == Type::ExtQual) { 3071 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr(); 3072 if (GCAttr != QualType::GCNone) { 3073 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr(); 3074 // __weak attribute must appear on both declarations. 3075 // __strong attribue is redundant if other decl is an objective-c 3076 // object pointer (or decorated with __strong attribute); otherwise 3077 // issue error. 3078 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) || 3079 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr && 3080 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) && 3081 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType()))) 3082 return QualType(); 3083 3084 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(), 3085 RHS.getCVRQualifiers()); 3086 QualType Result = mergeTypes(LHS, RHS); 3087 if (!Result.isNull()) { 3088 if (Result.getObjCGCAttr() == QualType::GCNone) 3089 Result = getObjCGCQualType(Result, GCAttr); 3090 else if (Result.getObjCGCAttr() != GCAttr) 3091 Result = QualType(); 3092 } 3093 return Result; 3094 } 3095 } 3096 if (LHSClass == Type::ExtQual) { 3097 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr(); 3098 if (GCAttr != QualType::GCNone) { 3099 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr(); 3100 // __weak attribute must appear on both declarations. __strong 3101 // __strong attribue is redundant if other decl is an objective-c 3102 // object pointer (or decorated with __strong attribute); otherwise 3103 // issue error. 3104 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) || 3105 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr && 3106 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) && 3107 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType()))) 3108 return QualType(); 3109 3110 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(), 3111 LHS.getCVRQualifiers()); 3112 QualType Result = mergeTypes(LHS, RHS); 3113 if (!Result.isNull()) { 3114 if (Result.getObjCGCAttr() == QualType::GCNone) 3115 Result = getObjCGCQualType(Result, GCAttr); 3116 else if (Result.getObjCGCAttr() != GCAttr) 3117 Result = QualType(); 3118 } 3119 return Result; 3120 } 3121 } 3122 3123 // Same as above for arrays 3124 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 3125 LHSClass = Type::ConstantArray; 3126 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 3127 RHSClass = Type::ConstantArray; 3128 3129 // Canonicalize ExtVector -> Vector. 3130 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 3131 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 3132 3133 // Consider qualified interfaces and interfaces the same. 3134 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 3135 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 3136 3137 // If the canonical type classes don't match. 3138 if (LHSClass != RHSClass) { 3139 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3140 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3141 3142 // 'id' and 'Class' act sort of like void* for ObjC interfaces 3143 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS))) 3144 return LHS; 3145 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS))) 3146 return RHS; 3147 3148 // ID is compatible with all qualified id types. 3149 if (LHS->isObjCQualifiedIdType()) { 3150 if (const PointerType *PT = RHS->getAsPointerType()) { 3151 QualType pType = PT->getPointeeType(); 3152 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3153 return LHS; 3154 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3155 // Unfortunately, this API is part of Sema (which we don't have access 3156 // to. Need to refactor. The following check is insufficient, since we 3157 // need to make sure the class implements the protocol. 3158 if (pType->isObjCInterfaceType()) 3159 return LHS; 3160 } 3161 } 3162 if (RHS->isObjCQualifiedIdType()) { 3163 if (const PointerType *PT = LHS->getAsPointerType()) { 3164 QualType pType = PT->getPointeeType(); 3165 if (isObjCIdStructType(pType) || isObjCClassStructType(pType)) 3166 return RHS; 3167 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true). 3168 // Unfortunately, this API is part of Sema (which we don't have access 3169 // to. Need to refactor. The following check is insufficient, since we 3170 // need to make sure the class implements the protocol. 3171 if (pType->isObjCInterfaceType()) 3172 return RHS; 3173 } 3174 } 3175 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 3176 // a signed integer type, or an unsigned integer type. 3177 if (const EnumType* ETy = LHS->getAsEnumType()) { 3178 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 3179 return RHS; 3180 } 3181 if (const EnumType* ETy = RHS->getAsEnumType()) { 3182 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 3183 return LHS; 3184 } 3185 3186 return QualType(); 3187 } 3188 3189 // The canonical type classes match. 3190 switch (LHSClass) { 3191#define TYPE(Class, Base) 3192#define ABSTRACT_TYPE(Class, Base) 3193#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3194#define DEPENDENT_TYPE(Class, Base) case Type::Class: 3195#include "clang/AST/TypeNodes.def" 3196 assert(false && "Non-canonical and dependent types shouldn't get here"); 3197 return QualType(); 3198 3199 case Type::LValueReference: 3200 case Type::RValueReference: 3201 case Type::MemberPointer: 3202 assert(false && "C++ should never be in mergeTypes"); 3203 return QualType(); 3204 3205 case Type::IncompleteArray: 3206 case Type::VariableArray: 3207 case Type::FunctionProto: 3208 case Type::ExtVector: 3209 case Type::ObjCQualifiedInterface: 3210 assert(false && "Types are eliminated above"); 3211 return QualType(); 3212 3213 case Type::Pointer: 3214 { 3215 // Merge two pointer types, while trying to preserve typedef info 3216 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType(); 3217 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType(); 3218 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3219 if (ResultType.isNull()) return QualType(); 3220 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3221 return LHS; 3222 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3223 return RHS; 3224 return getPointerType(ResultType); 3225 } 3226 case Type::BlockPointer: 3227 { 3228 // Merge two block pointer types, while trying to preserve typedef info 3229 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType(); 3230 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType(); 3231 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 3232 if (ResultType.isNull()) return QualType(); 3233 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 3234 return LHS; 3235 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 3236 return RHS; 3237 return getBlockPointerType(ResultType); 3238 } 3239 case Type::ConstantArray: 3240 { 3241 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 3242 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 3243 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 3244 return QualType(); 3245 3246 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 3247 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 3248 QualType ResultType = mergeTypes(LHSElem, RHSElem); 3249 if (ResultType.isNull()) return QualType(); 3250 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3251 return LHS; 3252 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3253 return RHS; 3254 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 3255 ArrayType::ArraySizeModifier(), 0); 3256 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 3257 ArrayType::ArraySizeModifier(), 0); 3258 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 3259 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 3260 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 3261 return LHS; 3262 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 3263 return RHS; 3264 if (LVAT) { 3265 // FIXME: This isn't correct! But tricky to implement because 3266 // the array's size has to be the size of LHS, but the type 3267 // has to be different. 3268 return LHS; 3269 } 3270 if (RVAT) { 3271 // FIXME: This isn't correct! But tricky to implement because 3272 // the array's size has to be the size of RHS, but the type 3273 // has to be different. 3274 return RHS; 3275 } 3276 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 3277 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 3278 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0); 3279 } 3280 case Type::FunctionNoProto: 3281 return mergeFunctionTypes(LHS, RHS); 3282 case Type::Record: 3283 case Type::Enum: 3284 // FIXME: Why are these compatible? 3285 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS; 3286 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS; 3287 return QualType(); 3288 case Type::Builtin: 3289 // Only exactly equal builtin types are compatible, which is tested above. 3290 return QualType(); 3291 case Type::Complex: 3292 // Distinct complex types are incompatible. 3293 return QualType(); 3294 case Type::Vector: 3295 // FIXME: The merged type should be an ExtVector! 3296 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType())) 3297 return LHS; 3298 return QualType(); 3299 case Type::ObjCInterface: { 3300 // Check if the interfaces are assignment compatible. 3301 // FIXME: This should be type compatibility, e.g. whether 3302 // "LHS x; RHS x;" at global scope is legal. 3303 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 3304 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 3305 if (LHSIface && RHSIface && 3306 canAssignObjCInterfaces(LHSIface, RHSIface)) 3307 return LHS; 3308 3309 return QualType(); 3310 } 3311 case Type::ObjCQualifiedId: 3312 // Distinct qualified id's are not compatible. 3313 return QualType(); 3314 case Type::FixedWidthInt: 3315 // Distinct fixed-width integers are not compatible. 3316 return QualType(); 3317 case Type::ExtQual: 3318 // FIXME: ExtQual types can be compatible even if they're not 3319 // identical! 3320 return QualType(); 3321 // First attempt at an implementation, but I'm not really sure it's 3322 // right... 3323#if 0 3324 ExtQualType* LQual = cast<ExtQualType>(LHSCan); 3325 ExtQualType* RQual = cast<ExtQualType>(RHSCan); 3326 if (LQual->getAddressSpace() != RQual->getAddressSpace() || 3327 LQual->getObjCGCAttr() != RQual->getObjCGCAttr()) 3328 return QualType(); 3329 QualType LHSBase, RHSBase, ResultType, ResCanUnqual; 3330 LHSBase = QualType(LQual->getBaseType(), 0); 3331 RHSBase = QualType(RQual->getBaseType(), 0); 3332 ResultType = mergeTypes(LHSBase, RHSBase); 3333 if (ResultType.isNull()) return QualType(); 3334 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType(); 3335 if (LHSCan.getUnqualifiedType() == ResCanUnqual) 3336 return LHS; 3337 if (RHSCan.getUnqualifiedType() == ResCanUnqual) 3338 return RHS; 3339 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace()); 3340 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr()); 3341 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers()); 3342 return ResultType; 3343#endif 3344 3345 case Type::TemplateSpecialization: 3346 assert(false && "Dependent types have no size"); 3347 break; 3348 } 3349 3350 return QualType(); 3351} 3352 3353//===----------------------------------------------------------------------===// 3354// Integer Predicates 3355//===----------------------------------------------------------------------===// 3356 3357unsigned ASTContext::getIntWidth(QualType T) { 3358 if (T == BoolTy) 3359 return 1; 3360 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) { 3361 return FWIT->getWidth(); 3362 } 3363 // For builtin types, just use the standard type sizing method 3364 return (unsigned)getTypeSize(T); 3365} 3366 3367QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 3368 assert(T->isSignedIntegerType() && "Unexpected type"); 3369 if (const EnumType* ETy = T->getAsEnumType()) 3370 T = ETy->getDecl()->getIntegerType(); 3371 const BuiltinType* BTy = T->getAsBuiltinType(); 3372 assert (BTy && "Unexpected signed integer type"); 3373 switch (BTy->getKind()) { 3374 case BuiltinType::Char_S: 3375 case BuiltinType::SChar: 3376 return UnsignedCharTy; 3377 case BuiltinType::Short: 3378 return UnsignedShortTy; 3379 case BuiltinType::Int: 3380 return UnsignedIntTy; 3381 case BuiltinType::Long: 3382 return UnsignedLongTy; 3383 case BuiltinType::LongLong: 3384 return UnsignedLongLongTy; 3385 case BuiltinType::Int128: 3386 return UnsignedInt128Ty; 3387 default: 3388 assert(0 && "Unexpected signed integer type"); 3389 return QualType(); 3390 } 3391} 3392 3393ExternalASTSource::~ExternalASTSource() { } 3394 3395void ExternalASTSource::PrintStats() { } 3396