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