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