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