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