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