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