ASTContext.cpp revision 3d815e7eb56c25d7ed812eced32e41df43039f9a
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/Expr.h" 18#include "clang/AST/RecordLayout.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/ADT/StringExtras.h" 21#include "llvm/Bitcode/Serialize.h" 22#include "llvm/Bitcode/Deserialize.h" 23 24using namespace clang; 25 26enum FloatingRank { 27 FloatRank, DoubleRank, LongDoubleRank 28}; 29 30ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t, 31 IdentifierTable &idents, SelectorTable &sels, 32 unsigned size_reserve) : 33 CFConstantStringTypeDecl(0), SourceMgr(SM), LangOpts(LOpts), Target(t), 34 Idents(idents), Selectors(sels) 35{ 36 if (size_reserve > 0) Types.reserve(size_reserve); 37 InitBuiltinTypes(); 38 BuiltinInfo.InitializeBuiltins(idents, Target); 39 TUDecl = TranslationUnitDecl::Create(*this); 40} 41 42ASTContext::~ASTContext() { 43 // Deallocate all the types. 44 while (!Types.empty()) { 45 Types.back()->Destroy(*this); 46 Types.pop_back(); 47 } 48 49 TUDecl->Destroy(*this); 50} 51 52void ASTContext::PrintStats() const { 53 fprintf(stderr, "*** AST Context Stats:\n"); 54 fprintf(stderr, " %d types total.\n", (int)Types.size()); 55 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0; 56 unsigned NumVector = 0, NumComplex = 0; 57 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0; 58 59 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0; 60 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0; 61 unsigned NumObjCQualifiedIds = 0; 62 unsigned NumTypeOfTypes = 0, NumTypeOfExprs = 0; 63 64 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 65 Type *T = Types[i]; 66 if (isa<BuiltinType>(T)) 67 ++NumBuiltin; 68 else if (isa<PointerType>(T)) 69 ++NumPointer; 70 else if (isa<ReferenceType>(T)) 71 ++NumReference; 72 else if (isa<ComplexType>(T)) 73 ++NumComplex; 74 else if (isa<ArrayType>(T)) 75 ++NumArray; 76 else if (isa<VectorType>(T)) 77 ++NumVector; 78 else if (isa<FunctionTypeNoProto>(T)) 79 ++NumFunctionNP; 80 else if (isa<FunctionTypeProto>(T)) 81 ++NumFunctionP; 82 else if (isa<TypedefType>(T)) 83 ++NumTypeName; 84 else if (TagType *TT = dyn_cast<TagType>(T)) { 85 ++NumTagged; 86 switch (TT->getDecl()->getTagKind()) { 87 default: assert(0 && "Unknown tagged type!"); 88 case TagDecl::TK_struct: ++NumTagStruct; break; 89 case TagDecl::TK_union: ++NumTagUnion; break; 90 case TagDecl::TK_class: ++NumTagClass; break; 91 case TagDecl::TK_enum: ++NumTagEnum; break; 92 } 93 } else if (isa<ObjCInterfaceType>(T)) 94 ++NumObjCInterfaces; 95 else if (isa<ObjCQualifiedInterfaceType>(T)) 96 ++NumObjCQualifiedInterfaces; 97 else if (isa<ObjCQualifiedIdType>(T)) 98 ++NumObjCQualifiedIds; 99 else if (isa<TypeOfType>(T)) 100 ++NumTypeOfTypes; 101 else if (isa<TypeOfExpr>(T)) 102 ++NumTypeOfExprs; 103 else { 104 QualType(T, 0).dump(); 105 assert(0 && "Unknown type!"); 106 } 107 } 108 109 fprintf(stderr, " %d builtin types\n", NumBuiltin); 110 fprintf(stderr, " %d pointer types\n", NumPointer); 111 fprintf(stderr, " %d reference types\n", NumReference); 112 fprintf(stderr, " %d complex types\n", NumComplex); 113 fprintf(stderr, " %d array types\n", NumArray); 114 fprintf(stderr, " %d vector types\n", NumVector); 115 fprintf(stderr, " %d function types with proto\n", NumFunctionP); 116 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP); 117 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName); 118 fprintf(stderr, " %d tagged types\n", NumTagged); 119 fprintf(stderr, " %d struct types\n", NumTagStruct); 120 fprintf(stderr, " %d union types\n", NumTagUnion); 121 fprintf(stderr, " %d class types\n", NumTagClass); 122 fprintf(stderr, " %d enum types\n", NumTagEnum); 123 fprintf(stderr, " %d interface types\n", NumObjCInterfaces); 124 fprintf(stderr, " %d protocol qualified interface types\n", 125 NumObjCQualifiedInterfaces); 126 fprintf(stderr, " %d protocol qualified id types\n", 127 NumObjCQualifiedIds); 128 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes); 129 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprs); 130 131 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+ 132 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+ 133 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+ 134 NumFunctionP*sizeof(FunctionTypeProto)+ 135 NumFunctionNP*sizeof(FunctionTypeNoProto)+ 136 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+ 137 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprs*sizeof(TypeOfExpr))); 138} 139 140 141void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) { 142 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr()); 143} 144 145void ASTContext::InitBuiltinTypes() { 146 assert(VoidTy.isNull() && "Context reinitialized?"); 147 148 // C99 6.2.5p19. 149 InitBuiltinType(VoidTy, BuiltinType::Void); 150 151 // C99 6.2.5p2. 152 InitBuiltinType(BoolTy, BuiltinType::Bool); 153 // C99 6.2.5p3. 154 if (Target.isCharSigned()) 155 InitBuiltinType(CharTy, BuiltinType::Char_S); 156 else 157 InitBuiltinType(CharTy, BuiltinType::Char_U); 158 // C99 6.2.5p4. 159 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 160 InitBuiltinType(ShortTy, BuiltinType::Short); 161 InitBuiltinType(IntTy, BuiltinType::Int); 162 InitBuiltinType(LongTy, BuiltinType::Long); 163 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 164 165 // C99 6.2.5p6. 166 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 167 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 168 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 169 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 170 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 171 172 // C99 6.2.5p10. 173 InitBuiltinType(FloatTy, BuiltinType::Float); 174 InitBuiltinType(DoubleTy, BuiltinType::Double); 175 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 176 177 // C++ 3.9.1p5 178 InitBuiltinType(WCharTy, BuiltinType::WChar); 179 180 // C99 6.2.5p11. 181 FloatComplexTy = getComplexType(FloatTy); 182 DoubleComplexTy = getComplexType(DoubleTy); 183 LongDoubleComplexTy = getComplexType(LongDoubleTy); 184 185 BuiltinVaListType = QualType(); 186 ObjCIdType = QualType(); 187 IdStructType = 0; 188 ObjCClassType = QualType(); 189 ClassStructType = 0; 190 191 ObjCConstantStringType = QualType(); 192 193 // void * type 194 VoidPtrTy = getPointerType(VoidTy); 195} 196 197//===----------------------------------------------------------------------===// 198// Type Sizing and Analysis 199//===----------------------------------------------------------------------===// 200 201/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 202/// scalar floating point type. 203const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 204 const BuiltinType *BT = T->getAsBuiltinType(); 205 assert(BT && "Not a floating point type!"); 206 switch (BT->getKind()) { 207 default: assert(0 && "Not a floating point type!"); 208 case BuiltinType::Float: return Target.getFloatFormat(); 209 case BuiltinType::Double: return Target.getDoubleFormat(); 210 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 211 } 212} 213 214 215/// getTypeSize - Return the size of the specified type, in bits. This method 216/// does not work on incomplete types. 217std::pair<uint64_t, unsigned> 218ASTContext::getTypeInfo(QualType T) { 219 T = getCanonicalType(T); 220 uint64_t Width; 221 unsigned Align; 222 switch (T->getTypeClass()) { 223 case Type::TypeName: assert(0 && "Not a canonical type!"); 224 case Type::FunctionNoProto: 225 case Type::FunctionProto: 226 default: 227 assert(0 && "Incomplete types have no size!"); 228 case Type::VariableArray: 229 assert(0 && "VLAs not implemented yet!"); 230 case Type::ConstantArray: { 231 ConstantArrayType *CAT = cast<ConstantArrayType>(T); 232 233 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 234 Width = EltInfo.first*CAT->getSize().getZExtValue(); 235 Align = EltInfo.second; 236 break; 237 } 238 case Type::ExtVector: 239 case Type::Vector: { 240 std::pair<uint64_t, unsigned> EltInfo = 241 getTypeInfo(cast<VectorType>(T)->getElementType()); 242 Width = EltInfo.first*cast<VectorType>(T)->getNumElements(); 243 // FIXME: This isn't right for unusual vectors 244 Align = Width; 245 break; 246 } 247 248 case Type::Builtin: 249 switch (cast<BuiltinType>(T)->getKind()) { 250 default: assert(0 && "Unknown builtin type!"); 251 case BuiltinType::Void: 252 assert(0 && "Incomplete types have no size!"); 253 case BuiltinType::Bool: 254 Width = Target.getBoolWidth(); 255 Align = Target.getBoolAlign(); 256 break; 257 case BuiltinType::Char_S: 258 case BuiltinType::Char_U: 259 case BuiltinType::UChar: 260 case BuiltinType::SChar: 261 Width = Target.getCharWidth(); 262 Align = Target.getCharAlign(); 263 break; 264 case BuiltinType::WChar: 265 Width = Target.getWCharWidth(); 266 Align = Target.getWCharAlign(); 267 break; 268 case BuiltinType::UShort: 269 case BuiltinType::Short: 270 Width = Target.getShortWidth(); 271 Align = Target.getShortAlign(); 272 break; 273 case BuiltinType::UInt: 274 case BuiltinType::Int: 275 Width = Target.getIntWidth(); 276 Align = Target.getIntAlign(); 277 break; 278 case BuiltinType::ULong: 279 case BuiltinType::Long: 280 Width = Target.getLongWidth(); 281 Align = Target.getLongAlign(); 282 break; 283 case BuiltinType::ULongLong: 284 case BuiltinType::LongLong: 285 Width = Target.getLongLongWidth(); 286 Align = Target.getLongLongAlign(); 287 break; 288 case BuiltinType::Float: 289 Width = Target.getFloatWidth(); 290 Align = Target.getFloatAlign(); 291 break; 292 case BuiltinType::Double: 293 Width = Target.getDoubleWidth(); 294 Align = Target.getDoubleAlign(); 295 break; 296 case BuiltinType::LongDouble: 297 Width = Target.getLongDoubleWidth(); 298 Align = Target.getLongDoubleAlign(); 299 break; 300 } 301 break; 302 case Type::ASQual: 303 // FIXME: Pointers into different addr spaces could have different sizes and 304 // alignment requirements: getPointerInfo should take an AddrSpace. 305 return getTypeInfo(QualType(cast<ASQualType>(T)->getBaseType(), 0)); 306 case Type::ObjCQualifiedId: 307 Width = Target.getPointerWidth(0); 308 Align = Target.getPointerAlign(0); 309 break; 310 case Type::Pointer: { 311 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 312 Width = Target.getPointerWidth(AS); 313 Align = Target.getPointerAlign(AS); 314 break; 315 } 316 case Type::Reference: 317 // "When applied to a reference or a reference type, the result is the size 318 // of the referenced type." C++98 5.3.3p2: expr.sizeof. 319 // FIXME: This is wrong for struct layout: a reference in a struct has 320 // pointer size. 321 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType()); 322 323 case Type::Complex: { 324 // Complex types have the same alignment as their elements, but twice the 325 // size. 326 std::pair<uint64_t, unsigned> EltInfo = 327 getTypeInfo(cast<ComplexType>(T)->getElementType()); 328 Width = EltInfo.first*2; 329 Align = EltInfo.second; 330 break; 331 } 332 case Type::ObjCInterface: { 333 ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 334 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 335 Width = Layout.getSize(); 336 Align = Layout.getAlignment(); 337 break; 338 } 339 case Type::Tagged: { 340 if (cast<TagType>(T)->getDecl()->isInvalidDecl()) { 341 Width = 1; 342 Align = 1; 343 break; 344 } 345 346 if (EnumType *ET = dyn_cast<EnumType>(cast<TagType>(T))) 347 return getTypeInfo(ET->getDecl()->getIntegerType()); 348 349 RecordType *RT = cast<RecordType>(T); 350 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 351 Width = Layout.getSize(); 352 Align = Layout.getAlignment(); 353 break; 354 } 355 } 356 357 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 358 return std::make_pair(Width, Align); 359} 360 361/// LayoutField - Field layout. 362void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo, 363 bool IsUnion, bool StructIsPacked, 364 ASTContext &Context) { 365 bool FieldIsPacked = StructIsPacked || FD->getAttr<PackedAttr>(); 366 uint64_t FieldOffset = IsUnion ? 0 : Size; 367 uint64_t FieldSize; 368 unsigned FieldAlign; 369 370 if (const Expr *BitWidthExpr = FD->getBitWidth()) { 371 // TODO: Need to check this algorithm on other targets! 372 // (tested on Linux-X86) 373 FieldSize = 374 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue(); 375 376 std::pair<uint64_t, unsigned> FieldInfo = 377 Context.getTypeInfo(FD->getType()); 378 uint64_t TypeSize = FieldInfo.first; 379 380 FieldAlign = FieldInfo.second; 381 if (FieldIsPacked) 382 FieldAlign = 1; 383 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 384 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 385 386 // Check if we need to add padding to give the field the correct 387 // alignment. 388 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize) 389 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 390 391 // Padding members don't affect overall alignment 392 if (!FD->getIdentifier()) 393 FieldAlign = 1; 394 } else { 395 if (FD->getType()->isIncompleteArrayType()) { 396 // This is a flexible array member; we can't directly 397 // query getTypeInfo about these, so we figure it out here. 398 // Flexible array members don't have any size, but they 399 // have to be aligned appropriately for their element type. 400 FieldSize = 0; 401 const ArrayType* ATy = Context.getAsArrayType(FD->getType()); 402 FieldAlign = Context.getTypeAlign(ATy->getElementType()); 403 } else { 404 std::pair<uint64_t, unsigned> FieldInfo = 405 Context.getTypeInfo(FD->getType()); 406 FieldSize = FieldInfo.first; 407 FieldAlign = FieldInfo.second; 408 } 409 410 if (FieldIsPacked) 411 FieldAlign = 8; 412 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>()) 413 FieldAlign = std::max(FieldAlign, AA->getAlignment()); 414 415 // Round up the current record size to the field's alignment boundary. 416 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1); 417 } 418 419 // Place this field at the current location. 420 FieldOffsets[FieldNo] = FieldOffset; 421 422 // Reserve space for this field. 423 if (IsUnion) { 424 Size = std::max(Size, FieldSize); 425 } else { 426 Size = FieldOffset + FieldSize; 427 } 428 429 // Remember max struct/class alignment. 430 Alignment = std::max(Alignment, FieldAlign); 431} 432 433 434/// getASTObjcInterfaceLayout - Get or compute information about the layout of the 435/// specified Objective C, which indicates its size and ivar 436/// position information. 437const ASTRecordLayout & 438ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 439 // Look up this layout, if already laid out, return what we have. 440 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D]; 441 if (Entry) return *Entry; 442 443 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 444 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 445 ASTRecordLayout *NewEntry = NULL; 446 unsigned FieldCount = D->ivar_size(); 447 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 448 FieldCount++; 449 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD); 450 unsigned Alignment = SL.getAlignment(); 451 uint64_t Size = SL.getSize(); 452 NewEntry = new ASTRecordLayout(Size, Alignment); 453 NewEntry->InitializeLayout(FieldCount); 454 NewEntry->SetFieldOffset(0, 0); // Super class is at the beginning of the layout. 455 } else { 456 NewEntry = new ASTRecordLayout(); 457 NewEntry->InitializeLayout(FieldCount); 458 } 459 Entry = NewEntry; 460 461 bool IsPacked = D->getAttr<PackedAttr>(); 462 463 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 464 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 465 AA->getAlignment())); 466 467 // Layout each ivar sequentially. 468 unsigned i = 0; 469 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(), 470 IVE = D->ivar_end(); IVI != IVE; ++IVI) { 471 const ObjCIvarDecl* Ivar = (*IVI); 472 NewEntry->LayoutField(Ivar, i++, false, IsPacked, *this); 473 } 474 475 // Finally, round the size of the total struct up to the alignment of the 476 // struct itself. 477 NewEntry->FinalizeLayout(); 478 return *NewEntry; 479} 480 481/// getASTRecordLayout - Get or compute information about the layout of the 482/// specified record (struct/union/class), which indicates its size and field 483/// position information. 484const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 485 assert(D->isDefinition() && "Cannot get layout of forward declarations!"); 486 487 // Look up this layout, if already laid out, return what we have. 488 const ASTRecordLayout *&Entry = ASTRecordLayouts[D]; 489 if (Entry) return *Entry; 490 491 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can 492 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into. 493 ASTRecordLayout *NewEntry = new ASTRecordLayout(); 494 Entry = NewEntry; 495 496 NewEntry->InitializeLayout(D->getNumMembers()); 497 bool StructIsPacked = D->getAttr<PackedAttr>(); 498 bool IsUnion = D->isUnion(); 499 500 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 501 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(), 502 AA->getAlignment())); 503 504 // Layout each field, for now, just sequentially, respecting alignment. In 505 // the future, this will need to be tweakable by targets. 506 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) { 507 const FieldDecl *FD = D->getMember(i); 508 NewEntry->LayoutField(FD, i, IsUnion, StructIsPacked, *this); 509 } 510 511 // Finally, round the size of the total struct up to the alignment of the 512 // struct itself. 513 NewEntry->FinalizeLayout(); 514 return *NewEntry; 515} 516 517//===----------------------------------------------------------------------===// 518// Type creation/memoization methods 519//===----------------------------------------------------------------------===// 520 521QualType ASTContext::getASQualType(QualType T, unsigned AddressSpace) { 522 QualType CanT = getCanonicalType(T); 523 if (CanT.getAddressSpace() == AddressSpace) 524 return T; 525 526 // Type's cannot have multiple ASQuals, therefore we know we only have to deal 527 // with CVR qualifiers from here on out. 528 assert(CanT.getAddressSpace() == 0 && 529 "Type is already address space qualified"); 530 531 // Check if we've already instantiated an address space qual'd type of this 532 // type. 533 llvm::FoldingSetNodeID ID; 534 ASQualType::Profile(ID, T.getTypePtr(), AddressSpace); 535 void *InsertPos = 0; 536 if (ASQualType *ASQy = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos)) 537 return QualType(ASQy, 0); 538 539 // If the base type isn't canonical, this won't be a canonical type either, 540 // so fill in the canonical type field. 541 QualType Canonical; 542 if (!T->isCanonical()) { 543 Canonical = getASQualType(CanT, AddressSpace); 544 545 // Get the new insert position for the node we care about. 546 ASQualType *NewIP = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos); 547 assert(NewIP == 0 && "Shouldn't be in the map!"); 548 } 549 ASQualType *New = new ASQualType(T.getTypePtr(), Canonical, AddressSpace); 550 ASQualTypes.InsertNode(New, InsertPos); 551 Types.push_back(New); 552 return QualType(New, T.getCVRQualifiers()); 553} 554 555 556/// getComplexType - Return the uniqued reference to the type for a complex 557/// number with the specified element type. 558QualType ASTContext::getComplexType(QualType T) { 559 // Unique pointers, to guarantee there is only one pointer of a particular 560 // structure. 561 llvm::FoldingSetNodeID ID; 562 ComplexType::Profile(ID, T); 563 564 void *InsertPos = 0; 565 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 566 return QualType(CT, 0); 567 568 // If the pointee type isn't canonical, this won't be a canonical type either, 569 // so fill in the canonical type field. 570 QualType Canonical; 571 if (!T->isCanonical()) { 572 Canonical = getComplexType(getCanonicalType(T)); 573 574 // Get the new insert position for the node we care about. 575 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 576 assert(NewIP == 0 && "Shouldn't be in the map!"); 577 } 578 ComplexType *New = new ComplexType(T, Canonical); 579 Types.push_back(New); 580 ComplexTypes.InsertNode(New, InsertPos); 581 return QualType(New, 0); 582} 583 584 585/// getPointerType - Return the uniqued reference to the type for a pointer to 586/// the specified type. 587QualType ASTContext::getPointerType(QualType T) { 588 // Unique pointers, to guarantee there is only one pointer of a particular 589 // structure. 590 llvm::FoldingSetNodeID ID; 591 PointerType::Profile(ID, T); 592 593 void *InsertPos = 0; 594 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 595 return QualType(PT, 0); 596 597 // If the pointee type isn't canonical, this won't be a canonical type either, 598 // so fill in the canonical type field. 599 QualType Canonical; 600 if (!T->isCanonical()) { 601 Canonical = getPointerType(getCanonicalType(T)); 602 603 // Get the new insert position for the node we care about. 604 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 605 assert(NewIP == 0 && "Shouldn't be in the map!"); 606 } 607 PointerType *New = new PointerType(T, Canonical); 608 Types.push_back(New); 609 PointerTypes.InsertNode(New, InsertPos); 610 return QualType(New, 0); 611} 612 613/// getReferenceType - Return the uniqued reference to the type for a reference 614/// to the specified type. 615QualType ASTContext::getReferenceType(QualType T) { 616 // Unique pointers, to guarantee there is only one pointer of a particular 617 // structure. 618 llvm::FoldingSetNodeID ID; 619 ReferenceType::Profile(ID, T); 620 621 void *InsertPos = 0; 622 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 623 return QualType(RT, 0); 624 625 // If the referencee type isn't canonical, this won't be a canonical type 626 // either, so fill in the canonical type field. 627 QualType Canonical; 628 if (!T->isCanonical()) { 629 Canonical = getReferenceType(getCanonicalType(T)); 630 631 // Get the new insert position for the node we care about. 632 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 633 assert(NewIP == 0 && "Shouldn't be in the map!"); 634 } 635 636 ReferenceType *New = new ReferenceType(T, Canonical); 637 Types.push_back(New); 638 ReferenceTypes.InsertNode(New, InsertPos); 639 return QualType(New, 0); 640} 641 642/// getConstantArrayType - Return the unique reference to the type for an 643/// array of the specified element type. 644QualType ASTContext::getConstantArrayType(QualType EltTy, 645 const llvm::APInt &ArySize, 646 ArrayType::ArraySizeModifier ASM, 647 unsigned EltTypeQuals) { 648 llvm::FoldingSetNodeID ID; 649 ConstantArrayType::Profile(ID, EltTy, ArySize); 650 651 void *InsertPos = 0; 652 if (ConstantArrayType *ATP = 653 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 654 return QualType(ATP, 0); 655 656 // If the element type isn't canonical, this won't be a canonical type either, 657 // so fill in the canonical type field. 658 QualType Canonical; 659 if (!EltTy->isCanonical()) { 660 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 661 ASM, EltTypeQuals); 662 // Get the new insert position for the node we care about. 663 ConstantArrayType *NewIP = 664 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 665 666 assert(NewIP == 0 && "Shouldn't be in the map!"); 667 } 668 669 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize, 670 ASM, EltTypeQuals); 671 ConstantArrayTypes.InsertNode(New, InsertPos); 672 Types.push_back(New); 673 return QualType(New, 0); 674} 675 676/// getVariableArrayType - Returns a non-unique reference to the type for a 677/// variable array of the specified element type. 678QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, 679 ArrayType::ArraySizeModifier ASM, 680 unsigned EltTypeQuals) { 681 // Since we don't unique expressions, it isn't possible to unique VLA's 682 // that have an expression provided for their size. 683 684 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts, 685 ASM, EltTypeQuals); 686 687 VariableArrayTypes.push_back(New); 688 Types.push_back(New); 689 return QualType(New, 0); 690} 691 692QualType ASTContext::getIncompleteArrayType(QualType EltTy, 693 ArrayType::ArraySizeModifier ASM, 694 unsigned EltTypeQuals) { 695 llvm::FoldingSetNodeID ID; 696 IncompleteArrayType::Profile(ID, EltTy); 697 698 void *InsertPos = 0; 699 if (IncompleteArrayType *ATP = 700 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 701 return QualType(ATP, 0); 702 703 // If the element type isn't canonical, this won't be a canonical type 704 // either, so fill in the canonical type field. 705 QualType Canonical; 706 707 if (!EltTy->isCanonical()) { 708 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 709 ASM, EltTypeQuals); 710 711 // Get the new insert position for the node we care about. 712 IncompleteArrayType *NewIP = 713 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 714 715 assert(NewIP == 0 && "Shouldn't be in the map!"); 716 } 717 718 IncompleteArrayType *New = new IncompleteArrayType(EltTy, Canonical, 719 ASM, EltTypeQuals); 720 721 IncompleteArrayTypes.InsertNode(New, InsertPos); 722 Types.push_back(New); 723 return QualType(New, 0); 724} 725 726/// getVectorType - Return the unique reference to a vector type of 727/// the specified element type and size. VectorType must be a built-in type. 728QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) { 729 BuiltinType *baseType; 730 731 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 732 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 733 734 // Check if we've already instantiated a vector of this type. 735 llvm::FoldingSetNodeID ID; 736 VectorType::Profile(ID, vecType, NumElts, Type::Vector); 737 void *InsertPos = 0; 738 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 739 return QualType(VTP, 0); 740 741 // If the element type isn't canonical, this won't be a canonical type either, 742 // so fill in the canonical type field. 743 QualType Canonical; 744 if (!vecType->isCanonical()) { 745 Canonical = getVectorType(getCanonicalType(vecType), NumElts); 746 747 // Get the new insert position for the node we care about. 748 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 749 assert(NewIP == 0 && "Shouldn't be in the map!"); 750 } 751 VectorType *New = new VectorType(vecType, NumElts, Canonical); 752 VectorTypes.InsertNode(New, InsertPos); 753 Types.push_back(New); 754 return QualType(New, 0); 755} 756 757/// getExtVectorType - Return the unique reference to an extended vector type of 758/// the specified element type and size. VectorType must be a built-in type. 759QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 760 BuiltinType *baseType; 761 762 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 763 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 764 765 // Check if we've already instantiated a vector of this type. 766 llvm::FoldingSetNodeID ID; 767 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector); 768 void *InsertPos = 0; 769 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 770 return QualType(VTP, 0); 771 772 // If the element type isn't canonical, this won't be a canonical type either, 773 // so fill in the canonical type field. 774 QualType Canonical; 775 if (!vecType->isCanonical()) { 776 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 777 778 // Get the new insert position for the node we care about. 779 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 780 assert(NewIP == 0 && "Shouldn't be in the map!"); 781 } 782 ExtVectorType *New = new ExtVectorType(vecType, NumElts, Canonical); 783 VectorTypes.InsertNode(New, InsertPos); 784 Types.push_back(New); 785 return QualType(New, 0); 786} 787 788/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'. 789/// 790QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) { 791 // Unique functions, to guarantee there is only one function of a particular 792 // structure. 793 llvm::FoldingSetNodeID ID; 794 FunctionTypeNoProto::Profile(ID, ResultTy); 795 796 void *InsertPos = 0; 797 if (FunctionTypeNoProto *FT = 798 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos)) 799 return QualType(FT, 0); 800 801 QualType Canonical; 802 if (!ResultTy->isCanonical()) { 803 Canonical = getFunctionTypeNoProto(getCanonicalType(ResultTy)); 804 805 // Get the new insert position for the node we care about. 806 FunctionTypeNoProto *NewIP = 807 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos); 808 assert(NewIP == 0 && "Shouldn't be in the map!"); 809 } 810 811 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical); 812 Types.push_back(New); 813 FunctionTypeNoProtos.InsertNode(New, InsertPos); 814 return QualType(New, 0); 815} 816 817/// getFunctionType - Return a normal function type with a typed argument 818/// list. isVariadic indicates whether the argument list includes '...'. 819QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray, 820 unsigned NumArgs, bool isVariadic) { 821 // Unique functions, to guarantee there is only one function of a particular 822 // structure. 823 llvm::FoldingSetNodeID ID; 824 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic); 825 826 void *InsertPos = 0; 827 if (FunctionTypeProto *FTP = 828 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos)) 829 return QualType(FTP, 0); 830 831 // Determine whether the type being created is already canonical or not. 832 bool isCanonical = ResultTy->isCanonical(); 833 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 834 if (!ArgArray[i]->isCanonical()) 835 isCanonical = false; 836 837 // If this type isn't canonical, get the canonical version of it. 838 QualType Canonical; 839 if (!isCanonical) { 840 llvm::SmallVector<QualType, 16> CanonicalArgs; 841 CanonicalArgs.reserve(NumArgs); 842 for (unsigned i = 0; i != NumArgs; ++i) 843 CanonicalArgs.push_back(getCanonicalType(ArgArray[i])); 844 845 Canonical = getFunctionType(getCanonicalType(ResultTy), 846 &CanonicalArgs[0], NumArgs, 847 isVariadic); 848 849 // Get the new insert position for the node we care about. 850 FunctionTypeProto *NewIP = 851 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos); 852 assert(NewIP == 0 && "Shouldn't be in the map!"); 853 } 854 855 // FunctionTypeProto objects are not allocated with new because they have a 856 // variable size array (for parameter types) at the end of them. 857 FunctionTypeProto *FTP = 858 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) + 859 NumArgs*sizeof(QualType)); 860 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic, 861 Canonical); 862 Types.push_back(FTP); 863 FunctionTypeProtos.InsertNode(FTP, InsertPos); 864 return QualType(FTP, 0); 865} 866 867/// getTypeDeclType - Return the unique reference to the type for the 868/// specified type declaration. 869QualType ASTContext::getTypeDeclType(TypeDecl *Decl) { 870 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 871 872 if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(Decl)) 873 return getTypedefType(Typedef); 874 else if (ObjCInterfaceDecl *ObjCInterface 875 = dyn_cast_or_null<ObjCInterfaceDecl>(Decl)) 876 return getObjCInterfaceType(ObjCInterface); 877 878 if (CXXRecordDecl *CXXRecord = dyn_cast_or_null<CXXRecordDecl>(Decl)) 879 Decl->TypeForDecl = new CXXRecordType(CXXRecord); 880 else if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Decl)) 881 Decl->TypeForDecl = new RecordType(Record); 882 else if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Decl)) 883 Decl->TypeForDecl = new EnumType(Enum); 884 else 885 assert(false && "TypeDecl without a type?"); 886 887 Types.push_back(Decl->TypeForDecl); 888 return QualType(Decl->TypeForDecl, 0); 889} 890 891/// getTypedefType - Return the unique reference to the type for the 892/// specified typename decl. 893QualType ASTContext::getTypedefType(TypedefDecl *Decl) { 894 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 895 896 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 897 Decl->TypeForDecl = new TypedefType(Type::TypeName, Decl, Canonical); 898 Types.push_back(Decl->TypeForDecl); 899 return QualType(Decl->TypeForDecl, 0); 900} 901 902/// getObjCInterfaceType - Return the unique reference to the type for the 903/// specified ObjC interface decl. 904QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) { 905 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 906 907 Decl->TypeForDecl = new ObjCInterfaceType(Type::ObjCInterface, Decl); 908 Types.push_back(Decl->TypeForDecl); 909 return QualType(Decl->TypeForDecl, 0); 910} 911 912/// CmpProtocolNames - Comparison predicate for sorting protocols 913/// alphabetically. 914static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 915 const ObjCProtocolDecl *RHS) { 916 return strcmp(LHS->getName(), RHS->getName()) < 0; 917} 918 919static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols, 920 unsigned &NumProtocols) { 921 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 922 923 // Sort protocols, keyed by name. 924 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 925 926 // Remove duplicates. 927 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 928 NumProtocols = ProtocolsEnd-Protocols; 929} 930 931 932/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for 933/// the given interface decl and the conforming protocol list. 934QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl, 935 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 936 // Sort the protocol list alphabetically to canonicalize it. 937 SortAndUniqueProtocols(Protocols, NumProtocols); 938 939 llvm::FoldingSetNodeID ID; 940 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 941 942 void *InsertPos = 0; 943 if (ObjCQualifiedInterfaceType *QT = 944 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 945 return QualType(QT, 0); 946 947 // No Match; 948 ObjCQualifiedInterfaceType *QType = 949 new ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols); 950 Types.push_back(QType); 951 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos); 952 return QualType(QType, 0); 953} 954 955/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl 956/// and the conforming protocol list. 957QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols, 958 unsigned NumProtocols) { 959 // Sort the protocol list alphabetically to canonicalize it. 960 SortAndUniqueProtocols(Protocols, NumProtocols); 961 962 llvm::FoldingSetNodeID ID; 963 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols); 964 965 void *InsertPos = 0; 966 if (ObjCQualifiedIdType *QT = 967 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos)) 968 return QualType(QT, 0); 969 970 // No Match; 971 ObjCQualifiedIdType *QType = new ObjCQualifiedIdType(Protocols, NumProtocols); 972 Types.push_back(QType); 973 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos); 974 return QualType(QType, 0); 975} 976 977/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique 978/// TypeOfExpr AST's (since expression's are never shared). For example, 979/// multiple declarations that refer to "typeof(x)" all contain different 980/// DeclRefExpr's. This doesn't effect the type checker, since it operates 981/// on canonical type's (which are always unique). 982QualType ASTContext::getTypeOfExpr(Expr *tofExpr) { 983 QualType Canonical = getCanonicalType(tofExpr->getType()); 984 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical); 985 Types.push_back(toe); 986 return QualType(toe, 0); 987} 988 989/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 990/// TypeOfType AST's. The only motivation to unique these nodes would be 991/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 992/// an issue. This doesn't effect the type checker, since it operates 993/// on canonical type's (which are always unique). 994QualType ASTContext::getTypeOfType(QualType tofType) { 995 QualType Canonical = getCanonicalType(tofType); 996 TypeOfType *tot = new TypeOfType(tofType, Canonical); 997 Types.push_back(tot); 998 return QualType(tot, 0); 999} 1000 1001/// getTagDeclType - Return the unique reference to the type for the 1002/// specified TagDecl (struct/union/class/enum) decl. 1003QualType ASTContext::getTagDeclType(TagDecl *Decl) { 1004 assert (Decl); 1005 return getTypeDeclType(Decl); 1006} 1007 1008/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 1009/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 1010/// needs to agree with the definition in <stddef.h>. 1011QualType ASTContext::getSizeType() const { 1012 // On Darwin, size_t is defined as a "long unsigned int". 1013 // FIXME: should derive from "Target". 1014 return UnsignedLongTy; 1015} 1016 1017/// getWCharType - Return the unique type for "wchar_t" (C99 7.17), the 1018/// width of characters in wide strings, The value is target dependent and 1019/// needs to agree with the definition in <stddef.h>. 1020QualType ASTContext::getWCharType() const { 1021 if (LangOpts.CPlusPlus) 1022 return WCharTy; 1023 1024 // On Darwin, wchar_t is defined as a "int". 1025 // FIXME: should derive from "Target". 1026 return IntTy; 1027} 1028 1029/// getSignedWCharType - Return the type of "signed wchar_t". 1030/// Used when in C++, as a GCC extension. 1031QualType ASTContext::getSignedWCharType() const { 1032 // FIXME: derive from "Target" ? 1033 return WCharTy; 1034} 1035 1036/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 1037/// Used when in C++, as a GCC extension. 1038QualType ASTContext::getUnsignedWCharType() const { 1039 // FIXME: derive from "Target" ? 1040 return UnsignedIntTy; 1041} 1042 1043/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 1044/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 1045QualType ASTContext::getPointerDiffType() const { 1046 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug... 1047 // FIXME: should derive from "Target". 1048 return IntTy; 1049} 1050 1051//===----------------------------------------------------------------------===// 1052// Type Operators 1053//===----------------------------------------------------------------------===// 1054 1055/// getCanonicalType - Return the canonical (structural) type corresponding to 1056/// the specified potentially non-canonical type. The non-canonical version 1057/// of a type may have many "decorated" versions of types. Decorators can 1058/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 1059/// to be free of any of these, allowing two canonical types to be compared 1060/// for exact equality with a simple pointer comparison. 1061QualType ASTContext::getCanonicalType(QualType T) { 1062 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal(); 1063 1064 // If the result has type qualifiers, make sure to canonicalize them as well. 1065 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers(); 1066 if (TypeQuals == 0) return CanType; 1067 1068 // If the type qualifiers are on an array type, get the canonical type of the 1069 // array with the qualifiers applied to the element type. 1070 ArrayType *AT = dyn_cast<ArrayType>(CanType); 1071 if (!AT) 1072 return CanType.getQualifiedType(TypeQuals); 1073 1074 // Get the canonical version of the element with the extra qualifiers on it. 1075 // This can recursively sink qualifiers through multiple levels of arrays. 1076 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals); 1077 NewEltTy = getCanonicalType(NewEltTy); 1078 1079 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1080 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(), 1081 CAT->getIndexTypeQualifier()); 1082 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 1083 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 1084 IAT->getIndexTypeQualifier()); 1085 1086 // FIXME: What is the ownership of size expressions in VLAs? 1087 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1088 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1089 VAT->getSizeModifier(), 1090 VAT->getIndexTypeQualifier()); 1091} 1092 1093 1094const ArrayType *ASTContext::getAsArrayType(QualType T) { 1095 // Handle the non-qualified case efficiently. 1096 if (T.getCVRQualifiers() == 0) { 1097 // Handle the common positive case fast. 1098 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 1099 return AT; 1100 } 1101 1102 // Handle the common negative case fast, ignoring CVR qualifiers. 1103 QualType CType = T->getCanonicalTypeInternal(); 1104 1105 // Make sure to look through type qualifiers (like ASQuals) for the negative 1106 // test. 1107 if (!isa<ArrayType>(CType) && 1108 !isa<ArrayType>(CType.getUnqualifiedType())) 1109 return 0; 1110 1111 // Apply any CVR qualifiers from the array type to the element type. This 1112 // implements C99 6.7.3p8: "If the specification of an array type includes 1113 // any type qualifiers, the element type is so qualified, not the array type." 1114 1115 // If we get here, we either have type qualifiers on the type, or we have 1116 // sugar such as a typedef in the way. If we have type qualifiers on the type 1117 // we must propagate them down into the elemeng type. 1118 unsigned CVRQuals = T.getCVRQualifiers(); 1119 unsigned AddrSpace = 0; 1120 Type *Ty = T.getTypePtr(); 1121 1122 // Rip through ASQualType's and typedefs to get to a concrete type. 1123 while (1) { 1124 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty)) { 1125 AddrSpace = ASQT->getAddressSpace(); 1126 Ty = ASQT->getBaseType(); 1127 } else { 1128 T = Ty->getDesugaredType(); 1129 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0) 1130 break; 1131 CVRQuals |= T.getCVRQualifiers(); 1132 Ty = T.getTypePtr(); 1133 } 1134 } 1135 1136 // If we have a simple case, just return now. 1137 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 1138 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0)) 1139 return ATy; 1140 1141 // Otherwise, we have an array and we have qualifiers on it. Push the 1142 // qualifiers into the array element type and return a new array type. 1143 // Get the canonical version of the element with the extra qualifiers on it. 1144 // This can recursively sink qualifiers through multiple levels of arrays. 1145 QualType NewEltTy = ATy->getElementType(); 1146 if (AddrSpace) 1147 NewEltTy = getASQualType(NewEltTy, AddrSpace); 1148 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals); 1149 1150 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 1151 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 1152 CAT->getSizeModifier(), 1153 CAT->getIndexTypeQualifier())); 1154 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 1155 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 1156 IAT->getSizeModifier(), 1157 IAT->getIndexTypeQualifier())); 1158 1159 // FIXME: What is the ownership of size expressions in VLAs? 1160 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 1161 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(), 1162 VAT->getSizeModifier(), 1163 VAT->getIndexTypeQualifier())); 1164} 1165 1166 1167/// getArrayDecayedType - Return the properly qualified result of decaying the 1168/// specified array type to a pointer. This operation is non-trivial when 1169/// handling typedefs etc. The canonical type of "T" must be an array type, 1170/// this returns a pointer to a properly qualified element of the array. 1171/// 1172/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 1173QualType ASTContext::getArrayDecayedType(QualType Ty) { 1174 // Get the element type with 'getAsArrayType' so that we don't lose any 1175 // typedefs in the element type of the array. This also handles propagation 1176 // of type qualifiers from the array type into the element type if present 1177 // (C99 6.7.3p8). 1178 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 1179 assert(PrettyArrayType && "Not an array type!"); 1180 1181 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 1182 1183 // int x[restrict 4] -> int *restrict 1184 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier()); 1185} 1186 1187/// getFloatingRank - Return a relative rank for floating point types. 1188/// This routine will assert if passed a built-in type that isn't a float. 1189static FloatingRank getFloatingRank(QualType T) { 1190 if (const ComplexType *CT = T->getAsComplexType()) 1191 return getFloatingRank(CT->getElementType()); 1192 1193 switch (T->getAsBuiltinType()->getKind()) { 1194 default: assert(0 && "getFloatingRank(): not a floating type"); 1195 case BuiltinType::Float: return FloatRank; 1196 case BuiltinType::Double: return DoubleRank; 1197 case BuiltinType::LongDouble: return LongDoubleRank; 1198 } 1199} 1200 1201/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 1202/// point or a complex type (based on typeDomain/typeSize). 1203/// 'typeDomain' is a real floating point or complex type. 1204/// 'typeSize' is a real floating point or complex type. 1205QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 1206 QualType Domain) const { 1207 FloatingRank EltRank = getFloatingRank(Size); 1208 if (Domain->isComplexType()) { 1209 switch (EltRank) { 1210 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1211 case FloatRank: return FloatComplexTy; 1212 case DoubleRank: return DoubleComplexTy; 1213 case LongDoubleRank: return LongDoubleComplexTy; 1214 } 1215 } 1216 1217 assert(Domain->isRealFloatingType() && "Unknown domain!"); 1218 switch (EltRank) { 1219 default: assert(0 && "getFloatingRank(): illegal value for rank"); 1220 case FloatRank: return FloatTy; 1221 case DoubleRank: return DoubleTy; 1222 case LongDoubleRank: return LongDoubleTy; 1223 } 1224} 1225 1226/// getFloatingTypeOrder - Compare the rank of the two specified floating 1227/// point types, ignoring the domain of the type (i.e. 'double' == 1228/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 1229/// LHS < RHS, return -1. 1230int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 1231 FloatingRank LHSR = getFloatingRank(LHS); 1232 FloatingRank RHSR = getFloatingRank(RHS); 1233 1234 if (LHSR == RHSR) 1235 return 0; 1236 if (LHSR > RHSR) 1237 return 1; 1238 return -1; 1239} 1240 1241/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 1242/// routine will assert if passed a built-in type that isn't an integer or enum, 1243/// or if it is not canonicalized. 1244static unsigned getIntegerRank(Type *T) { 1245 assert(T->isCanonical() && "T should be canonicalized"); 1246 if (isa<EnumType>(T)) 1247 return 4; 1248 1249 switch (cast<BuiltinType>(T)->getKind()) { 1250 default: assert(0 && "getIntegerRank(): not a built-in integer"); 1251 case BuiltinType::Bool: 1252 return 1; 1253 case BuiltinType::Char_S: 1254 case BuiltinType::Char_U: 1255 case BuiltinType::SChar: 1256 case BuiltinType::UChar: 1257 return 2; 1258 case BuiltinType::Short: 1259 case BuiltinType::UShort: 1260 return 3; 1261 case BuiltinType::Int: 1262 case BuiltinType::UInt: 1263 return 4; 1264 case BuiltinType::Long: 1265 case BuiltinType::ULong: 1266 return 5; 1267 case BuiltinType::LongLong: 1268 case BuiltinType::ULongLong: 1269 return 6; 1270 } 1271} 1272 1273/// getIntegerTypeOrder - Returns the highest ranked integer type: 1274/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 1275/// LHS < RHS, return -1. 1276int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 1277 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 1278 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 1279 if (LHSC == RHSC) return 0; 1280 1281 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 1282 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 1283 1284 unsigned LHSRank = getIntegerRank(LHSC); 1285 unsigned RHSRank = getIntegerRank(RHSC); 1286 1287 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 1288 if (LHSRank == RHSRank) return 0; 1289 return LHSRank > RHSRank ? 1 : -1; 1290 } 1291 1292 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 1293 if (LHSUnsigned) { 1294 // If the unsigned [LHS] type is larger, return it. 1295 if (LHSRank >= RHSRank) 1296 return 1; 1297 1298 // If the signed type can represent all values of the unsigned type, it 1299 // wins. Because we are dealing with 2's complement and types that are 1300 // powers of two larger than each other, this is always safe. 1301 return -1; 1302 } 1303 1304 // If the unsigned [RHS] type is larger, return it. 1305 if (RHSRank >= LHSRank) 1306 return -1; 1307 1308 // If the signed type can represent all values of the unsigned type, it 1309 // wins. Because we are dealing with 2's complement and types that are 1310 // powers of two larger than each other, this is always safe. 1311 return 1; 1312} 1313 1314// getCFConstantStringType - Return the type used for constant CFStrings. 1315QualType ASTContext::getCFConstantStringType() { 1316 if (!CFConstantStringTypeDecl) { 1317 CFConstantStringTypeDecl = 1318 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 1319 &Idents.get("NSConstantString"), 0); 1320 QualType FieldTypes[4]; 1321 1322 // const int *isa; 1323 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const)); 1324 // int flags; 1325 FieldTypes[1] = IntTy; 1326 // const char *str; 1327 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const)); 1328 // long length; 1329 FieldTypes[3] = LongTy; 1330 // Create fields 1331 FieldDecl *FieldDecls[4]; 1332 1333 for (unsigned i = 0; i < 4; ++i) 1334 FieldDecls[i] = FieldDecl::Create(*this, SourceLocation(), 0, 1335 FieldTypes[i]); 1336 1337 CFConstantStringTypeDecl->defineBody(FieldDecls, 4); 1338 } 1339 1340 return getTagDeclType(CFConstantStringTypeDecl); 1341} 1342 1343// This returns true if a type has been typedefed to BOOL: 1344// typedef <type> BOOL; 1345static bool isTypeTypedefedAsBOOL(QualType T) { 1346 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 1347 return !strcmp(TT->getDecl()->getName(), "BOOL"); 1348 1349 return false; 1350} 1351 1352/// getObjCEncodingTypeSize returns size of type for objective-c encoding 1353/// purpose. 1354int ASTContext::getObjCEncodingTypeSize(QualType type) { 1355 uint64_t sz = getTypeSize(type); 1356 1357 // Make all integer and enum types at least as large as an int 1358 if (sz > 0 && type->isIntegralType()) 1359 sz = std::max(sz, getTypeSize(IntTy)); 1360 // Treat arrays as pointers, since that's how they're passed in. 1361 else if (type->isArrayType()) 1362 sz = getTypeSize(VoidPtrTy); 1363 return sz / getTypeSize(CharTy); 1364} 1365 1366/// getObjCEncodingForMethodDecl - Return the encoded type for this method 1367/// declaration. 1368void ASTContext::getObjCEncodingForMethodDecl(ObjCMethodDecl *Decl, 1369 std::string& S) 1370{ 1371 // Encode type qualifer, 'in', 'inout', etc. for the return type. 1372 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 1373 // Encode result type. 1374 getObjCEncodingForType(Decl->getResultType(), S, EncodingRecordTypes); 1375 // Compute size of all parameters. 1376 // Start with computing size of a pointer in number of bytes. 1377 // FIXME: There might(should) be a better way of doing this computation! 1378 SourceLocation Loc; 1379 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy); 1380 // The first two arguments (self and _cmd) are pointers; account for 1381 // their size. 1382 int ParmOffset = 2 * PtrSize; 1383 int NumOfParams = Decl->getNumParams(); 1384 for (int i = 0; i < NumOfParams; i++) { 1385 QualType PType = Decl->getParamDecl(i)->getType(); 1386 int sz = getObjCEncodingTypeSize (PType); 1387 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type"); 1388 ParmOffset += sz; 1389 } 1390 S += llvm::utostr(ParmOffset); 1391 S += "@0:"; 1392 S += llvm::utostr(PtrSize); 1393 1394 // Argument types. 1395 ParmOffset = 2 * PtrSize; 1396 for (int i = 0; i < NumOfParams; i++) { 1397 QualType PType = Decl->getParamDecl(i)->getType(); 1398 // Process argument qualifiers for user supplied arguments; such as, 1399 // 'in', 'inout', etc. 1400 getObjCEncodingForTypeQualifier( 1401 Decl->getParamDecl(i)->getObjCDeclQualifier(), S); 1402 getObjCEncodingForType(PType, S, EncodingRecordTypes); 1403 S += llvm::utostr(ParmOffset); 1404 ParmOffset += getObjCEncodingTypeSize(PType); 1405 } 1406} 1407 1408void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 1409 llvm::SmallVector<const RecordType *, 8> &ERType) const { 1410 // FIXME: This currently doesn't encode: 1411 // @ An object (whether statically typed or typed id) 1412 // # A class object (Class) 1413 // : A method selector (SEL) 1414 // {name=type...} A structure 1415 // (name=type...) A union 1416 // bnum A bit field of num bits 1417 1418 if (const BuiltinType *BT = T->getAsBuiltinType()) { 1419 char encoding; 1420 switch (BT->getKind()) { 1421 default: assert(0 && "Unhandled builtin type kind"); 1422 case BuiltinType::Void: encoding = 'v'; break; 1423 case BuiltinType::Bool: encoding = 'B'; break; 1424 case BuiltinType::Char_U: 1425 case BuiltinType::UChar: encoding = 'C'; break; 1426 case BuiltinType::UShort: encoding = 'S'; break; 1427 case BuiltinType::UInt: encoding = 'I'; break; 1428 case BuiltinType::ULong: encoding = 'L'; break; 1429 case BuiltinType::ULongLong: encoding = 'Q'; break; 1430 case BuiltinType::Char_S: 1431 case BuiltinType::SChar: encoding = 'c'; break; 1432 case BuiltinType::Short: encoding = 's'; break; 1433 case BuiltinType::Int: encoding = 'i'; break; 1434 case BuiltinType::Long: encoding = 'l'; break; 1435 case BuiltinType::LongLong: encoding = 'q'; break; 1436 case BuiltinType::Float: encoding = 'f'; break; 1437 case BuiltinType::Double: encoding = 'd'; break; 1438 case BuiltinType::LongDouble: encoding = 'd'; break; 1439 } 1440 1441 S += encoding; 1442 } 1443 else if (T->isObjCQualifiedIdType()) { 1444 // Treat id<P...> same as 'id' for encoding purposes. 1445 return getObjCEncodingForType(getObjCIdType(), S, ERType); 1446 1447 } 1448 else if (const PointerType *PT = T->getAsPointerType()) { 1449 QualType PointeeTy = PT->getPointeeType(); 1450 if (isObjCIdType(PointeeTy) || PointeeTy->isObjCInterfaceType()) { 1451 S += '@'; 1452 return; 1453 } else if (isObjCClassType(PointeeTy)) { 1454 S += '#'; 1455 return; 1456 } else if (isObjCSelType(PointeeTy)) { 1457 S += ':'; 1458 return; 1459 } 1460 1461 if (PointeeTy->isCharType()) { 1462 // char pointer types should be encoded as '*' unless it is a 1463 // type that has been typedef'd to 'BOOL'. 1464 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 1465 S += '*'; 1466 return; 1467 } 1468 } 1469 1470 S += '^'; 1471 getObjCEncodingForType(PT->getPointeeType(), S, ERType); 1472 } else if (const ArrayType *AT = 1473 // Ignore type qualifiers etc. 1474 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 1475 S += '['; 1476 1477 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1478 S += llvm::utostr(CAT->getSize().getZExtValue()); 1479 else 1480 assert(0 && "Unhandled array type!"); 1481 1482 getObjCEncodingForType(AT->getElementType(), S, ERType); 1483 S += ']'; 1484 } else if (T->getAsFunctionType()) { 1485 S += '?'; 1486 } else if (const RecordType *RTy = T->getAsRecordType()) { 1487 RecordDecl *RDecl= RTy->getDecl(); 1488 // This mimics the behavior in gcc's encode_aggregate_within(). 1489 // The idea is to only inline structure definitions for top level pointers 1490 // to structures and embedded structures. 1491 bool inlining = (S.size() == 1 && S[0] == '^' || 1492 S.size() > 1 && S[S.size()-1] != '^'); 1493 S += '{'; 1494 S += RDecl->getName(); 1495 bool found = false; 1496 for (unsigned i = 0, e = ERType.size(); i != e; ++i) 1497 if (ERType[i] == RTy) { 1498 found = true; 1499 break; 1500 } 1501 if (!found && inlining) { 1502 ERType.push_back(RTy); 1503 S += '='; 1504 for (int i = 0; i < RDecl->getNumMembers(); i++) { 1505 FieldDecl *field = RDecl->getMember(i); 1506 getObjCEncodingForType(field->getType(), S, ERType); 1507 } 1508 assert(ERType.back() == RTy && "Record Type stack mismatch."); 1509 ERType.pop_back(); 1510 } 1511 S += '}'; 1512 } else if (T->isEnumeralType()) { 1513 S += 'i'; 1514 } else 1515 assert(0 && "@encode for type not implemented!"); 1516} 1517 1518void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 1519 std::string& S) const { 1520 if (QT & Decl::OBJC_TQ_In) 1521 S += 'n'; 1522 if (QT & Decl::OBJC_TQ_Inout) 1523 S += 'N'; 1524 if (QT & Decl::OBJC_TQ_Out) 1525 S += 'o'; 1526 if (QT & Decl::OBJC_TQ_Bycopy) 1527 S += 'O'; 1528 if (QT & Decl::OBJC_TQ_Byref) 1529 S += 'R'; 1530 if (QT & Decl::OBJC_TQ_Oneway) 1531 S += 'V'; 1532} 1533 1534void ASTContext::setBuiltinVaListType(QualType T) 1535{ 1536 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 1537 1538 BuiltinVaListType = T; 1539} 1540 1541void ASTContext::setObjCIdType(TypedefDecl *TD) 1542{ 1543 assert(ObjCIdType.isNull() && "'id' type already set!"); 1544 1545 ObjCIdType = getTypedefType(TD); 1546 1547 // typedef struct objc_object *id; 1548 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1549 assert(ptr && "'id' incorrectly typed"); 1550 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1551 assert(rec && "'id' incorrectly typed"); 1552 IdStructType = rec; 1553} 1554 1555void ASTContext::setObjCSelType(TypedefDecl *TD) 1556{ 1557 assert(ObjCSelType.isNull() && "'SEL' type already set!"); 1558 1559 ObjCSelType = getTypedefType(TD); 1560 1561 // typedef struct objc_selector *SEL; 1562 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1563 assert(ptr && "'SEL' incorrectly typed"); 1564 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1565 assert(rec && "'SEL' incorrectly typed"); 1566 SelStructType = rec; 1567} 1568 1569void ASTContext::setObjCProtoType(QualType QT) 1570{ 1571 assert(ObjCProtoType.isNull() && "'Protocol' type already set!"); 1572 ObjCProtoType = QT; 1573} 1574 1575void ASTContext::setObjCClassType(TypedefDecl *TD) 1576{ 1577 assert(ObjCClassType.isNull() && "'Class' type already set!"); 1578 1579 ObjCClassType = getTypedefType(TD); 1580 1581 // typedef struct objc_class *Class; 1582 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1583 assert(ptr && "'Class' incorrectly typed"); 1584 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1585 assert(rec && "'Class' incorrectly typed"); 1586 ClassStructType = rec; 1587} 1588 1589void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 1590 assert(ObjCConstantStringType.isNull() && 1591 "'NSConstantString' type already set!"); 1592 1593 ObjCConstantStringType = getObjCInterfaceType(Decl); 1594} 1595 1596 1597//===----------------------------------------------------------------------===// 1598// Type Predicates. 1599//===----------------------------------------------------------------------===// 1600 1601/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 1602/// to an object type. This includes "id" and "Class" (two 'special' pointers 1603/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 1604/// ID type). 1605bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 1606 if (Ty->isObjCQualifiedIdType()) 1607 return true; 1608 1609 if (!Ty->isPointerType()) 1610 return false; 1611 1612 // Check to see if this is 'id' or 'Class', both of which are typedefs for 1613 // pointer types. This looks for the typedef specifically, not for the 1614 // underlying type. 1615 if (Ty == getObjCIdType() || Ty == getObjCClassType()) 1616 return true; 1617 1618 // If this a pointer to an interface (e.g. NSString*), it is ok. 1619 return Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType(); 1620} 1621 1622//===----------------------------------------------------------------------===// 1623// Type Compatibility Testing 1624//===----------------------------------------------------------------------===// 1625 1626/// areCompatVectorTypes - Return true if the two specified vector types are 1627/// compatible. 1628static bool areCompatVectorTypes(const VectorType *LHS, 1629 const VectorType *RHS) { 1630 assert(LHS->isCanonical() && RHS->isCanonical()); 1631 return LHS->getElementType() == RHS->getElementType() && 1632 LHS->getNumElements() == RHS->getNumElements(); 1633} 1634 1635/// canAssignObjCInterfaces - Return true if the two interface types are 1636/// compatible for assignment from RHS to LHS. This handles validation of any 1637/// protocol qualifiers on the LHS or RHS. 1638/// 1639bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 1640 const ObjCInterfaceType *RHS) { 1641 // Verify that the base decls are compatible: the RHS must be a subclass of 1642 // the LHS. 1643 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 1644 return false; 1645 1646 // RHS must have a superset of the protocols in the LHS. If the LHS is not 1647 // protocol qualified at all, then we are good. 1648 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 1649 return true; 1650 1651 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 1652 // isn't a superset. 1653 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 1654 return true; // FIXME: should return false! 1655 1656 // Finally, we must have two protocol-qualified interfaces. 1657 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 1658 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 1659 ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(); 1660 ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end(); 1661 ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(); 1662 ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end(); 1663 1664 // All protocols in LHS must have a presence in RHS. Since the protocol lists 1665 // are both sorted alphabetically and have no duplicates, we can scan RHS and 1666 // LHS in a single parallel scan until we run out of elements in LHS. 1667 assert(LHSPI != LHSPE && "Empty LHS protocol list?"); 1668 ObjCProtocolDecl *LHSProto = *LHSPI; 1669 1670 while (RHSPI != RHSPE) { 1671 ObjCProtocolDecl *RHSProto = *RHSPI++; 1672 // If the RHS has a protocol that the LHS doesn't, ignore it. 1673 if (RHSProto != LHSProto) 1674 continue; 1675 1676 // Otherwise, the RHS does have this element. 1677 ++LHSPI; 1678 if (LHSPI == LHSPE) 1679 return true; // All protocols in LHS exist in RHS. 1680 1681 LHSProto = *LHSPI; 1682 } 1683 1684 // If we got here, we didn't find one of the LHS's protocols in the RHS list. 1685 return false; 1686} 1687 1688/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 1689/// both shall have the identically qualified version of a compatible type. 1690/// C99 6.2.7p1: Two types have compatible types if their types are the 1691/// same. See 6.7.[2,3,5] for additional rules. 1692bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 1693 return !mergeTypes(LHS, RHS).isNull(); 1694} 1695 1696QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) { 1697 const FunctionType *lbase = lhs->getAsFunctionType(); 1698 const FunctionType *rbase = rhs->getAsFunctionType(); 1699 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase); 1700 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase); 1701 bool allLTypes = true; 1702 bool allRTypes = true; 1703 1704 // Check return type 1705 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 1706 if (retType.isNull()) return QualType(); 1707 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) allLTypes = false; 1708 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) allRTypes = false; 1709 1710 if (lproto && rproto) { // two C99 style function prototypes 1711 unsigned lproto_nargs = lproto->getNumArgs(); 1712 unsigned rproto_nargs = rproto->getNumArgs(); 1713 1714 // Compatible functions must have the same number of arguments 1715 if (lproto_nargs != rproto_nargs) 1716 return QualType(); 1717 1718 // Variadic and non-variadic functions aren't compatible 1719 if (lproto->isVariadic() != rproto->isVariadic()) 1720 return QualType(); 1721 1722 // Check argument compatibility 1723 llvm::SmallVector<QualType, 10> types; 1724 for (unsigned i = 0; i < lproto_nargs; i++) { 1725 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 1726 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 1727 QualType argtype = mergeTypes(largtype, rargtype); 1728 if (argtype.isNull()) return QualType(); 1729 types.push_back(argtype); 1730 if (getCanonicalType(argtype) != getCanonicalType(largtype)) allLTypes = false; 1731 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) allRTypes = false; 1732 } 1733 if (allLTypes) return lhs; 1734 if (allRTypes) return rhs; 1735 return getFunctionType(retType, types.begin(), types.size(), 1736 lproto->isVariadic()); 1737 } 1738 1739 if (lproto) allRTypes = false; 1740 if (rproto) allLTypes = false; 1741 1742 const FunctionTypeProto *proto = lproto ? lproto : rproto; 1743 if (proto) { 1744 if (proto->isVariadic()) return QualType(); 1745 // Check that the types are compatible with the types that 1746 // would result from default argument promotions (C99 6.7.5.3p15). 1747 // The only types actually affected are promotable integer 1748 // types and floats, which would be passed as a different 1749 // type depending on whether the prototype is visible. 1750 unsigned proto_nargs = proto->getNumArgs(); 1751 for (unsigned i = 0; i < proto_nargs; ++i) { 1752 QualType argTy = proto->getArgType(i); 1753 if (argTy->isPromotableIntegerType() || 1754 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 1755 return QualType(); 1756 } 1757 1758 if (allLTypes) return lhs; 1759 if (allRTypes) return rhs; 1760 return getFunctionType(retType, proto->arg_type_begin(), 1761 proto->getNumArgs(), lproto->isVariadic()); 1762 } 1763 1764 if (allLTypes) return lhs; 1765 if (allRTypes) return rhs; 1766 return getFunctionTypeNoProto(retType); 1767} 1768 1769QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) { 1770 // C++ [expr]: If an expression initially has the type "reference to T", the 1771 // type is adjusted to "T" prior to any further analysis, the expression 1772 // designates the object or function denoted by the reference, and the 1773 // expression is an lvalue. 1774 // FIXME: C++ shouldn't be going through here! The rules are different 1775 // enough that they should be handled separately. 1776 if (const ReferenceType *RT = LHS->getAsReferenceType()) 1777 LHS = RT->getPointeeType(); 1778 if (const ReferenceType *RT = RHS->getAsReferenceType()) 1779 RHS = RT->getPointeeType(); 1780 1781 QualType LHSCan = getCanonicalType(LHS), 1782 RHSCan = getCanonicalType(RHS); 1783 1784 // If two types are identical, they are compatible. 1785 if (LHSCan == RHSCan) 1786 return LHS; 1787 1788 // If the qualifiers are different, the types aren't compatible 1789 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers() || 1790 LHSCan.getAddressSpace() != RHSCan.getAddressSpace()) 1791 return QualType(); 1792 1793 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 1794 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 1795 1796 // We want to consider the two function types to be the same for these 1797 // comparisons, just force one to the other. 1798 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 1799 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 1800 1801 // Same as above for arrays 1802 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 1803 LHSClass = Type::ConstantArray; 1804 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 1805 RHSClass = Type::ConstantArray; 1806 1807 // Canonicalize ExtVector -> Vector. 1808 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 1809 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 1810 1811 // Consider qualified interfaces and interfaces the same. 1812 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 1813 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 1814 1815 // If the canonical type classes don't match. 1816 if (LHSClass != RHSClass) { 1817 // ID is compatible with all qualified id types. 1818 if (LHS->isObjCQualifiedIdType()) { 1819 if (const PointerType *PT = RHS->getAsPointerType()) 1820 if (isObjCIdType(PT->getPointeeType())) 1821 return LHS; 1822 } 1823 if (RHS->isObjCQualifiedIdType()) { 1824 if (const PointerType *PT = LHS->getAsPointerType()) 1825 if (isObjCIdType(PT->getPointeeType())) 1826 return RHS; 1827 } 1828 1829 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 1830 // a signed integer type, or an unsigned integer type. 1831 if (const EnumType* ETy = LHS->getAsEnumType()) { 1832 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 1833 return RHS; 1834 } 1835 if (const EnumType* ETy = RHS->getAsEnumType()) { 1836 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 1837 return LHS; 1838 } 1839 1840 return QualType(); 1841 } 1842 1843 // The canonical type classes match. 1844 switch (LHSClass) { 1845 case Type::Pointer: 1846 { 1847 // Merge two pointer types, while trying to preserve typedef info 1848 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType(); 1849 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType(); 1850 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 1851 if (ResultType.isNull()) return QualType(); 1852 if (getCanonicalType(LHSPointee) != getCanonicalType(ResultType)) return LHS; 1853 if (getCanonicalType(RHSPointee) != getCanonicalType(ResultType)) return RHS; 1854 return getPointerType(ResultType); 1855 } 1856 case Type::ConstantArray: 1857 { 1858 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 1859 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 1860 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 1861 return QualType(); 1862 1863 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 1864 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 1865 QualType ResultType = mergeTypes(LHSElem, RHSElem); 1866 if (ResultType.isNull()) return QualType(); 1867 if (LCAT && getCanonicalType(LHSElem) != getCanonicalType(ResultType)) return LHS; 1868 if (RCAT && getCanonicalType(RHSElem) != getCanonicalType(ResultType)) return RHS; 1869 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 1870 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 1871 if (LVAT && getCanonicalType(LHSElem) != getCanonicalType(ResultType)) return LHS; 1872 if (RVAT && getCanonicalType(RHSElem) != getCanonicalType(ResultType)) return RHS; 1873 if (LVAT) { 1874 // FIXME: This isn't correct! But tricky to implement because 1875 // the array's size has to be the size of LHS, but the type 1876 // has to be different. 1877 return LHS; 1878 } 1879 if (RVAT) { 1880 // FIXME: This isn't correct! But tricky to implement because 1881 // the array's size has to be the size of RHS, but the type 1882 // has to be different. 1883 return RHS; 1884 } 1885 if (getCanonicalType(LHSElem) != getCanonicalType(ResultType)) return LHS; 1886 if (getCanonicalType(RHSElem) != getCanonicalType(ResultType)) return RHS; 1887 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(), 0); 1888 } 1889 case Type::FunctionNoProto: 1890 return mergeFunctionTypes(LHS, RHS); 1891 case Type::Tagged: 1892 { 1893 // FIXME: Why are these compatible? 1894 if (isObjCIdType(LHS) && isObjCClassType(RHS)) return LHS; 1895 if (isObjCClassType(LHS) && isObjCIdType(RHS)) return LHS; 1896 return QualType(); 1897 } 1898 case Type::Builtin: 1899 // Only exactly equal builtin types are compatible, which is tested above. 1900 return QualType(); 1901 case Type::Vector: 1902 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType())) 1903 return LHS; 1904 case Type::ObjCInterface: 1905 { 1906 // Distinct ObjC interfaces are not compatible; see canAssignObjCInterfaces 1907 // for checking assignment/comparison safety 1908 return QualType(); 1909 } 1910 default: 1911 assert(0 && "unexpected type"); 1912 return QualType(); 1913 } 1914} 1915 1916//===----------------------------------------------------------------------===// 1917// Integer Predicates 1918//===----------------------------------------------------------------------===// 1919unsigned ASTContext::getIntWidth(QualType T) { 1920 if (T == BoolTy) 1921 return 1; 1922 // At the moment, only bool has padding bits 1923 return (unsigned)getTypeSize(T); 1924} 1925 1926QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 1927 assert(T->isSignedIntegerType() && "Unexpected type"); 1928 if (const EnumType* ETy = T->getAsEnumType()) 1929 T = ETy->getDecl()->getIntegerType(); 1930 const BuiltinType* BTy = T->getAsBuiltinType(); 1931 assert (BTy && "Unexpected signed integer type"); 1932 switch (BTy->getKind()) { 1933 case BuiltinType::Char_S: 1934 case BuiltinType::SChar: 1935 return UnsignedCharTy; 1936 case BuiltinType::Short: 1937 return UnsignedShortTy; 1938 case BuiltinType::Int: 1939 return UnsignedIntTy; 1940 case BuiltinType::Long: 1941 return UnsignedLongTy; 1942 case BuiltinType::LongLong: 1943 return UnsignedLongLongTy; 1944 default: 1945 assert(0 && "Unexpected signed integer type"); 1946 return QualType(); 1947 } 1948} 1949 1950 1951//===----------------------------------------------------------------------===// 1952// Serialization Support 1953//===----------------------------------------------------------------------===// 1954 1955/// Emit - Serialize an ASTContext object to Bitcode. 1956void ASTContext::Emit(llvm::Serializer& S) const { 1957 S.Emit(LangOpts); 1958 S.EmitRef(SourceMgr); 1959 S.EmitRef(Target); 1960 S.EmitRef(Idents); 1961 S.EmitRef(Selectors); 1962 1963 // Emit the size of the type vector so that we can reserve that size 1964 // when we reconstitute the ASTContext object. 1965 S.EmitInt(Types.size()); 1966 1967 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end(); 1968 I!=E;++I) 1969 (*I)->Emit(S); 1970 1971 S.EmitOwnedPtr(TUDecl); 1972 1973 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl); 1974} 1975 1976ASTContext* ASTContext::Create(llvm::Deserializer& D) { 1977 1978 // Read the language options. 1979 LangOptions LOpts; 1980 LOpts.Read(D); 1981 1982 SourceManager &SM = D.ReadRef<SourceManager>(); 1983 TargetInfo &t = D.ReadRef<TargetInfo>(); 1984 IdentifierTable &idents = D.ReadRef<IdentifierTable>(); 1985 SelectorTable &sels = D.ReadRef<SelectorTable>(); 1986 1987 unsigned size_reserve = D.ReadInt(); 1988 1989 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels, size_reserve); 1990 1991 for (unsigned i = 0; i < size_reserve; ++i) 1992 Type::Create(*A,i,D); 1993 1994 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A)); 1995 1996 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>(); 1997 1998 return A; 1999} 2000