ASTContext.cpp revision 32442bbc98bafa512fa42d46fedf60ed7d79f574
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 S += '{'; 1489 S += RDecl->getName(); 1490 bool found = false; 1491 for (unsigned i = 0, e = ERType.size(); i != e; ++i) 1492 if (ERType[i] == RTy) { 1493 found = true; 1494 break; 1495 } 1496 if (!found) { 1497 ERType.push_back(RTy); 1498 S += '='; 1499 for (int i = 0; i < RDecl->getNumMembers(); i++) { 1500 FieldDecl *field = RDecl->getMember(i); 1501 getObjCEncodingForType(field->getType(), S, ERType); 1502 } 1503 assert(ERType.back() == RTy && "Record Type stack mismatch."); 1504 ERType.pop_back(); 1505 } 1506 S += '}'; 1507 } else if (T->isEnumeralType()) { 1508 S += 'i'; 1509 } else 1510 assert(0 && "@encode for type not implemented!"); 1511} 1512 1513void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 1514 std::string& S) const { 1515 if (QT & Decl::OBJC_TQ_In) 1516 S += 'n'; 1517 if (QT & Decl::OBJC_TQ_Inout) 1518 S += 'N'; 1519 if (QT & Decl::OBJC_TQ_Out) 1520 S += 'o'; 1521 if (QT & Decl::OBJC_TQ_Bycopy) 1522 S += 'O'; 1523 if (QT & Decl::OBJC_TQ_Byref) 1524 S += 'R'; 1525 if (QT & Decl::OBJC_TQ_Oneway) 1526 S += 'V'; 1527} 1528 1529void ASTContext::setBuiltinVaListType(QualType T) 1530{ 1531 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 1532 1533 BuiltinVaListType = T; 1534} 1535 1536void ASTContext::setObjCIdType(TypedefDecl *TD) 1537{ 1538 assert(ObjCIdType.isNull() && "'id' type already set!"); 1539 1540 ObjCIdType = getTypedefType(TD); 1541 1542 // typedef struct objc_object *id; 1543 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1544 assert(ptr && "'id' incorrectly typed"); 1545 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1546 assert(rec && "'id' incorrectly typed"); 1547 IdStructType = rec; 1548} 1549 1550void ASTContext::setObjCSelType(TypedefDecl *TD) 1551{ 1552 assert(ObjCSelType.isNull() && "'SEL' type already set!"); 1553 1554 ObjCSelType = getTypedefType(TD); 1555 1556 // typedef struct objc_selector *SEL; 1557 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1558 assert(ptr && "'SEL' incorrectly typed"); 1559 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1560 assert(rec && "'SEL' incorrectly typed"); 1561 SelStructType = rec; 1562} 1563 1564void ASTContext::setObjCProtoType(QualType QT) 1565{ 1566 assert(ObjCProtoType.isNull() && "'Protocol' type already set!"); 1567 ObjCProtoType = QT; 1568} 1569 1570void ASTContext::setObjCClassType(TypedefDecl *TD) 1571{ 1572 assert(ObjCClassType.isNull() && "'Class' type already set!"); 1573 1574 ObjCClassType = getTypedefType(TD); 1575 1576 // typedef struct objc_class *Class; 1577 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType(); 1578 assert(ptr && "'Class' incorrectly typed"); 1579 const RecordType *rec = ptr->getPointeeType()->getAsStructureType(); 1580 assert(rec && "'Class' incorrectly typed"); 1581 ClassStructType = rec; 1582} 1583 1584void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 1585 assert(ObjCConstantStringType.isNull() && 1586 "'NSConstantString' type already set!"); 1587 1588 ObjCConstantStringType = getObjCInterfaceType(Decl); 1589} 1590 1591 1592//===----------------------------------------------------------------------===// 1593// Type Predicates. 1594//===----------------------------------------------------------------------===// 1595 1596/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer 1597/// to an object type. This includes "id" and "Class" (two 'special' pointers 1598/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified 1599/// ID type). 1600bool ASTContext::isObjCObjectPointerType(QualType Ty) const { 1601 if (Ty->isObjCQualifiedIdType()) 1602 return true; 1603 1604 if (!Ty->isPointerType()) 1605 return false; 1606 1607 // Check to see if this is 'id' or 'Class', both of which are typedefs for 1608 // pointer types. This looks for the typedef specifically, not for the 1609 // underlying type. 1610 if (Ty == getObjCIdType() || Ty == getObjCClassType()) 1611 return true; 1612 1613 // If this a pointer to an interface (e.g. NSString*), it is ok. 1614 return Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType(); 1615} 1616 1617//===----------------------------------------------------------------------===// 1618// Type Compatibility Testing 1619//===----------------------------------------------------------------------===// 1620 1621/// C99 6.2.7p1: If both are complete types, then the following additional 1622/// requirements apply. 1623/// FIXME (handle compatibility across source files). 1624static bool areCompatTagTypes(TagType *LHS, TagType *RHS, 1625 const ASTContext &C) { 1626 // "Class" and "id" are compatible built-in structure types. 1627 if (C.isObjCIdType(QualType(LHS, 0)) && C.isObjCClassType(QualType(RHS, 0)) || 1628 C.isObjCClassType(QualType(LHS, 0)) && C.isObjCIdType(QualType(RHS, 0))) 1629 return true; 1630 1631 // Within a translation unit a tag type is only compatible with itself. Self 1632 // equality is already handled by the time we get here. 1633 assert(LHS != RHS && "Self equality not handled!"); 1634 return false; 1635} 1636 1637bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) { 1638 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be 1639 // identically qualified and both shall be pointers to compatible types. 1640 if (lhs.getCVRQualifiers() != rhs.getCVRQualifiers() || 1641 lhs.getAddressSpace() != rhs.getAddressSpace()) 1642 return false; 1643 1644 QualType ltype = lhs->getAsPointerType()->getPointeeType(); 1645 QualType rtype = rhs->getAsPointerType()->getPointeeType(); 1646 1647 return typesAreCompatible(ltype, rtype); 1648} 1649 1650bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) { 1651 const FunctionType *lbase = lhs->getAsFunctionType(); 1652 const FunctionType *rbase = rhs->getAsFunctionType(); 1653 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase); 1654 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase); 1655 1656 // first check the return types (common between C99 and K&R). 1657 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType())) 1658 return false; 1659 1660 if (lproto && rproto) { // two C99 style function prototypes 1661 unsigned lproto_nargs = lproto->getNumArgs(); 1662 unsigned rproto_nargs = rproto->getNumArgs(); 1663 1664 if (lproto_nargs != rproto_nargs) 1665 return false; 1666 1667 // both prototypes have the same number of arguments. 1668 if ((lproto->isVariadic() && !rproto->isVariadic()) || 1669 (rproto->isVariadic() && !lproto->isVariadic())) 1670 return false; 1671 1672 // The use of ellipsis agree...now check the argument types. 1673 for (unsigned i = 0; i < lproto_nargs; i++) 1674 // C99 6.7.5.3p15: ...and each parameter declared with qualified type 1675 // is taken as having the unqualified version of it's declared type. 1676 if (!typesAreCompatible(lproto->getArgType(i).getUnqualifiedType(), 1677 rproto->getArgType(i).getUnqualifiedType())) 1678 return false; 1679 return true; 1680 } 1681 1682 if (!lproto && !rproto) // two K&R style function decls, nothing to do. 1683 return true; 1684 1685 // we have a mixture of K&R style with C99 prototypes 1686 const FunctionTypeProto *proto = lproto ? lproto : rproto; 1687 if (proto->isVariadic()) 1688 return false; 1689 1690 // FIXME: Each parameter type T in the prototype must be compatible with the 1691 // type resulting from applying the usual argument conversions to T. 1692 return true; 1693} 1694 1695// C99 6.7.5.2p6 1696static bool areCompatArrayTypes(ArrayType *LHS, ArrayType *RHS, ASTContext &C) { 1697 // Constant arrays must be the same size to be compatible. 1698 if (const ConstantArrayType* LCAT = dyn_cast<ConstantArrayType>(LHS)) 1699 if (const ConstantArrayType* RCAT = dyn_cast<ConstantArrayType>(RHS)) 1700 if (RCAT->getSize() != LCAT->getSize()) 1701 return false; 1702 1703 // Compatible arrays must have compatible element types 1704 return C.typesAreCompatible(LHS->getElementType(), RHS->getElementType()); 1705} 1706 1707/// areCompatVectorTypes - Return true if the two specified vector types are 1708/// compatible. 1709static bool areCompatVectorTypes(const VectorType *LHS, 1710 const VectorType *RHS) { 1711 assert(LHS->isCanonical() && RHS->isCanonical()); 1712 return LHS->getElementType() == RHS->getElementType() && 1713 LHS->getNumElements() == RHS->getNumElements(); 1714} 1715 1716/// areCompatObjCInterfaces - Return true if the two interface types are 1717/// compatible for assignment from RHS to LHS. This handles validation of any 1718/// protocol qualifiers on the LHS or RHS. 1719/// 1720static bool areCompatObjCInterfaces(const ObjCInterfaceType *LHS, 1721 const ObjCInterfaceType *RHS) { 1722 // Verify that the base decls are compatible: the RHS must be a subclass of 1723 // the LHS. 1724 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 1725 return false; 1726 1727 // RHS must have a superset of the protocols in the LHS. If the LHS is not 1728 // protocol qualified at all, then we are good. 1729 if (!isa<ObjCQualifiedInterfaceType>(LHS)) 1730 return true; 1731 1732 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 1733 // isn't a superset. 1734 if (!isa<ObjCQualifiedInterfaceType>(RHS)) 1735 return true; // FIXME: should return false! 1736 1737 // Finally, we must have two protocol-qualified interfaces. 1738 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS); 1739 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS); 1740 ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(); 1741 ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end(); 1742 ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(); 1743 ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end(); 1744 1745 // All protocols in LHS must have a presence in RHS. Since the protocol lists 1746 // are both sorted alphabetically and have no duplicates, we can scan RHS and 1747 // LHS in a single parallel scan until we run out of elements in LHS. 1748 assert(LHSPI != LHSPE && "Empty LHS protocol list?"); 1749 ObjCProtocolDecl *LHSProto = *LHSPI; 1750 1751 while (RHSPI != RHSPE) { 1752 ObjCProtocolDecl *RHSProto = *RHSPI++; 1753 // If the RHS has a protocol that the LHS doesn't, ignore it. 1754 if (RHSProto != LHSProto) 1755 continue; 1756 1757 // Otherwise, the RHS does have this element. 1758 ++LHSPI; 1759 if (LHSPI == LHSPE) 1760 return true; // All protocols in LHS exist in RHS. 1761 1762 LHSProto = *LHSPI; 1763 } 1764 1765 // If we got here, we didn't find one of the LHS's protocols in the RHS list. 1766 return false; 1767} 1768 1769 1770/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 1771/// both shall have the identically qualified version of a compatible type. 1772/// C99 6.2.7p1: Two types have compatible types if their types are the 1773/// same. See 6.7.[2,3,5] for additional rules. 1774bool ASTContext::typesAreCompatible(QualType LHS_NC, QualType RHS_NC) { 1775 QualType LHS = getCanonicalType(LHS_NC); 1776 QualType RHS = getCanonicalType(RHS_NC); 1777 1778 // C++ [expr]: If an expression initially has the type "reference to T", the 1779 // type is adjusted to "T" prior to any further analysis, the expression 1780 // designates the object or function denoted by the reference, and the 1781 // expression is an lvalue. 1782 if (ReferenceType *RT = dyn_cast<ReferenceType>(LHS)) 1783 LHS = RT->getPointeeType(); 1784 if (ReferenceType *RT = dyn_cast<ReferenceType>(RHS)) 1785 RHS = RT->getPointeeType(); 1786 1787 // If two types are identical, they are compatible. 1788 if (LHS == RHS) 1789 return true; 1790 1791 // If qualifiers differ, the types are different. 1792 unsigned LHSAS = LHS.getAddressSpace(), RHSAS = RHS.getAddressSpace(); 1793 if (LHS.getCVRQualifiers() != RHS.getCVRQualifiers() || LHSAS != RHSAS) 1794 return false; 1795 1796 // Strip off ASQual's if present. 1797 if (LHSAS) { 1798 LHS = LHS.getUnqualifiedType(); 1799 RHS = RHS.getUnqualifiedType(); 1800 } 1801 1802 Type::TypeClass LHSClass = LHS->getTypeClass(); 1803 Type::TypeClass RHSClass = RHS->getTypeClass(); 1804 1805 // We want to consider the two function types to be the same for these 1806 // comparisons, just force one to the other. 1807 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 1808 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 1809 1810 // Same as above for arrays 1811 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 1812 LHSClass = Type::ConstantArray; 1813 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 1814 RHSClass = Type::ConstantArray; 1815 1816 // Canonicalize ExtVector -> Vector. 1817 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 1818 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 1819 1820 // Consider qualified interfaces and interfaces the same. 1821 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface; 1822 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface; 1823 1824 // If the canonical type classes don't match. 1825 if (LHSClass != RHSClass) { 1826 // ID is compatible with all interface types. 1827 if (isa<ObjCInterfaceType>(LHS)) 1828 return isObjCIdType(RHS); 1829 if (isa<ObjCInterfaceType>(RHS)) 1830 return isObjCIdType(LHS); 1831 1832 // ID is compatible with all qualified id types. 1833 if (isa<ObjCQualifiedIdType>(LHS)) { 1834 if (const PointerType *PT = RHS->getAsPointerType()) 1835 return isObjCIdType(PT->getPointeeType()); 1836 } 1837 if (isa<ObjCQualifiedIdType>(RHS)) { 1838 if (const PointerType *PT = LHS->getAsPointerType()) 1839 return isObjCIdType(PT->getPointeeType()); 1840 } 1841 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 1842 // a signed integer type, or an unsigned integer type. 1843 if (LHS->isEnumeralType() && RHS->isIntegralType()) { 1844 EnumDecl* EDecl = cast<EnumType>(LHS)->getDecl(); 1845 return EDecl->getIntegerType() == RHS; 1846 } 1847 if (RHS->isEnumeralType() && LHS->isIntegralType()) { 1848 EnumDecl* EDecl = cast<EnumType>(RHS)->getDecl(); 1849 return EDecl->getIntegerType() == LHS; 1850 } 1851 1852 return false; 1853 } 1854 1855 // The canonical type classes match. 1856 switch (LHSClass) { 1857 case Type::ASQual: 1858 case Type::FunctionProto: 1859 case Type::VariableArray: 1860 case Type::IncompleteArray: 1861 case Type::Reference: 1862 case Type::ObjCQualifiedInterface: 1863 assert(0 && "Canonicalized away above"); 1864 case Type::Pointer: 1865 return pointerTypesAreCompatible(LHS, RHS); 1866 case Type::ConstantArray: 1867 return areCompatArrayTypes(cast<ArrayType>(LHS), cast<ArrayType>(RHS), 1868 *this); 1869 case Type::FunctionNoProto: 1870 return functionTypesAreCompatible(LHS, RHS); 1871 case Type::Tagged: // handle structures, unions 1872 return areCompatTagTypes(cast<TagType>(LHS), cast<TagType>(RHS), *this); 1873 case Type::Builtin: 1874 // Only exactly equal builtin types are compatible, which is tested above. 1875 return false; 1876 case Type::Vector: 1877 return areCompatVectorTypes(cast<VectorType>(LHS), cast<VectorType>(RHS)); 1878 case Type::ObjCInterface: 1879 return areCompatObjCInterfaces(cast<ObjCInterfaceType>(LHS), 1880 cast<ObjCInterfaceType>(RHS)); 1881 default: 1882 assert(0 && "unexpected type"); 1883 } 1884 return true; // should never get here... 1885} 1886 1887//===----------------------------------------------------------------------===// 1888// Integer Predicates 1889//===----------------------------------------------------------------------===// 1890unsigned ASTContext::getIntWidth(QualType T) { 1891 if (T == BoolTy) 1892 return 1; 1893 // At the moment, only bool has padding bits 1894 return (unsigned)getTypeSize(T); 1895} 1896 1897QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 1898 assert(T->isSignedIntegerType() && "Unexpected type"); 1899 if (const EnumType* ETy = T->getAsEnumType()) 1900 T = ETy->getDecl()->getIntegerType(); 1901 const BuiltinType* BTy = T->getAsBuiltinType(); 1902 assert (BTy && "Unexpected signed integer type"); 1903 switch (BTy->getKind()) { 1904 case BuiltinType::Char_S: 1905 case BuiltinType::SChar: 1906 return UnsignedCharTy; 1907 case BuiltinType::Short: 1908 return UnsignedShortTy; 1909 case BuiltinType::Int: 1910 return UnsignedIntTy; 1911 case BuiltinType::Long: 1912 return UnsignedLongTy; 1913 case BuiltinType::LongLong: 1914 return UnsignedLongLongTy; 1915 default: 1916 assert(0 && "Unexpected signed integer type"); 1917 return QualType(); 1918 } 1919} 1920 1921 1922//===----------------------------------------------------------------------===// 1923// Serialization Support 1924//===----------------------------------------------------------------------===// 1925 1926/// Emit - Serialize an ASTContext object to Bitcode. 1927void ASTContext::Emit(llvm::Serializer& S) const { 1928 S.Emit(LangOpts); 1929 S.EmitRef(SourceMgr); 1930 S.EmitRef(Target); 1931 S.EmitRef(Idents); 1932 S.EmitRef(Selectors); 1933 1934 // Emit the size of the type vector so that we can reserve that size 1935 // when we reconstitute the ASTContext object. 1936 S.EmitInt(Types.size()); 1937 1938 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end(); 1939 I!=E;++I) 1940 (*I)->Emit(S); 1941 1942 S.EmitOwnedPtr(TUDecl); 1943 1944 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl); 1945} 1946 1947ASTContext* ASTContext::Create(llvm::Deserializer& D) { 1948 1949 // Read the language options. 1950 LangOptions LOpts; 1951 LOpts.Read(D); 1952 1953 SourceManager &SM = D.ReadRef<SourceManager>(); 1954 TargetInfo &t = D.ReadRef<TargetInfo>(); 1955 IdentifierTable &idents = D.ReadRef<IdentifierTable>(); 1956 SelectorTable &sels = D.ReadRef<SelectorTable>(); 1957 1958 unsigned size_reserve = D.ReadInt(); 1959 1960 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels, size_reserve); 1961 1962 for (unsigned i = 0; i < size_reserve; ++i) 1963 Type::Create(*A,i,D); 1964 1965 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A)); 1966 1967 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>(); 1968 1969 return A; 1970} 1971