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