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