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