ASTContext.cpp revision aa0cd85838f2a024e589ea4e8c2094130065af21
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/ExprCXX.h" 22#include "clang/AST/ExternalASTSource.h" 23#include "clang/AST/ASTMutationListener.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/Mangle.h" 26#include "clang/Basic/Builtins.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/SmallString.h" 30#include "llvm/ADT/StringExtras.h" 31#include "llvm/Support/MathExtras.h" 32#include "llvm/Support/raw_ostream.h" 33#include "llvm/Support/Capacity.h" 34#include "CXXABI.h" 35#include <map> 36 37using namespace clang; 38 39unsigned ASTContext::NumImplicitDefaultConstructors; 40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 41unsigned ASTContext::NumImplicitCopyConstructors; 42unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 43unsigned ASTContext::NumImplicitMoveConstructors; 44unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 45unsigned ASTContext::NumImplicitCopyAssignmentOperators; 46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 47unsigned ASTContext::NumImplicitMoveAssignmentOperators; 48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 49unsigned ASTContext::NumImplicitDestructors; 50unsigned ASTContext::NumImplicitDestructorsDeclared; 51 52enum FloatingRank { 53 HalfRank, FloatRank, DoubleRank, LongDoubleRank 54}; 55 56const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 57 if (!CommentsLoaded && ExternalSource) { 58 ExternalSource->ReadComments(); 59 CommentsLoaded = true; 60 } 61 62 assert(D); 63 64 // TODO: handle comments for function parameters properly. 65 if (isa<ParmVarDecl>(D)) 66 return NULL; 67 68 ArrayRef<RawComment> RawComments = Comments.getComments(); 69 70 // If there are no comments anywhere, we won't find anything. 71 if (RawComments.empty()) 72 return NULL; 73 74 // If the declaration doesn't map directly to a location in a file, we 75 // can't find the comment. 76 SourceLocation DeclLoc = D->getLocation(); 77 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 78 return NULL; 79 80 // Find the comment that occurs just after this declaration. 81 ArrayRef<RawComment>::iterator Comment 82 = std::lower_bound(RawComments.begin(), 83 RawComments.end(), 84 SourceRange(DeclLoc), 85 BeforeThanCompare<RawComment>(SourceMgr)); 86 87 // Decompose the location for the declaration and find the beginning of the 88 // file buffer. 89 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 90 91 // First check whether we have a trailing comment. 92 if (Comment != RawComments.end() && 93 Comment->isDoxygen() && Comment->isTrailingComment() && 94 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) { 95 std::pair<FileID, unsigned> CommentBeginDecomp 96 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin()); 97 // Check that Doxygen trailing comment comes after the declaration, starts 98 // on the same line and in the same file as the declaration. 99 if (DeclLocDecomp.first == CommentBeginDecomp.first && 100 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 101 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 102 CommentBeginDecomp.second)) { 103 return &*Comment; 104 } 105 } 106 107 // The comment just after the declaration was not a trailing comment. 108 // Let's look at the previous comment. 109 if (Comment == RawComments.begin()) 110 return NULL; 111 --Comment; 112 113 // Check that we actually have a non-member Doxygen comment. 114 if (!Comment->isDoxygen() || Comment->isTrailingComment()) 115 return NULL; 116 117 // Decompose the end of the comment. 118 std::pair<FileID, unsigned> CommentEndDecomp 119 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd()); 120 121 // If the comment and the declaration aren't in the same file, then they 122 // aren't related. 123 if (DeclLocDecomp.first != CommentEndDecomp.first) 124 return NULL; 125 126 // Get the corresponding buffer. 127 bool Invalid = false; 128 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 129 &Invalid).data(); 130 if (Invalid) 131 return NULL; 132 133 // Extract text between the comment and declaration. 134 StringRef Text(Buffer + CommentEndDecomp.second, 135 DeclLocDecomp.second - CommentEndDecomp.second); 136 137 // There should be no other declarations between comment and declaration. 138 if (Text.find_first_of(",;{}") != StringRef::npos) 139 return NULL; 140 141 return &*Comment; 142} 143 144const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const { 145 // Check whether we have cached a comment string for this declaration 146 // already. 147 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos 148 = DeclComments.find(D); 149 if (Pos != DeclComments.end()) 150 return Pos->second; 151 152 const RawComment *RC = getRawCommentForDeclNoCache(D); 153 DeclComments[D] = RC; 154 return RC; 155} 156 157void 158ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 159 TemplateTemplateParmDecl *Parm) { 160 ID.AddInteger(Parm->getDepth()); 161 ID.AddInteger(Parm->getPosition()); 162 ID.AddBoolean(Parm->isParameterPack()); 163 164 TemplateParameterList *Params = Parm->getTemplateParameters(); 165 ID.AddInteger(Params->size()); 166 for (TemplateParameterList::const_iterator P = Params->begin(), 167 PEnd = Params->end(); 168 P != PEnd; ++P) { 169 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 170 ID.AddInteger(0); 171 ID.AddBoolean(TTP->isParameterPack()); 172 continue; 173 } 174 175 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 176 ID.AddInteger(1); 177 ID.AddBoolean(NTTP->isParameterPack()); 178 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 179 if (NTTP->isExpandedParameterPack()) { 180 ID.AddBoolean(true); 181 ID.AddInteger(NTTP->getNumExpansionTypes()); 182 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 183 QualType T = NTTP->getExpansionType(I); 184 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 185 } 186 } else 187 ID.AddBoolean(false); 188 continue; 189 } 190 191 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 192 ID.AddInteger(2); 193 Profile(ID, TTP); 194 } 195} 196 197TemplateTemplateParmDecl * 198ASTContext::getCanonicalTemplateTemplateParmDecl( 199 TemplateTemplateParmDecl *TTP) const { 200 // Check if we already have a canonical template template parameter. 201 llvm::FoldingSetNodeID ID; 202 CanonicalTemplateTemplateParm::Profile(ID, TTP); 203 void *InsertPos = 0; 204 CanonicalTemplateTemplateParm *Canonical 205 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 206 if (Canonical) 207 return Canonical->getParam(); 208 209 // Build a canonical template parameter list. 210 TemplateParameterList *Params = TTP->getTemplateParameters(); 211 SmallVector<NamedDecl *, 4> CanonParams; 212 CanonParams.reserve(Params->size()); 213 for (TemplateParameterList::const_iterator P = Params->begin(), 214 PEnd = Params->end(); 215 P != PEnd; ++P) { 216 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 217 CanonParams.push_back( 218 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 219 SourceLocation(), 220 SourceLocation(), 221 TTP->getDepth(), 222 TTP->getIndex(), 0, false, 223 TTP->isParameterPack())); 224 else if (NonTypeTemplateParmDecl *NTTP 225 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 226 QualType T = getCanonicalType(NTTP->getType()); 227 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 228 NonTypeTemplateParmDecl *Param; 229 if (NTTP->isExpandedParameterPack()) { 230 SmallVector<QualType, 2> ExpandedTypes; 231 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 232 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 233 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 234 ExpandedTInfos.push_back( 235 getTrivialTypeSourceInfo(ExpandedTypes.back())); 236 } 237 238 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 239 SourceLocation(), 240 SourceLocation(), 241 NTTP->getDepth(), 242 NTTP->getPosition(), 0, 243 T, 244 TInfo, 245 ExpandedTypes.data(), 246 ExpandedTypes.size(), 247 ExpandedTInfos.data()); 248 } else { 249 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 250 SourceLocation(), 251 SourceLocation(), 252 NTTP->getDepth(), 253 NTTP->getPosition(), 0, 254 T, 255 NTTP->isParameterPack(), 256 TInfo); 257 } 258 CanonParams.push_back(Param); 259 260 } else 261 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 262 cast<TemplateTemplateParmDecl>(*P))); 263 } 264 265 TemplateTemplateParmDecl *CanonTTP 266 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 267 SourceLocation(), TTP->getDepth(), 268 TTP->getPosition(), 269 TTP->isParameterPack(), 270 0, 271 TemplateParameterList::Create(*this, SourceLocation(), 272 SourceLocation(), 273 CanonParams.data(), 274 CanonParams.size(), 275 SourceLocation())); 276 277 // Get the new insert position for the node we care about. 278 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 279 assert(Canonical == 0 && "Shouldn't be in the map!"); 280 (void)Canonical; 281 282 // Create the canonical template template parameter entry. 283 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 284 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 285 return CanonTTP; 286} 287 288CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 289 if (!LangOpts.CPlusPlus) return 0; 290 291 switch (T.getCXXABI()) { 292 case CXXABI_ARM: 293 return CreateARMCXXABI(*this); 294 case CXXABI_Itanium: 295 return CreateItaniumCXXABI(*this); 296 case CXXABI_Microsoft: 297 return CreateMicrosoftCXXABI(*this); 298 } 299 llvm_unreachable("Invalid CXXABI type!"); 300} 301 302static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 303 const LangOptions &LOpts) { 304 if (LOpts.FakeAddressSpaceMap) { 305 // The fake address space map must have a distinct entry for each 306 // language-specific address space. 307 static const unsigned FakeAddrSpaceMap[] = { 308 1, // opencl_global 309 2, // opencl_local 310 3, // opencl_constant 311 4, // cuda_device 312 5, // cuda_constant 313 6 // cuda_shared 314 }; 315 return &FakeAddrSpaceMap; 316 } else { 317 return &T.getAddressSpaceMap(); 318 } 319} 320 321ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 322 const TargetInfo *t, 323 IdentifierTable &idents, SelectorTable &sels, 324 Builtin::Context &builtins, 325 unsigned size_reserve, 326 bool DelayInitialization) 327 : FunctionProtoTypes(this_()), 328 TemplateSpecializationTypes(this_()), 329 DependentTemplateSpecializationTypes(this_()), 330 SubstTemplateTemplateParmPacks(this_()), 331 GlobalNestedNameSpecifier(0), 332 Int128Decl(0), UInt128Decl(0), 333 BuiltinVaListDecl(0), 334 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0), 335 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0), 336 FILEDecl(0), 337 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0), 338 BlockDescriptorType(0), BlockDescriptorExtendedType(0), 339 cudaConfigureCallDecl(0), 340 NullTypeSourceInfo(QualType()), 341 FirstLocalImport(), LastLocalImport(), 342 SourceMgr(SM), LangOpts(LOpts), 343 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts), 344 Idents(idents), Selectors(sels), 345 BuiltinInfo(builtins), 346 DeclarationNames(*this), 347 ExternalSource(0), Listener(0), 348 Comments(SM), CommentsLoaded(false), 349 LastSDM(0, 0), 350 UniqueBlockByRefTypeID(0) 351{ 352 if (size_reserve > 0) Types.reserve(size_reserve); 353 TUDecl = TranslationUnitDecl::Create(*this); 354 355 if (!DelayInitialization) { 356 assert(t && "No target supplied for ASTContext initialization"); 357 InitBuiltinTypes(*t); 358 } 359} 360 361ASTContext::~ASTContext() { 362 // Release the DenseMaps associated with DeclContext objects. 363 // FIXME: Is this the ideal solution? 364 ReleaseDeclContextMaps(); 365 366 // Call all of the deallocation functions. 367 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 368 Deallocations[I].first(Deallocations[I].second); 369 370 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 371 // because they can contain DenseMaps. 372 for (llvm::DenseMap<const ObjCContainerDecl*, 373 const ASTRecordLayout*>::iterator 374 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 375 // Increment in loop to prevent using deallocated memory. 376 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 377 R->Destroy(*this); 378 379 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 380 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 381 // Increment in loop to prevent using deallocated memory. 382 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 383 R->Destroy(*this); 384 } 385 386 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 387 AEnd = DeclAttrs.end(); 388 A != AEnd; ++A) 389 A->second->~AttrVec(); 390} 391 392void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 393 Deallocations.push_back(std::make_pair(Callback, Data)); 394} 395 396void 397ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) { 398 ExternalSource.reset(Source.take()); 399} 400 401void ASTContext::PrintStats() const { 402 llvm::errs() << "\n*** AST Context Stats:\n"; 403 llvm::errs() << " " << Types.size() << " types total.\n"; 404 405 unsigned counts[] = { 406#define TYPE(Name, Parent) 0, 407#define ABSTRACT_TYPE(Name, Parent) 408#include "clang/AST/TypeNodes.def" 409 0 // Extra 410 }; 411 412 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 413 Type *T = Types[i]; 414 counts[(unsigned)T->getTypeClass()]++; 415 } 416 417 unsigned Idx = 0; 418 unsigned TotalBytes = 0; 419#define TYPE(Name, Parent) \ 420 if (counts[Idx]) \ 421 llvm::errs() << " " << counts[Idx] << " " << #Name \ 422 << " types\n"; \ 423 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 424 ++Idx; 425#define ABSTRACT_TYPE(Name, Parent) 426#include "clang/AST/TypeNodes.def" 427 428 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 429 430 // Implicit special member functions. 431 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 432 << NumImplicitDefaultConstructors 433 << " implicit default constructors created\n"; 434 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 435 << NumImplicitCopyConstructors 436 << " implicit copy constructors created\n"; 437 if (getLangOpts().CPlusPlus) 438 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 439 << NumImplicitMoveConstructors 440 << " implicit move constructors created\n"; 441 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 442 << NumImplicitCopyAssignmentOperators 443 << " implicit copy assignment operators created\n"; 444 if (getLangOpts().CPlusPlus) 445 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 446 << NumImplicitMoveAssignmentOperators 447 << " implicit move assignment operators created\n"; 448 llvm::errs() << NumImplicitDestructorsDeclared << "/" 449 << NumImplicitDestructors 450 << " implicit destructors created\n"; 451 452 if (ExternalSource.get()) { 453 llvm::errs() << "\n"; 454 ExternalSource->PrintStats(); 455 } 456 457 BumpAlloc.PrintStats(); 458} 459 460TypedefDecl *ASTContext::getInt128Decl() const { 461 if (!Int128Decl) { 462 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty); 463 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 464 getTranslationUnitDecl(), 465 SourceLocation(), 466 SourceLocation(), 467 &Idents.get("__int128_t"), 468 TInfo); 469 } 470 471 return Int128Decl; 472} 473 474TypedefDecl *ASTContext::getUInt128Decl() const { 475 if (!UInt128Decl) { 476 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty); 477 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 478 getTranslationUnitDecl(), 479 SourceLocation(), 480 SourceLocation(), 481 &Idents.get("__uint128_t"), 482 TInfo); 483 } 484 485 return UInt128Decl; 486} 487 488void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 489 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 490 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 491 Types.push_back(Ty); 492} 493 494void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 495 assert((!this->Target || this->Target == &Target) && 496 "Incorrect target reinitialization"); 497 assert(VoidTy.isNull() && "Context reinitialized?"); 498 499 this->Target = &Target; 500 501 ABI.reset(createCXXABI(Target)); 502 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 503 504 // C99 6.2.5p19. 505 InitBuiltinType(VoidTy, BuiltinType::Void); 506 507 // C99 6.2.5p2. 508 InitBuiltinType(BoolTy, BuiltinType::Bool); 509 // C99 6.2.5p3. 510 if (LangOpts.CharIsSigned) 511 InitBuiltinType(CharTy, BuiltinType::Char_S); 512 else 513 InitBuiltinType(CharTy, BuiltinType::Char_U); 514 // C99 6.2.5p4. 515 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 516 InitBuiltinType(ShortTy, BuiltinType::Short); 517 InitBuiltinType(IntTy, BuiltinType::Int); 518 InitBuiltinType(LongTy, BuiltinType::Long); 519 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 520 521 // C99 6.2.5p6. 522 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 523 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 524 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 525 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 526 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 527 528 // C99 6.2.5p10. 529 InitBuiltinType(FloatTy, BuiltinType::Float); 530 InitBuiltinType(DoubleTy, BuiltinType::Double); 531 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 532 533 // GNU extension, 128-bit integers. 534 InitBuiltinType(Int128Ty, BuiltinType::Int128); 535 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 536 537 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5 538 if (TargetInfo::isTypeSigned(Target.getWCharType())) 539 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 540 else // -fshort-wchar makes wchar_t be unsigned. 541 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 542 } else // C99 543 WCharTy = getFromTargetType(Target.getWCharType()); 544 545 WIntTy = getFromTargetType(Target.getWIntType()); 546 547 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 548 InitBuiltinType(Char16Ty, BuiltinType::Char16); 549 else // C99 550 Char16Ty = getFromTargetType(Target.getChar16Type()); 551 552 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 553 InitBuiltinType(Char32Ty, BuiltinType::Char32); 554 else // C99 555 Char32Ty = getFromTargetType(Target.getChar32Type()); 556 557 // Placeholder type for type-dependent expressions whose type is 558 // completely unknown. No code should ever check a type against 559 // DependentTy and users should never see it; however, it is here to 560 // help diagnose failures to properly check for type-dependent 561 // expressions. 562 InitBuiltinType(DependentTy, BuiltinType::Dependent); 563 564 // Placeholder type for functions. 565 InitBuiltinType(OverloadTy, BuiltinType::Overload); 566 567 // Placeholder type for bound members. 568 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 569 570 // Placeholder type for pseudo-objects. 571 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 572 573 // "any" type; useful for debugger-like clients. 574 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 575 576 // Placeholder type for unbridged ARC casts. 577 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 578 579 // C99 6.2.5p11. 580 FloatComplexTy = getComplexType(FloatTy); 581 DoubleComplexTy = getComplexType(DoubleTy); 582 LongDoubleComplexTy = getComplexType(LongDoubleTy); 583 584 // Builtin types for 'id', 'Class', and 'SEL'. 585 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 586 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 587 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 588 589 // Builtin type for __objc_yes and __objc_no 590 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 591 SignedCharTy : BoolTy); 592 593 ObjCConstantStringType = QualType(); 594 595 // void * type 596 VoidPtrTy = getPointerType(VoidTy); 597 598 // nullptr type (C++0x 2.14.7) 599 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 600 601 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 602 InitBuiltinType(HalfTy, BuiltinType::Half); 603} 604 605DiagnosticsEngine &ASTContext::getDiagnostics() const { 606 return SourceMgr.getDiagnostics(); 607} 608 609AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 610 AttrVec *&Result = DeclAttrs[D]; 611 if (!Result) { 612 void *Mem = Allocate(sizeof(AttrVec)); 613 Result = new (Mem) AttrVec; 614 } 615 616 return *Result; 617} 618 619/// \brief Erase the attributes corresponding to the given declaration. 620void ASTContext::eraseDeclAttrs(const Decl *D) { 621 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 622 if (Pos != DeclAttrs.end()) { 623 Pos->second->~AttrVec(); 624 DeclAttrs.erase(Pos); 625 } 626} 627 628MemberSpecializationInfo * 629ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 630 assert(Var->isStaticDataMember() && "Not a static data member"); 631 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 632 = InstantiatedFromStaticDataMember.find(Var); 633 if (Pos == InstantiatedFromStaticDataMember.end()) 634 return 0; 635 636 return Pos->second; 637} 638 639void 640ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 641 TemplateSpecializationKind TSK, 642 SourceLocation PointOfInstantiation) { 643 assert(Inst->isStaticDataMember() && "Not a static data member"); 644 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 645 assert(!InstantiatedFromStaticDataMember[Inst] && 646 "Already noted what static data member was instantiated from"); 647 InstantiatedFromStaticDataMember[Inst] 648 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 649} 650 651FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 652 const FunctionDecl *FD){ 653 assert(FD && "Specialization is 0"); 654 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 655 = ClassScopeSpecializationPattern.find(FD); 656 if (Pos == ClassScopeSpecializationPattern.end()) 657 return 0; 658 659 return Pos->second; 660} 661 662void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 663 FunctionDecl *Pattern) { 664 assert(FD && "Specialization is 0"); 665 assert(Pattern && "Class scope specialization pattern is 0"); 666 ClassScopeSpecializationPattern[FD] = Pattern; 667} 668 669NamedDecl * 670ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 671 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 672 = InstantiatedFromUsingDecl.find(UUD); 673 if (Pos == InstantiatedFromUsingDecl.end()) 674 return 0; 675 676 return Pos->second; 677} 678 679void 680ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 681 assert((isa<UsingDecl>(Pattern) || 682 isa<UnresolvedUsingValueDecl>(Pattern) || 683 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 684 "pattern decl is not a using decl"); 685 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 686 InstantiatedFromUsingDecl[Inst] = Pattern; 687} 688 689UsingShadowDecl * 690ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 691 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 692 = InstantiatedFromUsingShadowDecl.find(Inst); 693 if (Pos == InstantiatedFromUsingShadowDecl.end()) 694 return 0; 695 696 return Pos->second; 697} 698 699void 700ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 701 UsingShadowDecl *Pattern) { 702 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 703 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 704} 705 706FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 707 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 708 = InstantiatedFromUnnamedFieldDecl.find(Field); 709 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 710 return 0; 711 712 return Pos->second; 713} 714 715void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 716 FieldDecl *Tmpl) { 717 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 718 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 719 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 720 "Already noted what unnamed field was instantiated from"); 721 722 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 723} 724 725bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 726 const FieldDecl *LastFD) const { 727 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 728 FD->getBitWidthValue(*this) == 0); 729} 730 731bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD, 732 const FieldDecl *LastFD) const { 733 return (FD->isBitField() && LastFD && LastFD->isBitField() && 734 FD->getBitWidthValue(*this) == 0 && 735 LastFD->getBitWidthValue(*this) != 0); 736} 737 738bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD, 739 const FieldDecl *LastFD) const { 740 return (FD->isBitField() && LastFD && LastFD->isBitField() && 741 FD->getBitWidthValue(*this) && 742 LastFD->getBitWidthValue(*this)); 743} 744 745bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD, 746 const FieldDecl *LastFD) const { 747 return (!FD->isBitField() && LastFD && LastFD->isBitField() && 748 LastFD->getBitWidthValue(*this)); 749} 750 751bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD, 752 const FieldDecl *LastFD) const { 753 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 754 FD->getBitWidthValue(*this)); 755} 756 757ASTContext::overridden_cxx_method_iterator 758ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 759 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 760 = OverriddenMethods.find(Method); 761 if (Pos == OverriddenMethods.end()) 762 return 0; 763 764 return Pos->second.begin(); 765} 766 767ASTContext::overridden_cxx_method_iterator 768ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 769 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 770 = OverriddenMethods.find(Method); 771 if (Pos == OverriddenMethods.end()) 772 return 0; 773 774 return Pos->second.end(); 775} 776 777unsigned 778ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 779 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 780 = OverriddenMethods.find(Method); 781 if (Pos == OverriddenMethods.end()) 782 return 0; 783 784 return Pos->second.size(); 785} 786 787void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 788 const CXXMethodDecl *Overridden) { 789 OverriddenMethods[Method].push_back(Overridden); 790} 791 792void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 793 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 794 assert(!Import->isFromASTFile() && "Non-local import declaration"); 795 if (!FirstLocalImport) { 796 FirstLocalImport = Import; 797 LastLocalImport = Import; 798 return; 799 } 800 801 LastLocalImport->NextLocalImport = Import; 802 LastLocalImport = Import; 803} 804 805//===----------------------------------------------------------------------===// 806// Type Sizing and Analysis 807//===----------------------------------------------------------------------===// 808 809/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 810/// scalar floating point type. 811const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 812 const BuiltinType *BT = T->getAs<BuiltinType>(); 813 assert(BT && "Not a floating point type!"); 814 switch (BT->getKind()) { 815 default: llvm_unreachable("Not a floating point type!"); 816 case BuiltinType::Half: return Target->getHalfFormat(); 817 case BuiltinType::Float: return Target->getFloatFormat(); 818 case BuiltinType::Double: return Target->getDoubleFormat(); 819 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 820 } 821} 822 823/// getDeclAlign - Return a conservative estimate of the alignment of the 824/// specified decl. Note that bitfields do not have a valid alignment, so 825/// this method will assert on them. 826/// If @p RefAsPointee, references are treated like their underlying type 827/// (for alignof), else they're treated like pointers (for CodeGen). 828CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const { 829 unsigned Align = Target->getCharWidth(); 830 831 bool UseAlignAttrOnly = false; 832 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 833 Align = AlignFromAttr; 834 835 // __attribute__((aligned)) can increase or decrease alignment 836 // *except* on a struct or struct member, where it only increases 837 // alignment unless 'packed' is also specified. 838 // 839 // It is an error for alignas to decrease alignment, so we can 840 // ignore that possibility; Sema should diagnose it. 841 if (isa<FieldDecl>(D)) { 842 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 843 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 844 } else { 845 UseAlignAttrOnly = true; 846 } 847 } 848 else if (isa<FieldDecl>(D)) 849 UseAlignAttrOnly = 850 D->hasAttr<PackedAttr>() || 851 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 852 853 // If we're using the align attribute only, just ignore everything 854 // else about the declaration and its type. 855 if (UseAlignAttrOnly) { 856 // do nothing 857 858 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 859 QualType T = VD->getType(); 860 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 861 if (RefAsPointee) 862 T = RT->getPointeeType(); 863 else 864 T = getPointerType(RT->getPointeeType()); 865 } 866 if (!T->isIncompleteType() && !T->isFunctionType()) { 867 // Adjust alignments of declarations with array type by the 868 // large-array alignment on the target. 869 unsigned MinWidth = Target->getLargeArrayMinWidth(); 870 const ArrayType *arrayType; 871 if (MinWidth && (arrayType = getAsArrayType(T))) { 872 if (isa<VariableArrayType>(arrayType)) 873 Align = std::max(Align, Target->getLargeArrayAlign()); 874 else if (isa<ConstantArrayType>(arrayType) && 875 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 876 Align = std::max(Align, Target->getLargeArrayAlign()); 877 878 // Walk through any array types while we're at it. 879 T = getBaseElementType(arrayType); 880 } 881 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 882 } 883 884 // Fields can be subject to extra alignment constraints, like if 885 // the field is packed, the struct is packed, or the struct has a 886 // a max-field-alignment constraint (#pragma pack). So calculate 887 // the actual alignment of the field within the struct, and then 888 // (as we're expected to) constrain that by the alignment of the type. 889 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) { 890 // So calculate the alignment of the field. 891 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent()); 892 893 // Start with the record's overall alignment. 894 unsigned fieldAlign = toBits(layout.getAlignment()); 895 896 // Use the GCD of that and the offset within the record. 897 uint64_t offset = layout.getFieldOffset(field->getFieldIndex()); 898 if (offset > 0) { 899 // Alignment is always a power of 2, so the GCD will be a power of 2, 900 // which means we get to do this crazy thing instead of Euclid's. 901 uint64_t lowBitOfOffset = offset & (~offset + 1); 902 if (lowBitOfOffset < fieldAlign) 903 fieldAlign = static_cast<unsigned>(lowBitOfOffset); 904 } 905 906 Align = std::min(Align, fieldAlign); 907 } 908 } 909 910 return toCharUnitsFromBits(Align); 911} 912 913std::pair<CharUnits, CharUnits> 914ASTContext::getTypeInfoInChars(const Type *T) const { 915 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 916 return std::make_pair(toCharUnitsFromBits(Info.first), 917 toCharUnitsFromBits(Info.second)); 918} 919 920std::pair<CharUnits, CharUnits> 921ASTContext::getTypeInfoInChars(QualType T) const { 922 return getTypeInfoInChars(T.getTypePtr()); 923} 924 925std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const { 926 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T); 927 if (it != MemoizedTypeInfo.end()) 928 return it->second; 929 930 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T); 931 MemoizedTypeInfo.insert(std::make_pair(T, Info)); 932 return Info; 933} 934 935/// getTypeInfoImpl - Return the size of the specified type, in bits. This 936/// method does not work on incomplete types. 937/// 938/// FIXME: Pointers into different addr spaces could have different sizes and 939/// alignment requirements: getPointerInfo should take an AddrSpace, this 940/// should take a QualType, &c. 941std::pair<uint64_t, unsigned> 942ASTContext::getTypeInfoImpl(const Type *T) const { 943 uint64_t Width=0; 944 unsigned Align=8; 945 switch (T->getTypeClass()) { 946#define TYPE(Class, Base) 947#define ABSTRACT_TYPE(Class, Base) 948#define NON_CANONICAL_TYPE(Class, Base) 949#define DEPENDENT_TYPE(Class, Base) case Type::Class: 950#include "clang/AST/TypeNodes.def" 951 llvm_unreachable("Should not see dependent types"); 952 953 case Type::FunctionNoProto: 954 case Type::FunctionProto: 955 // GCC extension: alignof(function) = 32 bits 956 Width = 0; 957 Align = 32; 958 break; 959 960 case Type::IncompleteArray: 961 case Type::VariableArray: 962 Width = 0; 963 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 964 break; 965 966 case Type::ConstantArray: { 967 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 968 969 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 970 uint64_t Size = CAT->getSize().getZExtValue(); 971 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 972 "Overflow in array type bit size evaluation"); 973 Width = EltInfo.first*Size; 974 Align = EltInfo.second; 975 Width = llvm::RoundUpToAlignment(Width, Align); 976 break; 977 } 978 case Type::ExtVector: 979 case Type::Vector: { 980 const VectorType *VT = cast<VectorType>(T); 981 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 982 Width = EltInfo.first*VT->getNumElements(); 983 Align = Width; 984 // If the alignment is not a power of 2, round up to the next power of 2. 985 // This happens for non-power-of-2 length vectors. 986 if (Align & (Align-1)) { 987 Align = llvm::NextPowerOf2(Align); 988 Width = llvm::RoundUpToAlignment(Width, Align); 989 } 990 break; 991 } 992 993 case Type::Builtin: 994 switch (cast<BuiltinType>(T)->getKind()) { 995 default: llvm_unreachable("Unknown builtin type!"); 996 case BuiltinType::Void: 997 // GCC extension: alignof(void) = 8 bits. 998 Width = 0; 999 Align = 8; 1000 break; 1001 1002 case BuiltinType::Bool: 1003 Width = Target->getBoolWidth(); 1004 Align = Target->getBoolAlign(); 1005 break; 1006 case BuiltinType::Char_S: 1007 case BuiltinType::Char_U: 1008 case BuiltinType::UChar: 1009 case BuiltinType::SChar: 1010 Width = Target->getCharWidth(); 1011 Align = Target->getCharAlign(); 1012 break; 1013 case BuiltinType::WChar_S: 1014 case BuiltinType::WChar_U: 1015 Width = Target->getWCharWidth(); 1016 Align = Target->getWCharAlign(); 1017 break; 1018 case BuiltinType::Char16: 1019 Width = Target->getChar16Width(); 1020 Align = Target->getChar16Align(); 1021 break; 1022 case BuiltinType::Char32: 1023 Width = Target->getChar32Width(); 1024 Align = Target->getChar32Align(); 1025 break; 1026 case BuiltinType::UShort: 1027 case BuiltinType::Short: 1028 Width = Target->getShortWidth(); 1029 Align = Target->getShortAlign(); 1030 break; 1031 case BuiltinType::UInt: 1032 case BuiltinType::Int: 1033 Width = Target->getIntWidth(); 1034 Align = Target->getIntAlign(); 1035 break; 1036 case BuiltinType::ULong: 1037 case BuiltinType::Long: 1038 Width = Target->getLongWidth(); 1039 Align = Target->getLongAlign(); 1040 break; 1041 case BuiltinType::ULongLong: 1042 case BuiltinType::LongLong: 1043 Width = Target->getLongLongWidth(); 1044 Align = Target->getLongLongAlign(); 1045 break; 1046 case BuiltinType::Int128: 1047 case BuiltinType::UInt128: 1048 Width = 128; 1049 Align = 128; // int128_t is 128-bit aligned on all targets. 1050 break; 1051 case BuiltinType::Half: 1052 Width = Target->getHalfWidth(); 1053 Align = Target->getHalfAlign(); 1054 break; 1055 case BuiltinType::Float: 1056 Width = Target->getFloatWidth(); 1057 Align = Target->getFloatAlign(); 1058 break; 1059 case BuiltinType::Double: 1060 Width = Target->getDoubleWidth(); 1061 Align = Target->getDoubleAlign(); 1062 break; 1063 case BuiltinType::LongDouble: 1064 Width = Target->getLongDoubleWidth(); 1065 Align = Target->getLongDoubleAlign(); 1066 break; 1067 case BuiltinType::NullPtr: 1068 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1069 Align = Target->getPointerAlign(0); // == sizeof(void*) 1070 break; 1071 case BuiltinType::ObjCId: 1072 case BuiltinType::ObjCClass: 1073 case BuiltinType::ObjCSel: 1074 Width = Target->getPointerWidth(0); 1075 Align = Target->getPointerAlign(0); 1076 break; 1077 } 1078 break; 1079 case Type::ObjCObjectPointer: 1080 Width = Target->getPointerWidth(0); 1081 Align = Target->getPointerAlign(0); 1082 break; 1083 case Type::BlockPointer: { 1084 unsigned AS = getTargetAddressSpace( 1085 cast<BlockPointerType>(T)->getPointeeType()); 1086 Width = Target->getPointerWidth(AS); 1087 Align = Target->getPointerAlign(AS); 1088 break; 1089 } 1090 case Type::LValueReference: 1091 case Type::RValueReference: { 1092 // alignof and sizeof should never enter this code path here, so we go 1093 // the pointer route. 1094 unsigned AS = getTargetAddressSpace( 1095 cast<ReferenceType>(T)->getPointeeType()); 1096 Width = Target->getPointerWidth(AS); 1097 Align = Target->getPointerAlign(AS); 1098 break; 1099 } 1100 case Type::Pointer: { 1101 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1102 Width = Target->getPointerWidth(AS); 1103 Align = Target->getPointerAlign(AS); 1104 break; 1105 } 1106 case Type::MemberPointer: { 1107 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1108 std::pair<uint64_t, unsigned> PtrDiffInfo = 1109 getTypeInfo(getPointerDiffType()); 1110 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 1111 Align = PtrDiffInfo.second; 1112 break; 1113 } 1114 case Type::Complex: { 1115 // Complex types have the same alignment as their elements, but twice the 1116 // size. 1117 std::pair<uint64_t, unsigned> EltInfo = 1118 getTypeInfo(cast<ComplexType>(T)->getElementType()); 1119 Width = EltInfo.first*2; 1120 Align = EltInfo.second; 1121 break; 1122 } 1123 case Type::ObjCObject: 1124 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1125 case Type::ObjCInterface: { 1126 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1127 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1128 Width = toBits(Layout.getSize()); 1129 Align = toBits(Layout.getAlignment()); 1130 break; 1131 } 1132 case Type::Record: 1133 case Type::Enum: { 1134 const TagType *TT = cast<TagType>(T); 1135 1136 if (TT->getDecl()->isInvalidDecl()) { 1137 Width = 8; 1138 Align = 8; 1139 break; 1140 } 1141 1142 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1143 return getTypeInfo(ET->getDecl()->getIntegerType()); 1144 1145 const RecordType *RT = cast<RecordType>(TT); 1146 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1147 Width = toBits(Layout.getSize()); 1148 Align = toBits(Layout.getAlignment()); 1149 break; 1150 } 1151 1152 case Type::SubstTemplateTypeParm: 1153 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1154 getReplacementType().getTypePtr()); 1155 1156 case Type::Auto: { 1157 const AutoType *A = cast<AutoType>(T); 1158 assert(A->isDeduced() && "Cannot request the size of a dependent type"); 1159 return getTypeInfo(A->getDeducedType().getTypePtr()); 1160 } 1161 1162 case Type::Paren: 1163 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1164 1165 case Type::Typedef: { 1166 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1167 std::pair<uint64_t, unsigned> Info 1168 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1169 // If the typedef has an aligned attribute on it, it overrides any computed 1170 // alignment we have. This violates the GCC documentation (which says that 1171 // attribute(aligned) can only round up) but matches its implementation. 1172 if (unsigned AttrAlign = Typedef->getMaxAlignment()) 1173 Align = AttrAlign; 1174 else 1175 Align = Info.second; 1176 Width = Info.first; 1177 break; 1178 } 1179 1180 case Type::TypeOfExpr: 1181 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 1182 .getTypePtr()); 1183 1184 case Type::TypeOf: 1185 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 1186 1187 case Type::Decltype: 1188 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 1189 .getTypePtr()); 1190 1191 case Type::UnaryTransform: 1192 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType()); 1193 1194 case Type::Elaborated: 1195 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1196 1197 case Type::Attributed: 1198 return getTypeInfo( 1199 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1200 1201 case Type::TemplateSpecialization: { 1202 assert(getCanonicalType(T) != T && 1203 "Cannot request the size of a dependent type"); 1204 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T); 1205 // A type alias template specialization may refer to a typedef with the 1206 // aligned attribute on it. 1207 if (TST->isTypeAlias()) 1208 return getTypeInfo(TST->getAliasedType().getTypePtr()); 1209 else 1210 return getTypeInfo(getCanonicalType(T)); 1211 } 1212 1213 case Type::Atomic: { 1214 std::pair<uint64_t, unsigned> Info 1215 = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1216 Width = Info.first; 1217 Align = Info.second; 1218 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() && 1219 llvm::isPowerOf2_64(Width)) { 1220 // We can potentially perform lock-free atomic operations for this 1221 // type; promote the alignment appropriately. 1222 // FIXME: We could potentially promote the width here as well... 1223 // is that worthwhile? (Non-struct atomic types generally have 1224 // power-of-two size anyway, but structs might not. Requires a bit 1225 // of implementation work to make sure we zero out the extra bits.) 1226 Align = static_cast<unsigned>(Width); 1227 } 1228 } 1229 1230 } 1231 1232 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1233 return std::make_pair(Width, Align); 1234} 1235 1236/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1237CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1238 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1239} 1240 1241/// toBits - Convert a size in characters to a size in characters. 1242int64_t ASTContext::toBits(CharUnits CharSize) const { 1243 return CharSize.getQuantity() * getCharWidth(); 1244} 1245 1246/// getTypeSizeInChars - Return the size of the specified type, in characters. 1247/// This method does not work on incomplete types. 1248CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1249 return toCharUnitsFromBits(getTypeSize(T)); 1250} 1251CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1252 return toCharUnitsFromBits(getTypeSize(T)); 1253} 1254 1255/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1256/// characters. This method does not work on incomplete types. 1257CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1258 return toCharUnitsFromBits(getTypeAlign(T)); 1259} 1260CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1261 return toCharUnitsFromBits(getTypeAlign(T)); 1262} 1263 1264/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1265/// type for the current target in bits. This can be different than the ABI 1266/// alignment in cases where it is beneficial for performance to overalign 1267/// a data type. 1268unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1269 unsigned ABIAlign = getTypeAlign(T); 1270 1271 // Double and long long should be naturally aligned if possible. 1272 if (const ComplexType* CT = T->getAs<ComplexType>()) 1273 T = CT->getElementType().getTypePtr(); 1274 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1275 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1276 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1277 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1278 1279 return ABIAlign; 1280} 1281 1282/// DeepCollectObjCIvars - 1283/// This routine first collects all declared, but not synthesized, ivars in 1284/// super class and then collects all ivars, including those synthesized for 1285/// current class. This routine is used for implementation of current class 1286/// when all ivars, declared and synthesized are known. 1287/// 1288void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1289 bool leafClass, 1290 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1291 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1292 DeepCollectObjCIvars(SuperClass, false, Ivars); 1293 if (!leafClass) { 1294 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1295 E = OI->ivar_end(); I != E; ++I) 1296 Ivars.push_back(*I); 1297 } else { 1298 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1299 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1300 Iv= Iv->getNextIvar()) 1301 Ivars.push_back(Iv); 1302 } 1303} 1304 1305/// CollectInheritedProtocols - Collect all protocols in current class and 1306/// those inherited by it. 1307void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1308 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1309 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1310 // We can use protocol_iterator here instead of 1311 // all_referenced_protocol_iterator since we are walking all categories. 1312 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 1313 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 1314 ObjCProtocolDecl *Proto = (*P); 1315 Protocols.insert(Proto->getCanonicalDecl()); 1316 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1317 PE = Proto->protocol_end(); P != PE; ++P) { 1318 Protocols.insert((*P)->getCanonicalDecl()); 1319 CollectInheritedProtocols(*P, Protocols); 1320 } 1321 } 1322 1323 // Categories of this Interface. 1324 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 1325 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 1326 CollectInheritedProtocols(CDeclChain, Protocols); 1327 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1328 while (SD) { 1329 CollectInheritedProtocols(SD, Protocols); 1330 SD = SD->getSuperClass(); 1331 } 1332 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1333 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 1334 PE = OC->protocol_end(); P != PE; ++P) { 1335 ObjCProtocolDecl *Proto = (*P); 1336 Protocols.insert(Proto->getCanonicalDecl()); 1337 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1338 PE = Proto->protocol_end(); P != PE; ++P) 1339 CollectInheritedProtocols(*P, Protocols); 1340 } 1341 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1342 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 1343 PE = OP->protocol_end(); P != PE; ++P) { 1344 ObjCProtocolDecl *Proto = (*P); 1345 Protocols.insert(Proto->getCanonicalDecl()); 1346 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1347 PE = Proto->protocol_end(); P != PE; ++P) 1348 CollectInheritedProtocols(*P, Protocols); 1349 } 1350 } 1351} 1352 1353unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1354 unsigned count = 0; 1355 // Count ivars declared in class extension. 1356 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 1357 CDecl = CDecl->getNextClassExtension()) 1358 count += CDecl->ivar_size(); 1359 1360 // Count ivar defined in this class's implementation. This 1361 // includes synthesized ivars. 1362 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1363 count += ImplDecl->ivar_size(); 1364 1365 return count; 1366} 1367 1368bool ASTContext::isSentinelNullExpr(const Expr *E) { 1369 if (!E) 1370 return false; 1371 1372 // nullptr_t is always treated as null. 1373 if (E->getType()->isNullPtrType()) return true; 1374 1375 if (E->getType()->isAnyPointerType() && 1376 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1377 Expr::NPC_ValueDependentIsNull)) 1378 return true; 1379 1380 // Unfortunately, __null has type 'int'. 1381 if (isa<GNUNullExpr>(E)) return true; 1382 1383 return false; 1384} 1385 1386/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1387ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1388 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1389 I = ObjCImpls.find(D); 1390 if (I != ObjCImpls.end()) 1391 return cast<ObjCImplementationDecl>(I->second); 1392 return 0; 1393} 1394/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1395ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1396 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1397 I = ObjCImpls.find(D); 1398 if (I != ObjCImpls.end()) 1399 return cast<ObjCCategoryImplDecl>(I->second); 1400 return 0; 1401} 1402 1403/// \brief Set the implementation of ObjCInterfaceDecl. 1404void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1405 ObjCImplementationDecl *ImplD) { 1406 assert(IFaceD && ImplD && "Passed null params"); 1407 ObjCImpls[IFaceD] = ImplD; 1408} 1409/// \brief Set the implementation of ObjCCategoryDecl. 1410void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1411 ObjCCategoryImplDecl *ImplD) { 1412 assert(CatD && ImplD && "Passed null params"); 1413 ObjCImpls[CatD] = ImplD; 1414} 1415 1416ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const { 1417 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1418 return ID; 1419 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1420 return CD->getClassInterface(); 1421 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1422 return IMD->getClassInterface(); 1423 1424 return 0; 1425} 1426 1427/// \brief Get the copy initialization expression of VarDecl,or NULL if 1428/// none exists. 1429Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1430 assert(VD && "Passed null params"); 1431 assert(VD->hasAttr<BlocksAttr>() && 1432 "getBlockVarCopyInits - not __block var"); 1433 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1434 I = BlockVarCopyInits.find(VD); 1435 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1436} 1437 1438/// \brief Set the copy inialization expression of a block var decl. 1439void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1440 assert(VD && Init && "Passed null params"); 1441 assert(VD->hasAttr<BlocksAttr>() && 1442 "setBlockVarCopyInits - not __block var"); 1443 BlockVarCopyInits[VD] = Init; 1444} 1445 1446TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1447 unsigned DataSize) const { 1448 if (!DataSize) 1449 DataSize = TypeLoc::getFullDataSizeForType(T); 1450 else 1451 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1452 "incorrect data size provided to CreateTypeSourceInfo!"); 1453 1454 TypeSourceInfo *TInfo = 1455 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1456 new (TInfo) TypeSourceInfo(T); 1457 return TInfo; 1458} 1459 1460TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1461 SourceLocation L) const { 1462 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1463 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1464 return DI; 1465} 1466 1467const ASTRecordLayout & 1468ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1469 return getObjCLayout(D, 0); 1470} 1471 1472const ASTRecordLayout & 1473ASTContext::getASTObjCImplementationLayout( 1474 const ObjCImplementationDecl *D) const { 1475 return getObjCLayout(D->getClassInterface(), D); 1476} 1477 1478//===----------------------------------------------------------------------===// 1479// Type creation/memoization methods 1480//===----------------------------------------------------------------------===// 1481 1482QualType 1483ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 1484 unsigned fastQuals = quals.getFastQualifiers(); 1485 quals.removeFastQualifiers(); 1486 1487 // Check if we've already instantiated this type. 1488 llvm::FoldingSetNodeID ID; 1489 ExtQuals::Profile(ID, baseType, quals); 1490 void *insertPos = 0; 1491 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 1492 assert(eq->getQualifiers() == quals); 1493 return QualType(eq, fastQuals); 1494 } 1495 1496 // If the base type is not canonical, make the appropriate canonical type. 1497 QualType canon; 1498 if (!baseType->isCanonicalUnqualified()) { 1499 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 1500 canonSplit.Quals.addConsistentQualifiers(quals); 1501 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 1502 1503 // Re-find the insert position. 1504 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 1505 } 1506 1507 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 1508 ExtQualNodes.InsertNode(eq, insertPos); 1509 return QualType(eq, fastQuals); 1510} 1511 1512QualType 1513ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 1514 QualType CanT = getCanonicalType(T); 1515 if (CanT.getAddressSpace() == AddressSpace) 1516 return T; 1517 1518 // If we are composing extended qualifiers together, merge together 1519 // into one ExtQuals node. 1520 QualifierCollector Quals; 1521 const Type *TypeNode = Quals.strip(T); 1522 1523 // If this type already has an address space specified, it cannot get 1524 // another one. 1525 assert(!Quals.hasAddressSpace() && 1526 "Type cannot be in multiple addr spaces!"); 1527 Quals.addAddressSpace(AddressSpace); 1528 1529 return getExtQualType(TypeNode, Quals); 1530} 1531 1532QualType ASTContext::getObjCGCQualType(QualType T, 1533 Qualifiers::GC GCAttr) const { 1534 QualType CanT = getCanonicalType(T); 1535 if (CanT.getObjCGCAttr() == GCAttr) 1536 return T; 1537 1538 if (const PointerType *ptr = T->getAs<PointerType>()) { 1539 QualType Pointee = ptr->getPointeeType(); 1540 if (Pointee->isAnyPointerType()) { 1541 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1542 return getPointerType(ResultType); 1543 } 1544 } 1545 1546 // If we are composing extended qualifiers together, merge together 1547 // into one ExtQuals node. 1548 QualifierCollector Quals; 1549 const Type *TypeNode = Quals.strip(T); 1550 1551 // If this type already has an ObjCGC specified, it cannot get 1552 // another one. 1553 assert(!Quals.hasObjCGCAttr() && 1554 "Type cannot have multiple ObjCGCs!"); 1555 Quals.addObjCGCAttr(GCAttr); 1556 1557 return getExtQualType(TypeNode, Quals); 1558} 1559 1560const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 1561 FunctionType::ExtInfo Info) { 1562 if (T->getExtInfo() == Info) 1563 return T; 1564 1565 QualType Result; 1566 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 1567 Result = getFunctionNoProtoType(FNPT->getResultType(), Info); 1568 } else { 1569 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1570 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 1571 EPI.ExtInfo = Info; 1572 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1573 FPT->getNumArgs(), EPI); 1574 } 1575 1576 return cast<FunctionType>(Result.getTypePtr()); 1577} 1578 1579/// getComplexType - Return the uniqued reference to the type for a complex 1580/// number with the specified element type. 1581QualType ASTContext::getComplexType(QualType T) const { 1582 // Unique pointers, to guarantee there is only one pointer of a particular 1583 // structure. 1584 llvm::FoldingSetNodeID ID; 1585 ComplexType::Profile(ID, T); 1586 1587 void *InsertPos = 0; 1588 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1589 return QualType(CT, 0); 1590 1591 // If the pointee type isn't canonical, this won't be a canonical type either, 1592 // so fill in the canonical type field. 1593 QualType Canonical; 1594 if (!T.isCanonical()) { 1595 Canonical = getComplexType(getCanonicalType(T)); 1596 1597 // Get the new insert position for the node we care about. 1598 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1599 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1600 } 1601 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1602 Types.push_back(New); 1603 ComplexTypes.InsertNode(New, InsertPos); 1604 return QualType(New, 0); 1605} 1606 1607/// getPointerType - Return the uniqued reference to the type for a pointer to 1608/// the specified type. 1609QualType ASTContext::getPointerType(QualType T) const { 1610 // Unique pointers, to guarantee there is only one pointer of a particular 1611 // structure. 1612 llvm::FoldingSetNodeID ID; 1613 PointerType::Profile(ID, T); 1614 1615 void *InsertPos = 0; 1616 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1617 return QualType(PT, 0); 1618 1619 // If the pointee type isn't canonical, this won't be a canonical type either, 1620 // so fill in the canonical type field. 1621 QualType Canonical; 1622 if (!T.isCanonical()) { 1623 Canonical = getPointerType(getCanonicalType(T)); 1624 1625 // Get the new insert position for the node we care about. 1626 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1627 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1628 } 1629 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1630 Types.push_back(New); 1631 PointerTypes.InsertNode(New, InsertPos); 1632 return QualType(New, 0); 1633} 1634 1635/// getBlockPointerType - Return the uniqued reference to the type for 1636/// a pointer to the specified block. 1637QualType ASTContext::getBlockPointerType(QualType T) const { 1638 assert(T->isFunctionType() && "block of function types only"); 1639 // Unique pointers, to guarantee there is only one block of a particular 1640 // structure. 1641 llvm::FoldingSetNodeID ID; 1642 BlockPointerType::Profile(ID, T); 1643 1644 void *InsertPos = 0; 1645 if (BlockPointerType *PT = 1646 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1647 return QualType(PT, 0); 1648 1649 // If the block pointee type isn't canonical, this won't be a canonical 1650 // type either so fill in the canonical type field. 1651 QualType Canonical; 1652 if (!T.isCanonical()) { 1653 Canonical = getBlockPointerType(getCanonicalType(T)); 1654 1655 // Get the new insert position for the node we care about. 1656 BlockPointerType *NewIP = 1657 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1658 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1659 } 1660 BlockPointerType *New 1661 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1662 Types.push_back(New); 1663 BlockPointerTypes.InsertNode(New, InsertPos); 1664 return QualType(New, 0); 1665} 1666 1667/// getLValueReferenceType - Return the uniqued reference to the type for an 1668/// lvalue reference to the specified type. 1669QualType 1670ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 1671 assert(getCanonicalType(T) != OverloadTy && 1672 "Unresolved overloaded function type"); 1673 1674 // Unique pointers, to guarantee there is only one pointer of a particular 1675 // structure. 1676 llvm::FoldingSetNodeID ID; 1677 ReferenceType::Profile(ID, T, SpelledAsLValue); 1678 1679 void *InsertPos = 0; 1680 if (LValueReferenceType *RT = 1681 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1682 return QualType(RT, 0); 1683 1684 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1685 1686 // If the referencee type isn't canonical, this won't be a canonical type 1687 // either, so fill in the canonical type field. 1688 QualType Canonical; 1689 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1690 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1691 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1692 1693 // Get the new insert position for the node we care about. 1694 LValueReferenceType *NewIP = 1695 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1696 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1697 } 1698 1699 LValueReferenceType *New 1700 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1701 SpelledAsLValue); 1702 Types.push_back(New); 1703 LValueReferenceTypes.InsertNode(New, InsertPos); 1704 1705 return QualType(New, 0); 1706} 1707 1708/// getRValueReferenceType - Return the uniqued reference to the type for an 1709/// rvalue reference to the specified type. 1710QualType ASTContext::getRValueReferenceType(QualType T) const { 1711 // Unique pointers, to guarantee there is only one pointer of a particular 1712 // structure. 1713 llvm::FoldingSetNodeID ID; 1714 ReferenceType::Profile(ID, T, false); 1715 1716 void *InsertPos = 0; 1717 if (RValueReferenceType *RT = 1718 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1719 return QualType(RT, 0); 1720 1721 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1722 1723 // If the referencee type isn't canonical, this won't be a canonical type 1724 // either, so fill in the canonical type field. 1725 QualType Canonical; 1726 if (InnerRef || !T.isCanonical()) { 1727 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1728 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1729 1730 // Get the new insert position for the node we care about. 1731 RValueReferenceType *NewIP = 1732 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1733 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1734 } 1735 1736 RValueReferenceType *New 1737 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1738 Types.push_back(New); 1739 RValueReferenceTypes.InsertNode(New, InsertPos); 1740 return QualType(New, 0); 1741} 1742 1743/// getMemberPointerType - Return the uniqued reference to the type for a 1744/// member pointer to the specified type, in the specified class. 1745QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 1746 // Unique pointers, to guarantee there is only one pointer of a particular 1747 // structure. 1748 llvm::FoldingSetNodeID ID; 1749 MemberPointerType::Profile(ID, T, Cls); 1750 1751 void *InsertPos = 0; 1752 if (MemberPointerType *PT = 1753 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1754 return QualType(PT, 0); 1755 1756 // If the pointee or class type isn't canonical, this won't be a canonical 1757 // type either, so fill in the canonical type field. 1758 QualType Canonical; 1759 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1760 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1761 1762 // Get the new insert position for the node we care about. 1763 MemberPointerType *NewIP = 1764 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1765 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1766 } 1767 MemberPointerType *New 1768 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1769 Types.push_back(New); 1770 MemberPointerTypes.InsertNode(New, InsertPos); 1771 return QualType(New, 0); 1772} 1773 1774/// getConstantArrayType - Return the unique reference to the type for an 1775/// array of the specified element type. 1776QualType ASTContext::getConstantArrayType(QualType EltTy, 1777 const llvm::APInt &ArySizeIn, 1778 ArrayType::ArraySizeModifier ASM, 1779 unsigned IndexTypeQuals) const { 1780 assert((EltTy->isDependentType() || 1781 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1782 "Constant array of VLAs is illegal!"); 1783 1784 // Convert the array size into a canonical width matching the pointer size for 1785 // the target. 1786 llvm::APInt ArySize(ArySizeIn); 1787 ArySize = 1788 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 1789 1790 llvm::FoldingSetNodeID ID; 1791 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 1792 1793 void *InsertPos = 0; 1794 if (ConstantArrayType *ATP = 1795 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1796 return QualType(ATP, 0); 1797 1798 // If the element type isn't canonical or has qualifiers, this won't 1799 // be a canonical type either, so fill in the canonical type field. 1800 QualType Canon; 1801 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1802 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1803 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 1804 ASM, IndexTypeQuals); 1805 Canon = getQualifiedType(Canon, canonSplit.Quals); 1806 1807 // Get the new insert position for the node we care about. 1808 ConstantArrayType *NewIP = 1809 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1810 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1811 } 1812 1813 ConstantArrayType *New = new(*this,TypeAlignment) 1814 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 1815 ConstantArrayTypes.InsertNode(New, InsertPos); 1816 Types.push_back(New); 1817 return QualType(New, 0); 1818} 1819 1820/// getVariableArrayDecayedType - Turns the given type, which may be 1821/// variably-modified, into the corresponding type with all the known 1822/// sizes replaced with [*]. 1823QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 1824 // Vastly most common case. 1825 if (!type->isVariablyModifiedType()) return type; 1826 1827 QualType result; 1828 1829 SplitQualType split = type.getSplitDesugaredType(); 1830 const Type *ty = split.Ty; 1831 switch (ty->getTypeClass()) { 1832#define TYPE(Class, Base) 1833#define ABSTRACT_TYPE(Class, Base) 1834#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 1835#include "clang/AST/TypeNodes.def" 1836 llvm_unreachable("didn't desugar past all non-canonical types?"); 1837 1838 // These types should never be variably-modified. 1839 case Type::Builtin: 1840 case Type::Complex: 1841 case Type::Vector: 1842 case Type::ExtVector: 1843 case Type::DependentSizedExtVector: 1844 case Type::ObjCObject: 1845 case Type::ObjCInterface: 1846 case Type::ObjCObjectPointer: 1847 case Type::Record: 1848 case Type::Enum: 1849 case Type::UnresolvedUsing: 1850 case Type::TypeOfExpr: 1851 case Type::TypeOf: 1852 case Type::Decltype: 1853 case Type::UnaryTransform: 1854 case Type::DependentName: 1855 case Type::InjectedClassName: 1856 case Type::TemplateSpecialization: 1857 case Type::DependentTemplateSpecialization: 1858 case Type::TemplateTypeParm: 1859 case Type::SubstTemplateTypeParmPack: 1860 case Type::Auto: 1861 case Type::PackExpansion: 1862 llvm_unreachable("type should never be variably-modified"); 1863 1864 // These types can be variably-modified but should never need to 1865 // further decay. 1866 case Type::FunctionNoProto: 1867 case Type::FunctionProto: 1868 case Type::BlockPointer: 1869 case Type::MemberPointer: 1870 return type; 1871 1872 // These types can be variably-modified. All these modifications 1873 // preserve structure except as noted by comments. 1874 // TODO: if we ever care about optimizing VLAs, there are no-op 1875 // optimizations available here. 1876 case Type::Pointer: 1877 result = getPointerType(getVariableArrayDecayedType( 1878 cast<PointerType>(ty)->getPointeeType())); 1879 break; 1880 1881 case Type::LValueReference: { 1882 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 1883 result = getLValueReferenceType( 1884 getVariableArrayDecayedType(lv->getPointeeType()), 1885 lv->isSpelledAsLValue()); 1886 break; 1887 } 1888 1889 case Type::RValueReference: { 1890 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 1891 result = getRValueReferenceType( 1892 getVariableArrayDecayedType(lv->getPointeeType())); 1893 break; 1894 } 1895 1896 case Type::Atomic: { 1897 const AtomicType *at = cast<AtomicType>(ty); 1898 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 1899 break; 1900 } 1901 1902 case Type::ConstantArray: { 1903 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 1904 result = getConstantArrayType( 1905 getVariableArrayDecayedType(cat->getElementType()), 1906 cat->getSize(), 1907 cat->getSizeModifier(), 1908 cat->getIndexTypeCVRQualifiers()); 1909 break; 1910 } 1911 1912 case Type::DependentSizedArray: { 1913 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 1914 result = getDependentSizedArrayType( 1915 getVariableArrayDecayedType(dat->getElementType()), 1916 dat->getSizeExpr(), 1917 dat->getSizeModifier(), 1918 dat->getIndexTypeCVRQualifiers(), 1919 dat->getBracketsRange()); 1920 break; 1921 } 1922 1923 // Turn incomplete types into [*] types. 1924 case Type::IncompleteArray: { 1925 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 1926 result = getVariableArrayType( 1927 getVariableArrayDecayedType(iat->getElementType()), 1928 /*size*/ 0, 1929 ArrayType::Normal, 1930 iat->getIndexTypeCVRQualifiers(), 1931 SourceRange()); 1932 break; 1933 } 1934 1935 // Turn VLA types into [*] types. 1936 case Type::VariableArray: { 1937 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1938 result = getVariableArrayType( 1939 getVariableArrayDecayedType(vat->getElementType()), 1940 /*size*/ 0, 1941 ArrayType::Star, 1942 vat->getIndexTypeCVRQualifiers(), 1943 vat->getBracketsRange()); 1944 break; 1945 } 1946 } 1947 1948 // Apply the top-level qualifiers from the original. 1949 return getQualifiedType(result, split.Quals); 1950} 1951 1952/// getVariableArrayType - Returns a non-unique reference to the type for a 1953/// variable array of the specified element type. 1954QualType ASTContext::getVariableArrayType(QualType EltTy, 1955 Expr *NumElts, 1956 ArrayType::ArraySizeModifier ASM, 1957 unsigned IndexTypeQuals, 1958 SourceRange Brackets) const { 1959 // Since we don't unique expressions, it isn't possible to unique VLA's 1960 // that have an expression provided for their size. 1961 QualType Canon; 1962 1963 // Be sure to pull qualifiers off the element type. 1964 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1965 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1966 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 1967 IndexTypeQuals, Brackets); 1968 Canon = getQualifiedType(Canon, canonSplit.Quals); 1969 } 1970 1971 VariableArrayType *New = new(*this, TypeAlignment) 1972 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 1973 1974 VariableArrayTypes.push_back(New); 1975 Types.push_back(New); 1976 return QualType(New, 0); 1977} 1978 1979/// getDependentSizedArrayType - Returns a non-unique reference to 1980/// the type for a dependently-sized array of the specified element 1981/// type. 1982QualType ASTContext::getDependentSizedArrayType(QualType elementType, 1983 Expr *numElements, 1984 ArrayType::ArraySizeModifier ASM, 1985 unsigned elementTypeQuals, 1986 SourceRange brackets) const { 1987 assert((!numElements || numElements->isTypeDependent() || 1988 numElements->isValueDependent()) && 1989 "Size must be type- or value-dependent!"); 1990 1991 // Dependently-sized array types that do not have a specified number 1992 // of elements will have their sizes deduced from a dependent 1993 // initializer. We do no canonicalization here at all, which is okay 1994 // because they can't be used in most locations. 1995 if (!numElements) { 1996 DependentSizedArrayType *newType 1997 = new (*this, TypeAlignment) 1998 DependentSizedArrayType(*this, elementType, QualType(), 1999 numElements, ASM, elementTypeQuals, 2000 brackets); 2001 Types.push_back(newType); 2002 return QualType(newType, 0); 2003 } 2004 2005 // Otherwise, we actually build a new type every time, but we 2006 // also build a canonical type. 2007 2008 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2009 2010 void *insertPos = 0; 2011 llvm::FoldingSetNodeID ID; 2012 DependentSizedArrayType::Profile(ID, *this, 2013 QualType(canonElementType.Ty, 0), 2014 ASM, elementTypeQuals, numElements); 2015 2016 // Look for an existing type with these properties. 2017 DependentSizedArrayType *canonTy = 2018 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2019 2020 // If we don't have one, build one. 2021 if (!canonTy) { 2022 canonTy = new (*this, TypeAlignment) 2023 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2024 QualType(), numElements, ASM, elementTypeQuals, 2025 brackets); 2026 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2027 Types.push_back(canonTy); 2028 } 2029 2030 // Apply qualifiers from the element type to the array. 2031 QualType canon = getQualifiedType(QualType(canonTy,0), 2032 canonElementType.Quals); 2033 2034 // If we didn't need extra canonicalization for the element type, 2035 // then just use that as our result. 2036 if (QualType(canonElementType.Ty, 0) == elementType) 2037 return canon; 2038 2039 // Otherwise, we need to build a type which follows the spelling 2040 // of the element type. 2041 DependentSizedArrayType *sugaredType 2042 = new (*this, TypeAlignment) 2043 DependentSizedArrayType(*this, elementType, canon, numElements, 2044 ASM, elementTypeQuals, brackets); 2045 Types.push_back(sugaredType); 2046 return QualType(sugaredType, 0); 2047} 2048 2049QualType ASTContext::getIncompleteArrayType(QualType elementType, 2050 ArrayType::ArraySizeModifier ASM, 2051 unsigned elementTypeQuals) const { 2052 llvm::FoldingSetNodeID ID; 2053 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2054 2055 void *insertPos = 0; 2056 if (IncompleteArrayType *iat = 2057 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2058 return QualType(iat, 0); 2059 2060 // If the element type isn't canonical, this won't be a canonical type 2061 // either, so fill in the canonical type field. We also have to pull 2062 // qualifiers off the element type. 2063 QualType canon; 2064 2065 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2066 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2067 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2068 ASM, elementTypeQuals); 2069 canon = getQualifiedType(canon, canonSplit.Quals); 2070 2071 // Get the new insert position for the node we care about. 2072 IncompleteArrayType *existing = 2073 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2074 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2075 } 2076 2077 IncompleteArrayType *newType = new (*this, TypeAlignment) 2078 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2079 2080 IncompleteArrayTypes.InsertNode(newType, insertPos); 2081 Types.push_back(newType); 2082 return QualType(newType, 0); 2083} 2084 2085/// getVectorType - Return the unique reference to a vector type of 2086/// the specified element type and size. VectorType must be a built-in type. 2087QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2088 VectorType::VectorKind VecKind) const { 2089 assert(vecType->isBuiltinType()); 2090 2091 // Check if we've already instantiated a vector of this type. 2092 llvm::FoldingSetNodeID ID; 2093 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2094 2095 void *InsertPos = 0; 2096 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2097 return QualType(VTP, 0); 2098 2099 // If the element type isn't canonical, this won't be a canonical type either, 2100 // so fill in the canonical type field. 2101 QualType Canonical; 2102 if (!vecType.isCanonical()) { 2103 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2104 2105 // Get the new insert position for the node we care about. 2106 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2108 } 2109 VectorType *New = new (*this, TypeAlignment) 2110 VectorType(vecType, NumElts, Canonical, VecKind); 2111 VectorTypes.InsertNode(New, InsertPos); 2112 Types.push_back(New); 2113 return QualType(New, 0); 2114} 2115 2116/// getExtVectorType - Return the unique reference to an extended vector type of 2117/// the specified element type and size. VectorType must be a built-in type. 2118QualType 2119ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2120 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2121 2122 // Check if we've already instantiated a vector of this type. 2123 llvm::FoldingSetNodeID ID; 2124 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2125 VectorType::GenericVector); 2126 void *InsertPos = 0; 2127 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2128 return QualType(VTP, 0); 2129 2130 // If the element type isn't canonical, this won't be a canonical type either, 2131 // so fill in the canonical type field. 2132 QualType Canonical; 2133 if (!vecType.isCanonical()) { 2134 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2135 2136 // Get the new insert position for the node we care about. 2137 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2138 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2139 } 2140 ExtVectorType *New = new (*this, TypeAlignment) 2141 ExtVectorType(vecType, NumElts, Canonical); 2142 VectorTypes.InsertNode(New, InsertPos); 2143 Types.push_back(New); 2144 return QualType(New, 0); 2145} 2146 2147QualType 2148ASTContext::getDependentSizedExtVectorType(QualType vecType, 2149 Expr *SizeExpr, 2150 SourceLocation AttrLoc) const { 2151 llvm::FoldingSetNodeID ID; 2152 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2153 SizeExpr); 2154 2155 void *InsertPos = 0; 2156 DependentSizedExtVectorType *Canon 2157 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2158 DependentSizedExtVectorType *New; 2159 if (Canon) { 2160 // We already have a canonical version of this array type; use it as 2161 // the canonical type for a newly-built type. 2162 New = new (*this, TypeAlignment) 2163 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2164 SizeExpr, AttrLoc); 2165 } else { 2166 QualType CanonVecTy = getCanonicalType(vecType); 2167 if (CanonVecTy == vecType) { 2168 New = new (*this, TypeAlignment) 2169 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2170 AttrLoc); 2171 2172 DependentSizedExtVectorType *CanonCheck 2173 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2174 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2175 (void)CanonCheck; 2176 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2177 } else { 2178 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2179 SourceLocation()); 2180 New = new (*this, TypeAlignment) 2181 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2182 } 2183 } 2184 2185 Types.push_back(New); 2186 return QualType(New, 0); 2187} 2188 2189/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2190/// 2191QualType 2192ASTContext::getFunctionNoProtoType(QualType ResultTy, 2193 const FunctionType::ExtInfo &Info) const { 2194 const CallingConv DefaultCC = Info.getCC(); 2195 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2196 CC_X86StdCall : DefaultCC; 2197 // Unique functions, to guarantee there is only one function of a particular 2198 // structure. 2199 llvm::FoldingSetNodeID ID; 2200 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2201 2202 void *InsertPos = 0; 2203 if (FunctionNoProtoType *FT = 2204 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2205 return QualType(FT, 0); 2206 2207 QualType Canonical; 2208 if (!ResultTy.isCanonical() || 2209 getCanonicalCallConv(CallConv) != CallConv) { 2210 Canonical = 2211 getFunctionNoProtoType(getCanonicalType(ResultTy), 2212 Info.withCallingConv(getCanonicalCallConv(CallConv))); 2213 2214 // Get the new insert position for the node we care about. 2215 FunctionNoProtoType *NewIP = 2216 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2217 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2218 } 2219 2220 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2221 FunctionNoProtoType *New = new (*this, TypeAlignment) 2222 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2223 Types.push_back(New); 2224 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2225 return QualType(New, 0); 2226} 2227 2228/// getFunctionType - Return a normal function type with a typed argument 2229/// list. isVariadic indicates whether the argument list includes '...'. 2230QualType 2231ASTContext::getFunctionType(QualType ResultTy, 2232 const QualType *ArgArray, unsigned NumArgs, 2233 const FunctionProtoType::ExtProtoInfo &EPI) const { 2234 // Unique functions, to guarantee there is only one function of a particular 2235 // structure. 2236 llvm::FoldingSetNodeID ID; 2237 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this); 2238 2239 void *InsertPos = 0; 2240 if (FunctionProtoType *FTP = 2241 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2242 return QualType(FTP, 0); 2243 2244 // Determine whether the type being created is already canonical or not. 2245 bool isCanonical = 2246 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() && 2247 !EPI.HasTrailingReturn; 2248 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2249 if (!ArgArray[i].isCanonicalAsParam()) 2250 isCanonical = false; 2251 2252 const CallingConv DefaultCC = EPI.ExtInfo.getCC(); 2253 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2254 CC_X86StdCall : DefaultCC; 2255 2256 // If this type isn't canonical, get the canonical version of it. 2257 // The exception spec is not part of the canonical type. 2258 QualType Canonical; 2259 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 2260 SmallVector<QualType, 16> CanonicalArgs; 2261 CanonicalArgs.reserve(NumArgs); 2262 for (unsigned i = 0; i != NumArgs; ++i) 2263 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2264 2265 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2266 CanonicalEPI.HasTrailingReturn = false; 2267 CanonicalEPI.ExceptionSpecType = EST_None; 2268 CanonicalEPI.NumExceptions = 0; 2269 CanonicalEPI.ExtInfo 2270 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv)); 2271 2272 Canonical = getFunctionType(getCanonicalType(ResultTy), 2273 CanonicalArgs.data(), NumArgs, 2274 CanonicalEPI); 2275 2276 // Get the new insert position for the node we care about. 2277 FunctionProtoType *NewIP = 2278 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2279 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2280 } 2281 2282 // FunctionProtoType objects are allocated with extra bytes after 2283 // them for three variable size arrays at the end: 2284 // - parameter types 2285 // - exception types 2286 // - consumed-arguments flags 2287 // Instead of the exception types, there could be a noexcept 2288 // expression. 2289 size_t Size = sizeof(FunctionProtoType) + 2290 NumArgs * sizeof(QualType); 2291 if (EPI.ExceptionSpecType == EST_Dynamic) 2292 Size += EPI.NumExceptions * sizeof(QualType); 2293 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) { 2294 Size += sizeof(Expr*); 2295 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) { 2296 Size += 2 * sizeof(FunctionDecl*); 2297 } 2298 if (EPI.ConsumedArguments) 2299 Size += NumArgs * sizeof(bool); 2300 2301 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2302 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2303 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv); 2304 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI); 2305 Types.push_back(FTP); 2306 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2307 return QualType(FTP, 0); 2308} 2309 2310#ifndef NDEBUG 2311static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2312 if (!isa<CXXRecordDecl>(D)) return false; 2313 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2314 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2315 return true; 2316 if (RD->getDescribedClassTemplate() && 2317 !isa<ClassTemplateSpecializationDecl>(RD)) 2318 return true; 2319 return false; 2320} 2321#endif 2322 2323/// getInjectedClassNameType - Return the unique reference to the 2324/// injected class name type for the specified templated declaration. 2325QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2326 QualType TST) const { 2327 assert(NeedsInjectedClassNameType(Decl)); 2328 if (Decl->TypeForDecl) { 2329 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2330 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2331 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2332 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2333 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2334 } else { 2335 Type *newType = 2336 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2337 Decl->TypeForDecl = newType; 2338 Types.push_back(newType); 2339 } 2340 return QualType(Decl->TypeForDecl, 0); 2341} 2342 2343/// getTypeDeclType - Return the unique reference to the type for the 2344/// specified type declaration. 2345QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2346 assert(Decl && "Passed null for Decl param"); 2347 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2348 2349 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2350 return getTypedefType(Typedef); 2351 2352 assert(!isa<TemplateTypeParmDecl>(Decl) && 2353 "Template type parameter types are always available."); 2354 2355 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2356 assert(!Record->getPreviousDecl() && 2357 "struct/union has previous declaration"); 2358 assert(!NeedsInjectedClassNameType(Record)); 2359 return getRecordType(Record); 2360 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2361 assert(!Enum->getPreviousDecl() && 2362 "enum has previous declaration"); 2363 return getEnumType(Enum); 2364 } else if (const UnresolvedUsingTypenameDecl *Using = 2365 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2366 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2367 Decl->TypeForDecl = newType; 2368 Types.push_back(newType); 2369 } else 2370 llvm_unreachable("TypeDecl without a type?"); 2371 2372 return QualType(Decl->TypeForDecl, 0); 2373} 2374 2375/// getTypedefType - Return the unique reference to the type for the 2376/// specified typedef name decl. 2377QualType 2378ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2379 QualType Canonical) const { 2380 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2381 2382 if (Canonical.isNull()) 2383 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2384 TypedefType *newType = new(*this, TypeAlignment) 2385 TypedefType(Type::Typedef, Decl, Canonical); 2386 Decl->TypeForDecl = newType; 2387 Types.push_back(newType); 2388 return QualType(newType, 0); 2389} 2390 2391QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2392 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2393 2394 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2395 if (PrevDecl->TypeForDecl) 2396 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2397 2398 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 2399 Decl->TypeForDecl = newType; 2400 Types.push_back(newType); 2401 return QualType(newType, 0); 2402} 2403 2404QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 2405 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2406 2407 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 2408 if (PrevDecl->TypeForDecl) 2409 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2410 2411 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 2412 Decl->TypeForDecl = newType; 2413 Types.push_back(newType); 2414 return QualType(newType, 0); 2415} 2416 2417QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 2418 QualType modifiedType, 2419 QualType equivalentType) { 2420 llvm::FoldingSetNodeID id; 2421 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 2422 2423 void *insertPos = 0; 2424 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 2425 if (type) return QualType(type, 0); 2426 2427 QualType canon = getCanonicalType(equivalentType); 2428 type = new (*this, TypeAlignment) 2429 AttributedType(canon, attrKind, modifiedType, equivalentType); 2430 2431 Types.push_back(type); 2432 AttributedTypes.InsertNode(type, insertPos); 2433 2434 return QualType(type, 0); 2435} 2436 2437 2438/// \brief Retrieve a substitution-result type. 2439QualType 2440ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 2441 QualType Replacement) const { 2442 assert(Replacement.isCanonical() 2443 && "replacement types must always be canonical"); 2444 2445 llvm::FoldingSetNodeID ID; 2446 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 2447 void *InsertPos = 0; 2448 SubstTemplateTypeParmType *SubstParm 2449 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2450 2451 if (!SubstParm) { 2452 SubstParm = new (*this, TypeAlignment) 2453 SubstTemplateTypeParmType(Parm, Replacement); 2454 Types.push_back(SubstParm); 2455 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2456 } 2457 2458 return QualType(SubstParm, 0); 2459} 2460 2461/// \brief Retrieve a 2462QualType ASTContext::getSubstTemplateTypeParmPackType( 2463 const TemplateTypeParmType *Parm, 2464 const TemplateArgument &ArgPack) { 2465#ifndef NDEBUG 2466 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 2467 PEnd = ArgPack.pack_end(); 2468 P != PEnd; ++P) { 2469 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 2470 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type"); 2471 } 2472#endif 2473 2474 llvm::FoldingSetNodeID ID; 2475 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 2476 void *InsertPos = 0; 2477 if (SubstTemplateTypeParmPackType *SubstParm 2478 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 2479 return QualType(SubstParm, 0); 2480 2481 QualType Canon; 2482 if (!Parm->isCanonicalUnqualified()) { 2483 Canon = getCanonicalType(QualType(Parm, 0)); 2484 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 2485 ArgPack); 2486 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 2487 } 2488 2489 SubstTemplateTypeParmPackType *SubstParm 2490 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 2491 ArgPack); 2492 Types.push_back(SubstParm); 2493 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2494 return QualType(SubstParm, 0); 2495} 2496 2497/// \brief Retrieve the template type parameter type for a template 2498/// parameter or parameter pack with the given depth, index, and (optionally) 2499/// name. 2500QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 2501 bool ParameterPack, 2502 TemplateTypeParmDecl *TTPDecl) const { 2503 llvm::FoldingSetNodeID ID; 2504 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 2505 void *InsertPos = 0; 2506 TemplateTypeParmType *TypeParm 2507 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2508 2509 if (TypeParm) 2510 return QualType(TypeParm, 0); 2511 2512 if (TTPDecl) { 2513 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 2514 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 2515 2516 TemplateTypeParmType *TypeCheck 2517 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2518 assert(!TypeCheck && "Template type parameter canonical type broken"); 2519 (void)TypeCheck; 2520 } else 2521 TypeParm = new (*this, TypeAlignment) 2522 TemplateTypeParmType(Depth, Index, ParameterPack); 2523 2524 Types.push_back(TypeParm); 2525 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 2526 2527 return QualType(TypeParm, 0); 2528} 2529 2530TypeSourceInfo * 2531ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 2532 SourceLocation NameLoc, 2533 const TemplateArgumentListInfo &Args, 2534 QualType Underlying) const { 2535 assert(!Name.getAsDependentTemplateName() && 2536 "No dependent template names here!"); 2537 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 2538 2539 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 2540 TemplateSpecializationTypeLoc TL 2541 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 2542 TL.setTemplateKeywordLoc(SourceLocation()); 2543 TL.setTemplateNameLoc(NameLoc); 2544 TL.setLAngleLoc(Args.getLAngleLoc()); 2545 TL.setRAngleLoc(Args.getRAngleLoc()); 2546 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 2547 TL.setArgLocInfo(i, Args[i].getLocInfo()); 2548 return DI; 2549} 2550 2551QualType 2552ASTContext::getTemplateSpecializationType(TemplateName Template, 2553 const TemplateArgumentListInfo &Args, 2554 QualType Underlying) const { 2555 assert(!Template.getAsDependentTemplateName() && 2556 "No dependent template names here!"); 2557 2558 unsigned NumArgs = Args.size(); 2559 2560 SmallVector<TemplateArgument, 4> ArgVec; 2561 ArgVec.reserve(NumArgs); 2562 for (unsigned i = 0; i != NumArgs; ++i) 2563 ArgVec.push_back(Args[i].getArgument()); 2564 2565 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 2566 Underlying); 2567} 2568 2569#ifndef NDEBUG 2570static bool hasAnyPackExpansions(const TemplateArgument *Args, 2571 unsigned NumArgs) { 2572 for (unsigned I = 0; I != NumArgs; ++I) 2573 if (Args[I].isPackExpansion()) 2574 return true; 2575 2576 return true; 2577} 2578#endif 2579 2580QualType 2581ASTContext::getTemplateSpecializationType(TemplateName Template, 2582 const TemplateArgument *Args, 2583 unsigned NumArgs, 2584 QualType Underlying) const { 2585 assert(!Template.getAsDependentTemplateName() && 2586 "No dependent template names here!"); 2587 // Look through qualified template names. 2588 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2589 Template = TemplateName(QTN->getTemplateDecl()); 2590 2591 bool IsTypeAlias = 2592 Template.getAsTemplateDecl() && 2593 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 2594 QualType CanonType; 2595 if (!Underlying.isNull()) 2596 CanonType = getCanonicalType(Underlying); 2597 else { 2598 // We can get here with an alias template when the specialization contains 2599 // a pack expansion that does not match up with a parameter pack. 2600 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 2601 "Caller must compute aliased type"); 2602 IsTypeAlias = false; 2603 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 2604 NumArgs); 2605 } 2606 2607 // Allocate the (non-canonical) template specialization type, but don't 2608 // try to unique it: these types typically have location information that 2609 // we don't unique and don't want to lose. 2610 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 2611 sizeof(TemplateArgument) * NumArgs + 2612 (IsTypeAlias? sizeof(QualType) : 0), 2613 TypeAlignment); 2614 TemplateSpecializationType *Spec 2615 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 2616 IsTypeAlias ? Underlying : QualType()); 2617 2618 Types.push_back(Spec); 2619 return QualType(Spec, 0); 2620} 2621 2622QualType 2623ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2624 const TemplateArgument *Args, 2625 unsigned NumArgs) const { 2626 assert(!Template.getAsDependentTemplateName() && 2627 "No dependent template names here!"); 2628 2629 // Look through qualified template names. 2630 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2631 Template = TemplateName(QTN->getTemplateDecl()); 2632 2633 // Build the canonical template specialization type. 2634 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2635 SmallVector<TemplateArgument, 4> CanonArgs; 2636 CanonArgs.reserve(NumArgs); 2637 for (unsigned I = 0; I != NumArgs; ++I) 2638 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2639 2640 // Determine whether this canonical template specialization type already 2641 // exists. 2642 llvm::FoldingSetNodeID ID; 2643 TemplateSpecializationType::Profile(ID, CanonTemplate, 2644 CanonArgs.data(), NumArgs, *this); 2645 2646 void *InsertPos = 0; 2647 TemplateSpecializationType *Spec 2648 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2649 2650 if (!Spec) { 2651 // Allocate a new canonical template specialization type. 2652 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2653 sizeof(TemplateArgument) * NumArgs), 2654 TypeAlignment); 2655 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2656 CanonArgs.data(), NumArgs, 2657 QualType(), QualType()); 2658 Types.push_back(Spec); 2659 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2660 } 2661 2662 assert(Spec->isDependentType() && 2663 "Non-dependent template-id type must have a canonical type"); 2664 return QualType(Spec, 0); 2665} 2666 2667QualType 2668ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2669 NestedNameSpecifier *NNS, 2670 QualType NamedType) const { 2671 llvm::FoldingSetNodeID ID; 2672 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2673 2674 void *InsertPos = 0; 2675 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2676 if (T) 2677 return QualType(T, 0); 2678 2679 QualType Canon = NamedType; 2680 if (!Canon.isCanonical()) { 2681 Canon = getCanonicalType(NamedType); 2682 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2683 assert(!CheckT && "Elaborated canonical type broken"); 2684 (void)CheckT; 2685 } 2686 2687 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2688 Types.push_back(T); 2689 ElaboratedTypes.InsertNode(T, InsertPos); 2690 return QualType(T, 0); 2691} 2692 2693QualType 2694ASTContext::getParenType(QualType InnerType) const { 2695 llvm::FoldingSetNodeID ID; 2696 ParenType::Profile(ID, InnerType); 2697 2698 void *InsertPos = 0; 2699 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2700 if (T) 2701 return QualType(T, 0); 2702 2703 QualType Canon = InnerType; 2704 if (!Canon.isCanonical()) { 2705 Canon = getCanonicalType(InnerType); 2706 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2707 assert(!CheckT && "Paren canonical type broken"); 2708 (void)CheckT; 2709 } 2710 2711 T = new (*this) ParenType(InnerType, Canon); 2712 Types.push_back(T); 2713 ParenTypes.InsertNode(T, InsertPos); 2714 return QualType(T, 0); 2715} 2716 2717QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2718 NestedNameSpecifier *NNS, 2719 const IdentifierInfo *Name, 2720 QualType Canon) const { 2721 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2722 2723 if (Canon.isNull()) { 2724 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2725 ElaboratedTypeKeyword CanonKeyword = Keyword; 2726 if (Keyword == ETK_None) 2727 CanonKeyword = ETK_Typename; 2728 2729 if (CanonNNS != NNS || CanonKeyword != Keyword) 2730 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2731 } 2732 2733 llvm::FoldingSetNodeID ID; 2734 DependentNameType::Profile(ID, Keyword, NNS, Name); 2735 2736 void *InsertPos = 0; 2737 DependentNameType *T 2738 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2739 if (T) 2740 return QualType(T, 0); 2741 2742 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2743 Types.push_back(T); 2744 DependentNameTypes.InsertNode(T, InsertPos); 2745 return QualType(T, 0); 2746} 2747 2748QualType 2749ASTContext::getDependentTemplateSpecializationType( 2750 ElaboratedTypeKeyword Keyword, 2751 NestedNameSpecifier *NNS, 2752 const IdentifierInfo *Name, 2753 const TemplateArgumentListInfo &Args) const { 2754 // TODO: avoid this copy 2755 SmallVector<TemplateArgument, 16> ArgCopy; 2756 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2757 ArgCopy.push_back(Args[I].getArgument()); 2758 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2759 ArgCopy.size(), 2760 ArgCopy.data()); 2761} 2762 2763QualType 2764ASTContext::getDependentTemplateSpecializationType( 2765 ElaboratedTypeKeyword Keyword, 2766 NestedNameSpecifier *NNS, 2767 const IdentifierInfo *Name, 2768 unsigned NumArgs, 2769 const TemplateArgument *Args) const { 2770 assert((!NNS || NNS->isDependent()) && 2771 "nested-name-specifier must be dependent"); 2772 2773 llvm::FoldingSetNodeID ID; 2774 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2775 Name, NumArgs, Args); 2776 2777 void *InsertPos = 0; 2778 DependentTemplateSpecializationType *T 2779 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2780 if (T) 2781 return QualType(T, 0); 2782 2783 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2784 2785 ElaboratedTypeKeyword CanonKeyword = Keyword; 2786 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2787 2788 bool AnyNonCanonArgs = false; 2789 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2790 for (unsigned I = 0; I != NumArgs; ++I) { 2791 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2792 if (!CanonArgs[I].structurallyEquals(Args[I])) 2793 AnyNonCanonArgs = true; 2794 } 2795 2796 QualType Canon; 2797 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2798 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2799 Name, NumArgs, 2800 CanonArgs.data()); 2801 2802 // Find the insert position again. 2803 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2804 } 2805 2806 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2807 sizeof(TemplateArgument) * NumArgs), 2808 TypeAlignment); 2809 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2810 Name, NumArgs, Args, Canon); 2811 Types.push_back(T); 2812 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2813 return QualType(T, 0); 2814} 2815 2816QualType ASTContext::getPackExpansionType(QualType Pattern, 2817 llvm::Optional<unsigned> NumExpansions) { 2818 llvm::FoldingSetNodeID ID; 2819 PackExpansionType::Profile(ID, Pattern, NumExpansions); 2820 2821 assert(Pattern->containsUnexpandedParameterPack() && 2822 "Pack expansions must expand one or more parameter packs"); 2823 void *InsertPos = 0; 2824 PackExpansionType *T 2825 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2826 if (T) 2827 return QualType(T, 0); 2828 2829 QualType Canon; 2830 if (!Pattern.isCanonical()) { 2831 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions); 2832 2833 // Find the insert position again. 2834 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2835 } 2836 2837 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 2838 Types.push_back(T); 2839 PackExpansionTypes.InsertNode(T, InsertPos); 2840 return QualType(T, 0); 2841} 2842 2843/// CmpProtocolNames - Comparison predicate for sorting protocols 2844/// alphabetically. 2845static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2846 const ObjCProtocolDecl *RHS) { 2847 return LHS->getDeclName() < RHS->getDeclName(); 2848} 2849 2850static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2851 unsigned NumProtocols) { 2852 if (NumProtocols == 0) return true; 2853 2854 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 2855 return false; 2856 2857 for (unsigned i = 1; i != NumProtocols; ++i) 2858 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 2859 Protocols[i]->getCanonicalDecl() != Protocols[i]) 2860 return false; 2861 return true; 2862} 2863 2864static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2865 unsigned &NumProtocols) { 2866 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2867 2868 // Sort protocols, keyed by name. 2869 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2870 2871 // Canonicalize. 2872 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 2873 Protocols[I] = Protocols[I]->getCanonicalDecl(); 2874 2875 // Remove duplicates. 2876 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2877 NumProtocols = ProtocolsEnd-Protocols; 2878} 2879 2880QualType ASTContext::getObjCObjectType(QualType BaseType, 2881 ObjCProtocolDecl * const *Protocols, 2882 unsigned NumProtocols) const { 2883 // If the base type is an interface and there aren't any protocols 2884 // to add, then the interface type will do just fine. 2885 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2886 return BaseType; 2887 2888 // Look in the folding set for an existing type. 2889 llvm::FoldingSetNodeID ID; 2890 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2891 void *InsertPos = 0; 2892 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2893 return QualType(QT, 0); 2894 2895 // Build the canonical type, which has the canonical base type and 2896 // a sorted-and-uniqued list of protocols. 2897 QualType Canonical; 2898 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2899 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2900 if (!ProtocolsSorted) { 2901 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2902 Protocols + NumProtocols); 2903 unsigned UniqueCount = NumProtocols; 2904 2905 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2906 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2907 &Sorted[0], UniqueCount); 2908 } else { 2909 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2910 Protocols, NumProtocols); 2911 } 2912 2913 // Regenerate InsertPos. 2914 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2915 } 2916 2917 unsigned Size = sizeof(ObjCObjectTypeImpl); 2918 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2919 void *Mem = Allocate(Size, TypeAlignment); 2920 ObjCObjectTypeImpl *T = 2921 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2922 2923 Types.push_back(T); 2924 ObjCObjectTypes.InsertNode(T, InsertPos); 2925 return QualType(T, 0); 2926} 2927 2928/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2929/// the given object type. 2930QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 2931 llvm::FoldingSetNodeID ID; 2932 ObjCObjectPointerType::Profile(ID, ObjectT); 2933 2934 void *InsertPos = 0; 2935 if (ObjCObjectPointerType *QT = 2936 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2937 return QualType(QT, 0); 2938 2939 // Find the canonical object type. 2940 QualType Canonical; 2941 if (!ObjectT.isCanonical()) { 2942 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2943 2944 // Regenerate InsertPos. 2945 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2946 } 2947 2948 // No match. 2949 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2950 ObjCObjectPointerType *QType = 2951 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2952 2953 Types.push_back(QType); 2954 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2955 return QualType(QType, 0); 2956} 2957 2958/// getObjCInterfaceType - Return the unique reference to the type for the 2959/// specified ObjC interface decl. The list of protocols is optional. 2960QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 2961 ObjCInterfaceDecl *PrevDecl) const { 2962 if (Decl->TypeForDecl) 2963 return QualType(Decl->TypeForDecl, 0); 2964 2965 if (PrevDecl) { 2966 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 2967 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2968 return QualType(PrevDecl->TypeForDecl, 0); 2969 } 2970 2971 // Prefer the definition, if there is one. 2972 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 2973 Decl = Def; 2974 2975 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2976 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2977 Decl->TypeForDecl = T; 2978 Types.push_back(T); 2979 return QualType(T, 0); 2980} 2981 2982/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2983/// TypeOfExprType AST's (since expression's are never shared). For example, 2984/// multiple declarations that refer to "typeof(x)" all contain different 2985/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2986/// on canonical type's (which are always unique). 2987QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 2988 TypeOfExprType *toe; 2989 if (tofExpr->isTypeDependent()) { 2990 llvm::FoldingSetNodeID ID; 2991 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2992 2993 void *InsertPos = 0; 2994 DependentTypeOfExprType *Canon 2995 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2996 if (Canon) { 2997 // We already have a "canonical" version of an identical, dependent 2998 // typeof(expr) type. Use that as our canonical type. 2999 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3000 QualType((TypeOfExprType*)Canon, 0)); 3001 } else { 3002 // Build a new, canonical typeof(expr) type. 3003 Canon 3004 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3005 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3006 toe = Canon; 3007 } 3008 } else { 3009 QualType Canonical = getCanonicalType(tofExpr->getType()); 3010 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3011 } 3012 Types.push_back(toe); 3013 return QualType(toe, 0); 3014} 3015 3016/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3017/// TypeOfType AST's. The only motivation to unique these nodes would be 3018/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3019/// an issue. This doesn't effect the type checker, since it operates 3020/// on canonical type's (which are always unique). 3021QualType ASTContext::getTypeOfType(QualType tofType) const { 3022 QualType Canonical = getCanonicalType(tofType); 3023 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3024 Types.push_back(tot); 3025 return QualType(tot, 0); 3026} 3027 3028 3029/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 3030/// DecltypeType AST's. The only motivation to unique these nodes would be 3031/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 3032/// an issue. This doesn't effect the type checker, since it operates 3033/// on canonical types (which are always unique). 3034QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3035 DecltypeType *dt; 3036 3037 // C++0x [temp.type]p2: 3038 // If an expression e involves a template parameter, decltype(e) denotes a 3039 // unique dependent type. Two such decltype-specifiers refer to the same 3040 // type only if their expressions are equivalent (14.5.6.1). 3041 if (e->isInstantiationDependent()) { 3042 llvm::FoldingSetNodeID ID; 3043 DependentDecltypeType::Profile(ID, *this, e); 3044 3045 void *InsertPos = 0; 3046 DependentDecltypeType *Canon 3047 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3048 if (Canon) { 3049 // We already have a "canonical" version of an equivalent, dependent 3050 // decltype type. Use that as our canonical type. 3051 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 3052 QualType((DecltypeType*)Canon, 0)); 3053 } else { 3054 // Build a new, canonical typeof(expr) type. 3055 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3056 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3057 dt = Canon; 3058 } 3059 } else { 3060 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3061 getCanonicalType(UnderlyingType)); 3062 } 3063 Types.push_back(dt); 3064 return QualType(dt, 0); 3065} 3066 3067/// getUnaryTransformationType - We don't unique these, since the memory 3068/// savings are minimal and these are rare. 3069QualType ASTContext::getUnaryTransformType(QualType BaseType, 3070 QualType UnderlyingType, 3071 UnaryTransformType::UTTKind Kind) 3072 const { 3073 UnaryTransformType *Ty = 3074 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3075 Kind, 3076 UnderlyingType->isDependentType() ? 3077 QualType() : getCanonicalType(UnderlyingType)); 3078 Types.push_back(Ty); 3079 return QualType(Ty, 0); 3080} 3081 3082/// getAutoType - We only unique auto types after they've been deduced. 3083QualType ASTContext::getAutoType(QualType DeducedType) const { 3084 void *InsertPos = 0; 3085 if (!DeducedType.isNull()) { 3086 // Look in the folding set for an existing type. 3087 llvm::FoldingSetNodeID ID; 3088 AutoType::Profile(ID, DeducedType); 3089 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3090 return QualType(AT, 0); 3091 } 3092 3093 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType); 3094 Types.push_back(AT); 3095 if (InsertPos) 3096 AutoTypes.InsertNode(AT, InsertPos); 3097 return QualType(AT, 0); 3098} 3099 3100/// getAtomicType - Return the uniqued reference to the atomic type for 3101/// the given value type. 3102QualType ASTContext::getAtomicType(QualType T) const { 3103 // Unique pointers, to guarantee there is only one pointer of a particular 3104 // structure. 3105 llvm::FoldingSetNodeID ID; 3106 AtomicType::Profile(ID, T); 3107 3108 void *InsertPos = 0; 3109 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3110 return QualType(AT, 0); 3111 3112 // If the atomic value type isn't canonical, this won't be a canonical type 3113 // either, so fill in the canonical type field. 3114 QualType Canonical; 3115 if (!T.isCanonical()) { 3116 Canonical = getAtomicType(getCanonicalType(T)); 3117 3118 // Get the new insert position for the node we care about. 3119 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3120 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3121 } 3122 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3123 Types.push_back(New); 3124 AtomicTypes.InsertNode(New, InsertPos); 3125 return QualType(New, 0); 3126} 3127 3128/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3129QualType ASTContext::getAutoDeductType() const { 3130 if (AutoDeductTy.isNull()) 3131 AutoDeductTy = getAutoType(QualType()); 3132 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern"); 3133 return AutoDeductTy; 3134} 3135 3136/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3137QualType ASTContext::getAutoRRefDeductType() const { 3138 if (AutoRRefDeductTy.isNull()) 3139 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3140 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3141 return AutoRRefDeductTy; 3142} 3143 3144/// getTagDeclType - Return the unique reference to the type for the 3145/// specified TagDecl (struct/union/class/enum) decl. 3146QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3147 assert (Decl); 3148 // FIXME: What is the design on getTagDeclType when it requires casting 3149 // away const? mutable? 3150 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3151} 3152 3153/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3154/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3155/// needs to agree with the definition in <stddef.h>. 3156CanQualType ASTContext::getSizeType() const { 3157 return getFromTargetType(Target->getSizeType()); 3158} 3159 3160/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3161CanQualType ASTContext::getIntMaxType() const { 3162 return getFromTargetType(Target->getIntMaxType()); 3163} 3164 3165/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3166CanQualType ASTContext::getUIntMaxType() const { 3167 return getFromTargetType(Target->getUIntMaxType()); 3168} 3169 3170/// getSignedWCharType - Return the type of "signed wchar_t". 3171/// Used when in C++, as a GCC extension. 3172QualType ASTContext::getSignedWCharType() const { 3173 // FIXME: derive from "Target" ? 3174 return WCharTy; 3175} 3176 3177/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3178/// Used when in C++, as a GCC extension. 3179QualType ASTContext::getUnsignedWCharType() const { 3180 // FIXME: derive from "Target" ? 3181 return UnsignedIntTy; 3182} 3183 3184/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3185/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3186QualType ASTContext::getPointerDiffType() const { 3187 return getFromTargetType(Target->getPtrDiffType(0)); 3188} 3189 3190//===----------------------------------------------------------------------===// 3191// Type Operators 3192//===----------------------------------------------------------------------===// 3193 3194CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3195 // Push qualifiers into arrays, and then discard any remaining 3196 // qualifiers. 3197 T = getCanonicalType(T); 3198 T = getVariableArrayDecayedType(T); 3199 const Type *Ty = T.getTypePtr(); 3200 QualType Result; 3201 if (isa<ArrayType>(Ty)) { 3202 Result = getArrayDecayedType(QualType(Ty,0)); 3203 } else if (isa<FunctionType>(Ty)) { 3204 Result = getPointerType(QualType(Ty, 0)); 3205 } else { 3206 Result = QualType(Ty, 0); 3207 } 3208 3209 return CanQualType::CreateUnsafe(Result); 3210} 3211 3212QualType ASTContext::getUnqualifiedArrayType(QualType type, 3213 Qualifiers &quals) { 3214 SplitQualType splitType = type.getSplitUnqualifiedType(); 3215 3216 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3217 // the unqualified desugared type and then drops it on the floor. 3218 // We then have to strip that sugar back off with 3219 // getUnqualifiedDesugaredType(), which is silly. 3220 const ArrayType *AT = 3221 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3222 3223 // If we don't have an array, just use the results in splitType. 3224 if (!AT) { 3225 quals = splitType.Quals; 3226 return QualType(splitType.Ty, 0); 3227 } 3228 3229 // Otherwise, recurse on the array's element type. 3230 QualType elementType = AT->getElementType(); 3231 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3232 3233 // If that didn't change the element type, AT has no qualifiers, so we 3234 // can just use the results in splitType. 3235 if (elementType == unqualElementType) { 3236 assert(quals.empty()); // from the recursive call 3237 quals = splitType.Quals; 3238 return QualType(splitType.Ty, 0); 3239 } 3240 3241 // Otherwise, add in the qualifiers from the outermost type, then 3242 // build the type back up. 3243 quals.addConsistentQualifiers(splitType.Quals); 3244 3245 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3246 return getConstantArrayType(unqualElementType, CAT->getSize(), 3247 CAT->getSizeModifier(), 0); 3248 } 3249 3250 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3251 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3252 } 3253 3254 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3255 return getVariableArrayType(unqualElementType, 3256 VAT->getSizeExpr(), 3257 VAT->getSizeModifier(), 3258 VAT->getIndexTypeCVRQualifiers(), 3259 VAT->getBracketsRange()); 3260 } 3261 3262 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3263 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3264 DSAT->getSizeModifier(), 0, 3265 SourceRange()); 3266} 3267 3268/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3269/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3270/// they point to and return true. If T1 and T2 aren't pointer types 3271/// or pointer-to-member types, or if they are not similar at this 3272/// level, returns false and leaves T1 and T2 unchanged. Top-level 3273/// qualifiers on T1 and T2 are ignored. This function will typically 3274/// be called in a loop that successively "unwraps" pointer and 3275/// pointer-to-member types to compare them at each level. 3276bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3277 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3278 *T2PtrType = T2->getAs<PointerType>(); 3279 if (T1PtrType && T2PtrType) { 3280 T1 = T1PtrType->getPointeeType(); 3281 T2 = T2PtrType->getPointeeType(); 3282 return true; 3283 } 3284 3285 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3286 *T2MPType = T2->getAs<MemberPointerType>(); 3287 if (T1MPType && T2MPType && 3288 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3289 QualType(T2MPType->getClass(), 0))) { 3290 T1 = T1MPType->getPointeeType(); 3291 T2 = T2MPType->getPointeeType(); 3292 return true; 3293 } 3294 3295 if (getLangOpts().ObjC1) { 3296 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3297 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3298 if (T1OPType && T2OPType) { 3299 T1 = T1OPType->getPointeeType(); 3300 T2 = T2OPType->getPointeeType(); 3301 return true; 3302 } 3303 } 3304 3305 // FIXME: Block pointers, too? 3306 3307 return false; 3308} 3309 3310DeclarationNameInfo 3311ASTContext::getNameForTemplate(TemplateName Name, 3312 SourceLocation NameLoc) const { 3313 switch (Name.getKind()) { 3314 case TemplateName::QualifiedTemplate: 3315 case TemplateName::Template: 3316 // DNInfo work in progress: CHECKME: what about DNLoc? 3317 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3318 NameLoc); 3319 3320 case TemplateName::OverloadedTemplate: { 3321 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3322 // DNInfo work in progress: CHECKME: what about DNLoc? 3323 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3324 } 3325 3326 case TemplateName::DependentTemplate: { 3327 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3328 DeclarationName DName; 3329 if (DTN->isIdentifier()) { 3330 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3331 return DeclarationNameInfo(DName, NameLoc); 3332 } else { 3333 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3334 // DNInfo work in progress: FIXME: source locations? 3335 DeclarationNameLoc DNLoc; 3336 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3337 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3338 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3339 } 3340 } 3341 3342 case TemplateName::SubstTemplateTemplateParm: { 3343 SubstTemplateTemplateParmStorage *subst 3344 = Name.getAsSubstTemplateTemplateParm(); 3345 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3346 NameLoc); 3347 } 3348 3349 case TemplateName::SubstTemplateTemplateParmPack: { 3350 SubstTemplateTemplateParmPackStorage *subst 3351 = Name.getAsSubstTemplateTemplateParmPack(); 3352 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3353 NameLoc); 3354 } 3355 } 3356 3357 llvm_unreachable("bad template name kind!"); 3358} 3359 3360TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3361 switch (Name.getKind()) { 3362 case TemplateName::QualifiedTemplate: 3363 case TemplateName::Template: { 3364 TemplateDecl *Template = Name.getAsTemplateDecl(); 3365 if (TemplateTemplateParmDecl *TTP 3366 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3367 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3368 3369 // The canonical template name is the canonical template declaration. 3370 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3371 } 3372 3373 case TemplateName::OverloadedTemplate: 3374 llvm_unreachable("cannot canonicalize overloaded template"); 3375 3376 case TemplateName::DependentTemplate: { 3377 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3378 assert(DTN && "Non-dependent template names must refer to template decls."); 3379 return DTN->CanonicalTemplateName; 3380 } 3381 3382 case TemplateName::SubstTemplateTemplateParm: { 3383 SubstTemplateTemplateParmStorage *subst 3384 = Name.getAsSubstTemplateTemplateParm(); 3385 return getCanonicalTemplateName(subst->getReplacement()); 3386 } 3387 3388 case TemplateName::SubstTemplateTemplateParmPack: { 3389 SubstTemplateTemplateParmPackStorage *subst 3390 = Name.getAsSubstTemplateTemplateParmPack(); 3391 TemplateTemplateParmDecl *canonParameter 3392 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3393 TemplateArgument canonArgPack 3394 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3395 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3396 } 3397 } 3398 3399 llvm_unreachable("bad template name!"); 3400} 3401 3402bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 3403 X = getCanonicalTemplateName(X); 3404 Y = getCanonicalTemplateName(Y); 3405 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 3406} 3407 3408TemplateArgument 3409ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 3410 switch (Arg.getKind()) { 3411 case TemplateArgument::Null: 3412 return Arg; 3413 3414 case TemplateArgument::Expression: 3415 return Arg; 3416 3417 case TemplateArgument::Declaration: { 3418 if (Decl *D = Arg.getAsDecl()) 3419 return TemplateArgument(D->getCanonicalDecl()); 3420 return TemplateArgument((Decl*)0); 3421 } 3422 3423 case TemplateArgument::Template: 3424 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 3425 3426 case TemplateArgument::TemplateExpansion: 3427 return TemplateArgument(getCanonicalTemplateName( 3428 Arg.getAsTemplateOrTemplatePattern()), 3429 Arg.getNumTemplateExpansions()); 3430 3431 case TemplateArgument::Integral: 3432 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 3433 3434 case TemplateArgument::Type: 3435 return TemplateArgument(getCanonicalType(Arg.getAsType())); 3436 3437 case TemplateArgument::Pack: { 3438 if (Arg.pack_size() == 0) 3439 return Arg; 3440 3441 TemplateArgument *CanonArgs 3442 = new (*this) TemplateArgument[Arg.pack_size()]; 3443 unsigned Idx = 0; 3444 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 3445 AEnd = Arg.pack_end(); 3446 A != AEnd; (void)++A, ++Idx) 3447 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 3448 3449 return TemplateArgument(CanonArgs, Arg.pack_size()); 3450 } 3451 } 3452 3453 // Silence GCC warning 3454 llvm_unreachable("Unhandled template argument kind"); 3455} 3456 3457NestedNameSpecifier * 3458ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 3459 if (!NNS) 3460 return 0; 3461 3462 switch (NNS->getKind()) { 3463 case NestedNameSpecifier::Identifier: 3464 // Canonicalize the prefix but keep the identifier the same. 3465 return NestedNameSpecifier::Create(*this, 3466 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 3467 NNS->getAsIdentifier()); 3468 3469 case NestedNameSpecifier::Namespace: 3470 // A namespace is canonical; build a nested-name-specifier with 3471 // this namespace and no prefix. 3472 return NestedNameSpecifier::Create(*this, 0, 3473 NNS->getAsNamespace()->getOriginalNamespace()); 3474 3475 case NestedNameSpecifier::NamespaceAlias: 3476 // A namespace is canonical; build a nested-name-specifier with 3477 // this namespace and no prefix. 3478 return NestedNameSpecifier::Create(*this, 0, 3479 NNS->getAsNamespaceAlias()->getNamespace() 3480 ->getOriginalNamespace()); 3481 3482 case NestedNameSpecifier::TypeSpec: 3483 case NestedNameSpecifier::TypeSpecWithTemplate: { 3484 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 3485 3486 // If we have some kind of dependent-named type (e.g., "typename T::type"), 3487 // break it apart into its prefix and identifier, then reconsititute those 3488 // as the canonical nested-name-specifier. This is required to canonicalize 3489 // a dependent nested-name-specifier involving typedefs of dependent-name 3490 // types, e.g., 3491 // typedef typename T::type T1; 3492 // typedef typename T1::type T2; 3493 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 3494 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 3495 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 3496 3497 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 3498 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 3499 // first place? 3500 return NestedNameSpecifier::Create(*this, 0, false, 3501 const_cast<Type*>(T.getTypePtr())); 3502 } 3503 3504 case NestedNameSpecifier::Global: 3505 // The global specifier is canonical and unique. 3506 return NNS; 3507 } 3508 3509 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 3510} 3511 3512 3513const ArrayType *ASTContext::getAsArrayType(QualType T) const { 3514 // Handle the non-qualified case efficiently. 3515 if (!T.hasLocalQualifiers()) { 3516 // Handle the common positive case fast. 3517 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 3518 return AT; 3519 } 3520 3521 // Handle the common negative case fast. 3522 if (!isa<ArrayType>(T.getCanonicalType())) 3523 return 0; 3524 3525 // Apply any qualifiers from the array type to the element type. This 3526 // implements C99 6.7.3p8: "If the specification of an array type includes 3527 // any type qualifiers, the element type is so qualified, not the array type." 3528 3529 // If we get here, we either have type qualifiers on the type, or we have 3530 // sugar such as a typedef in the way. If we have type qualifiers on the type 3531 // we must propagate them down into the element type. 3532 3533 SplitQualType split = T.getSplitDesugaredType(); 3534 Qualifiers qs = split.Quals; 3535 3536 // If we have a simple case, just return now. 3537 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 3538 if (ATy == 0 || qs.empty()) 3539 return ATy; 3540 3541 // Otherwise, we have an array and we have qualifiers on it. Push the 3542 // qualifiers into the array element type and return a new array type. 3543 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 3544 3545 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 3546 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 3547 CAT->getSizeModifier(), 3548 CAT->getIndexTypeCVRQualifiers())); 3549 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 3550 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 3551 IAT->getSizeModifier(), 3552 IAT->getIndexTypeCVRQualifiers())); 3553 3554 if (const DependentSizedArrayType *DSAT 3555 = dyn_cast<DependentSizedArrayType>(ATy)) 3556 return cast<ArrayType>( 3557 getDependentSizedArrayType(NewEltTy, 3558 DSAT->getSizeExpr(), 3559 DSAT->getSizeModifier(), 3560 DSAT->getIndexTypeCVRQualifiers(), 3561 DSAT->getBracketsRange())); 3562 3563 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 3564 return cast<ArrayType>(getVariableArrayType(NewEltTy, 3565 VAT->getSizeExpr(), 3566 VAT->getSizeModifier(), 3567 VAT->getIndexTypeCVRQualifiers(), 3568 VAT->getBracketsRange())); 3569} 3570 3571QualType ASTContext::getAdjustedParameterType(QualType T) const { 3572 // C99 6.7.5.3p7: 3573 // A declaration of a parameter as "array of type" shall be 3574 // adjusted to "qualified pointer to type", where the type 3575 // qualifiers (if any) are those specified within the [ and ] of 3576 // the array type derivation. 3577 if (T->isArrayType()) 3578 return getArrayDecayedType(T); 3579 3580 // C99 6.7.5.3p8: 3581 // A declaration of a parameter as "function returning type" 3582 // shall be adjusted to "pointer to function returning type", as 3583 // in 6.3.2.1. 3584 if (T->isFunctionType()) 3585 return getPointerType(T); 3586 3587 return T; 3588} 3589 3590QualType ASTContext::getSignatureParameterType(QualType T) const { 3591 T = getVariableArrayDecayedType(T); 3592 T = getAdjustedParameterType(T); 3593 return T.getUnqualifiedType(); 3594} 3595 3596/// getArrayDecayedType - Return the properly qualified result of decaying the 3597/// specified array type to a pointer. This operation is non-trivial when 3598/// handling typedefs etc. The canonical type of "T" must be an array type, 3599/// this returns a pointer to a properly qualified element of the array. 3600/// 3601/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 3602QualType ASTContext::getArrayDecayedType(QualType Ty) const { 3603 // Get the element type with 'getAsArrayType' so that we don't lose any 3604 // typedefs in the element type of the array. This also handles propagation 3605 // of type qualifiers from the array type into the element type if present 3606 // (C99 6.7.3p8). 3607 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 3608 assert(PrettyArrayType && "Not an array type!"); 3609 3610 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 3611 3612 // int x[restrict 4] -> int *restrict 3613 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 3614} 3615 3616QualType ASTContext::getBaseElementType(const ArrayType *array) const { 3617 return getBaseElementType(array->getElementType()); 3618} 3619 3620QualType ASTContext::getBaseElementType(QualType type) const { 3621 Qualifiers qs; 3622 while (true) { 3623 SplitQualType split = type.getSplitDesugaredType(); 3624 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 3625 if (!array) break; 3626 3627 type = array->getElementType(); 3628 qs.addConsistentQualifiers(split.Quals); 3629 } 3630 3631 return getQualifiedType(type, qs); 3632} 3633 3634/// getConstantArrayElementCount - Returns number of constant array elements. 3635uint64_t 3636ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 3637 uint64_t ElementCount = 1; 3638 do { 3639 ElementCount *= CA->getSize().getZExtValue(); 3640 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 3641 } while (CA); 3642 return ElementCount; 3643} 3644 3645/// getFloatingRank - Return a relative rank for floating point types. 3646/// This routine will assert if passed a built-in type that isn't a float. 3647static FloatingRank getFloatingRank(QualType T) { 3648 if (const ComplexType *CT = T->getAs<ComplexType>()) 3649 return getFloatingRank(CT->getElementType()); 3650 3651 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 3652 switch (T->getAs<BuiltinType>()->getKind()) { 3653 default: llvm_unreachable("getFloatingRank(): not a floating type"); 3654 case BuiltinType::Half: return HalfRank; 3655 case BuiltinType::Float: return FloatRank; 3656 case BuiltinType::Double: return DoubleRank; 3657 case BuiltinType::LongDouble: return LongDoubleRank; 3658 } 3659} 3660 3661/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 3662/// point or a complex type (based on typeDomain/typeSize). 3663/// 'typeDomain' is a real floating point or complex type. 3664/// 'typeSize' is a real floating point or complex type. 3665QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 3666 QualType Domain) const { 3667 FloatingRank EltRank = getFloatingRank(Size); 3668 if (Domain->isComplexType()) { 3669 switch (EltRank) { 3670 case HalfRank: llvm_unreachable("Complex half is not supported"); 3671 case FloatRank: return FloatComplexTy; 3672 case DoubleRank: return DoubleComplexTy; 3673 case LongDoubleRank: return LongDoubleComplexTy; 3674 } 3675 } 3676 3677 assert(Domain->isRealFloatingType() && "Unknown domain!"); 3678 switch (EltRank) { 3679 case HalfRank: llvm_unreachable("Half ranks are not valid here"); 3680 case FloatRank: return FloatTy; 3681 case DoubleRank: return DoubleTy; 3682 case LongDoubleRank: return LongDoubleTy; 3683 } 3684 llvm_unreachable("getFloatingRank(): illegal value for rank"); 3685} 3686 3687/// getFloatingTypeOrder - Compare the rank of the two specified floating 3688/// point types, ignoring the domain of the type (i.e. 'double' == 3689/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 3690/// LHS < RHS, return -1. 3691int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 3692 FloatingRank LHSR = getFloatingRank(LHS); 3693 FloatingRank RHSR = getFloatingRank(RHS); 3694 3695 if (LHSR == RHSR) 3696 return 0; 3697 if (LHSR > RHSR) 3698 return 1; 3699 return -1; 3700} 3701 3702/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 3703/// routine will assert if passed a built-in type that isn't an integer or enum, 3704/// or if it is not canonicalized. 3705unsigned ASTContext::getIntegerRank(const Type *T) const { 3706 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 3707 3708 switch (cast<BuiltinType>(T)->getKind()) { 3709 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 3710 case BuiltinType::Bool: 3711 return 1 + (getIntWidth(BoolTy) << 3); 3712 case BuiltinType::Char_S: 3713 case BuiltinType::Char_U: 3714 case BuiltinType::SChar: 3715 case BuiltinType::UChar: 3716 return 2 + (getIntWidth(CharTy) << 3); 3717 case BuiltinType::Short: 3718 case BuiltinType::UShort: 3719 return 3 + (getIntWidth(ShortTy) << 3); 3720 case BuiltinType::Int: 3721 case BuiltinType::UInt: 3722 return 4 + (getIntWidth(IntTy) << 3); 3723 case BuiltinType::Long: 3724 case BuiltinType::ULong: 3725 return 5 + (getIntWidth(LongTy) << 3); 3726 case BuiltinType::LongLong: 3727 case BuiltinType::ULongLong: 3728 return 6 + (getIntWidth(LongLongTy) << 3); 3729 case BuiltinType::Int128: 3730 case BuiltinType::UInt128: 3731 return 7 + (getIntWidth(Int128Ty) << 3); 3732 } 3733} 3734 3735/// \brief Whether this is a promotable bitfield reference according 3736/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3737/// 3738/// \returns the type this bit-field will promote to, or NULL if no 3739/// promotion occurs. 3740QualType ASTContext::isPromotableBitField(Expr *E) const { 3741 if (E->isTypeDependent() || E->isValueDependent()) 3742 return QualType(); 3743 3744 FieldDecl *Field = E->getBitField(); 3745 if (!Field) 3746 return QualType(); 3747 3748 QualType FT = Field->getType(); 3749 3750 uint64_t BitWidth = Field->getBitWidthValue(*this); 3751 uint64_t IntSize = getTypeSize(IntTy); 3752 // GCC extension compatibility: if the bit-field size is less than or equal 3753 // to the size of int, it gets promoted no matter what its type is. 3754 // For instance, unsigned long bf : 4 gets promoted to signed int. 3755 if (BitWidth < IntSize) 3756 return IntTy; 3757 3758 if (BitWidth == IntSize) 3759 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3760 3761 // Types bigger than int are not subject to promotions, and therefore act 3762 // like the base type. 3763 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3764 // is ridiculous. 3765 return QualType(); 3766} 3767 3768/// getPromotedIntegerType - Returns the type that Promotable will 3769/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3770/// integer type. 3771QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 3772 assert(!Promotable.isNull()); 3773 assert(Promotable->isPromotableIntegerType()); 3774 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3775 return ET->getDecl()->getPromotionType(); 3776 3777 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 3778 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 3779 // (3.9.1) can be converted to a prvalue of the first of the following 3780 // types that can represent all the values of its underlying type: 3781 // int, unsigned int, long int, unsigned long int, long long int, or 3782 // unsigned long long int [...] 3783 // FIXME: Is there some better way to compute this? 3784 if (BT->getKind() == BuiltinType::WChar_S || 3785 BT->getKind() == BuiltinType::WChar_U || 3786 BT->getKind() == BuiltinType::Char16 || 3787 BT->getKind() == BuiltinType::Char32) { 3788 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 3789 uint64_t FromSize = getTypeSize(BT); 3790 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 3791 LongLongTy, UnsignedLongLongTy }; 3792 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 3793 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 3794 if (FromSize < ToSize || 3795 (FromSize == ToSize && 3796 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 3797 return PromoteTypes[Idx]; 3798 } 3799 llvm_unreachable("char type should fit into long long"); 3800 } 3801 } 3802 3803 // At this point, we should have a signed or unsigned integer type. 3804 if (Promotable->isSignedIntegerType()) 3805 return IntTy; 3806 uint64_t PromotableSize = getTypeSize(Promotable); 3807 uint64_t IntSize = getTypeSize(IntTy); 3808 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 3809 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 3810} 3811 3812/// \brief Recurses in pointer/array types until it finds an objc retainable 3813/// type and returns its ownership. 3814Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 3815 while (!T.isNull()) { 3816 if (T.getObjCLifetime() != Qualifiers::OCL_None) 3817 return T.getObjCLifetime(); 3818 if (T->isArrayType()) 3819 T = getBaseElementType(T); 3820 else if (const PointerType *PT = T->getAs<PointerType>()) 3821 T = PT->getPointeeType(); 3822 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3823 T = RT->getPointeeType(); 3824 else 3825 break; 3826 } 3827 3828 return Qualifiers::OCL_None; 3829} 3830 3831/// getIntegerTypeOrder - Returns the highest ranked integer type: 3832/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 3833/// LHS < RHS, return -1. 3834int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 3835 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 3836 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 3837 if (LHSC == RHSC) return 0; 3838 3839 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 3840 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 3841 3842 unsigned LHSRank = getIntegerRank(LHSC); 3843 unsigned RHSRank = getIntegerRank(RHSC); 3844 3845 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 3846 if (LHSRank == RHSRank) return 0; 3847 return LHSRank > RHSRank ? 1 : -1; 3848 } 3849 3850 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3851 if (LHSUnsigned) { 3852 // If the unsigned [LHS] type is larger, return it. 3853 if (LHSRank >= RHSRank) 3854 return 1; 3855 3856 // If the signed type can represent all values of the unsigned type, it 3857 // wins. Because we are dealing with 2's complement and types that are 3858 // powers of two larger than each other, this is always safe. 3859 return -1; 3860 } 3861 3862 // If the unsigned [RHS] type is larger, return it. 3863 if (RHSRank >= LHSRank) 3864 return -1; 3865 3866 // If the signed type can represent all values of the unsigned type, it 3867 // wins. Because we are dealing with 2's complement and types that are 3868 // powers of two larger than each other, this is always safe. 3869 return 1; 3870} 3871 3872static RecordDecl * 3873CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 3874 DeclContext *DC, IdentifierInfo *Id) { 3875 SourceLocation Loc; 3876 if (Ctx.getLangOpts().CPlusPlus) 3877 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3878 else 3879 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3880} 3881 3882// getCFConstantStringType - Return the type used for constant CFStrings. 3883QualType ASTContext::getCFConstantStringType() const { 3884 if (!CFConstantStringTypeDecl) { 3885 CFConstantStringTypeDecl = 3886 CreateRecordDecl(*this, TTK_Struct, TUDecl, 3887 &Idents.get("NSConstantString")); 3888 CFConstantStringTypeDecl->startDefinition(); 3889 3890 QualType FieldTypes[4]; 3891 3892 // const int *isa; 3893 FieldTypes[0] = getPointerType(IntTy.withConst()); 3894 // int flags; 3895 FieldTypes[1] = IntTy; 3896 // const char *str; 3897 FieldTypes[2] = getPointerType(CharTy.withConst()); 3898 // long length; 3899 FieldTypes[3] = LongTy; 3900 3901 // Create fields 3902 for (unsigned i = 0; i < 4; ++i) { 3903 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 3904 SourceLocation(), 3905 SourceLocation(), 0, 3906 FieldTypes[i], /*TInfo=*/0, 3907 /*BitWidth=*/0, 3908 /*Mutable=*/false, 3909 ICIS_NoInit); 3910 Field->setAccess(AS_public); 3911 CFConstantStringTypeDecl->addDecl(Field); 3912 } 3913 3914 CFConstantStringTypeDecl->completeDefinition(); 3915 } 3916 3917 return getTagDeclType(CFConstantStringTypeDecl); 3918} 3919 3920void ASTContext::setCFConstantStringType(QualType T) { 3921 const RecordType *Rec = T->getAs<RecordType>(); 3922 assert(Rec && "Invalid CFConstantStringType"); 3923 CFConstantStringTypeDecl = Rec->getDecl(); 3924} 3925 3926QualType ASTContext::getBlockDescriptorType() const { 3927 if (BlockDescriptorType) 3928 return getTagDeclType(BlockDescriptorType); 3929 3930 RecordDecl *T; 3931 // FIXME: Needs the FlagAppleBlock bit. 3932 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3933 &Idents.get("__block_descriptor")); 3934 T->startDefinition(); 3935 3936 QualType FieldTypes[] = { 3937 UnsignedLongTy, 3938 UnsignedLongTy, 3939 }; 3940 3941 const char *FieldNames[] = { 3942 "reserved", 3943 "Size" 3944 }; 3945 3946 for (size_t i = 0; i < 2; ++i) { 3947 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3948 SourceLocation(), 3949 &Idents.get(FieldNames[i]), 3950 FieldTypes[i], /*TInfo=*/0, 3951 /*BitWidth=*/0, 3952 /*Mutable=*/false, 3953 ICIS_NoInit); 3954 Field->setAccess(AS_public); 3955 T->addDecl(Field); 3956 } 3957 3958 T->completeDefinition(); 3959 3960 BlockDescriptorType = T; 3961 3962 return getTagDeclType(BlockDescriptorType); 3963} 3964 3965QualType ASTContext::getBlockDescriptorExtendedType() const { 3966 if (BlockDescriptorExtendedType) 3967 return getTagDeclType(BlockDescriptorExtendedType); 3968 3969 RecordDecl *T; 3970 // FIXME: Needs the FlagAppleBlock bit. 3971 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 3972 &Idents.get("__block_descriptor_withcopydispose")); 3973 T->startDefinition(); 3974 3975 QualType FieldTypes[] = { 3976 UnsignedLongTy, 3977 UnsignedLongTy, 3978 getPointerType(VoidPtrTy), 3979 getPointerType(VoidPtrTy) 3980 }; 3981 3982 const char *FieldNames[] = { 3983 "reserved", 3984 "Size", 3985 "CopyFuncPtr", 3986 "DestroyFuncPtr" 3987 }; 3988 3989 for (size_t i = 0; i < 4; ++i) { 3990 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3991 SourceLocation(), 3992 &Idents.get(FieldNames[i]), 3993 FieldTypes[i], /*TInfo=*/0, 3994 /*BitWidth=*/0, 3995 /*Mutable=*/false, 3996 ICIS_NoInit); 3997 Field->setAccess(AS_public); 3998 T->addDecl(Field); 3999 } 4000 4001 T->completeDefinition(); 4002 4003 BlockDescriptorExtendedType = T; 4004 4005 return getTagDeclType(BlockDescriptorExtendedType); 4006} 4007 4008bool ASTContext::BlockRequiresCopying(QualType Ty) const { 4009 if (Ty->isObjCRetainableType()) 4010 return true; 4011 if (getLangOpts().CPlusPlus) { 4012 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4013 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4014 return RD->hasConstCopyConstructor(); 4015 4016 } 4017 } 4018 return false; 4019} 4020 4021QualType 4022ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const { 4023 // type = struct __Block_byref_1_X { 4024 // void *__isa; 4025 // struct __Block_byref_1_X *__forwarding; 4026 // unsigned int __flags; 4027 // unsigned int __size; 4028 // void *__copy_helper; // as needed 4029 // void *__destroy_help // as needed 4030 // int X; 4031 // } * 4032 4033 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 4034 4035 // FIXME: Move up 4036 SmallString<36> Name; 4037 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 4038 ++UniqueBlockByRefTypeID << '_' << DeclName; 4039 RecordDecl *T; 4040 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str())); 4041 T->startDefinition(); 4042 QualType Int32Ty = IntTy; 4043 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 4044 QualType FieldTypes[] = { 4045 getPointerType(VoidPtrTy), 4046 getPointerType(getTagDeclType(T)), 4047 Int32Ty, 4048 Int32Ty, 4049 getPointerType(VoidPtrTy), 4050 getPointerType(VoidPtrTy), 4051 Ty 4052 }; 4053 4054 StringRef FieldNames[] = { 4055 "__isa", 4056 "__forwarding", 4057 "__flags", 4058 "__size", 4059 "__copy_helper", 4060 "__destroy_helper", 4061 DeclName, 4062 }; 4063 4064 for (size_t i = 0; i < 7; ++i) { 4065 if (!HasCopyAndDispose && i >=4 && i <= 5) 4066 continue; 4067 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4068 SourceLocation(), 4069 &Idents.get(FieldNames[i]), 4070 FieldTypes[i], /*TInfo=*/0, 4071 /*BitWidth=*/0, /*Mutable=*/false, 4072 ICIS_NoInit); 4073 Field->setAccess(AS_public); 4074 T->addDecl(Field); 4075 } 4076 4077 T->completeDefinition(); 4078 4079 return getPointerType(getTagDeclType(T)); 4080} 4081 4082TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4083 if (!ObjCInstanceTypeDecl) 4084 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 4085 getTranslationUnitDecl(), 4086 SourceLocation(), 4087 SourceLocation(), 4088 &Idents.get("instancetype"), 4089 getTrivialTypeSourceInfo(getObjCIdType())); 4090 return ObjCInstanceTypeDecl; 4091} 4092 4093// This returns true if a type has been typedefed to BOOL: 4094// typedef <type> BOOL; 4095static bool isTypeTypedefedAsBOOL(QualType T) { 4096 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4097 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4098 return II->isStr("BOOL"); 4099 4100 return false; 4101} 4102 4103/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4104/// purpose. 4105CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4106 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4107 return CharUnits::Zero(); 4108 4109 CharUnits sz = getTypeSizeInChars(type); 4110 4111 // Make all integer and enum types at least as large as an int 4112 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4113 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4114 // Treat arrays as pointers, since that's how they're passed in. 4115 else if (type->isArrayType()) 4116 sz = getTypeSizeInChars(VoidPtrTy); 4117 return sz; 4118} 4119 4120static inline 4121std::string charUnitsToString(const CharUnits &CU) { 4122 return llvm::itostr(CU.getQuantity()); 4123} 4124 4125/// getObjCEncodingForBlock - Return the encoded type for this block 4126/// declaration. 4127std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4128 std::string S; 4129 4130 const BlockDecl *Decl = Expr->getBlockDecl(); 4131 QualType BlockTy = 4132 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4133 // Encode result type. 4134 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 4135 // Compute size of all parameters. 4136 // Start with computing size of a pointer in number of bytes. 4137 // FIXME: There might(should) be a better way of doing this computation! 4138 SourceLocation Loc; 4139 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4140 CharUnits ParmOffset = PtrSize; 4141 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4142 E = Decl->param_end(); PI != E; ++PI) { 4143 QualType PType = (*PI)->getType(); 4144 CharUnits sz = getObjCEncodingTypeSize(PType); 4145 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4146 ParmOffset += sz; 4147 } 4148 // Size of the argument frame 4149 S += charUnitsToString(ParmOffset); 4150 // Block pointer and offset. 4151 S += "@?0"; 4152 4153 // Argument types. 4154 ParmOffset = PtrSize; 4155 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4156 Decl->param_end(); PI != E; ++PI) { 4157 ParmVarDecl *PVDecl = *PI; 4158 QualType PType = PVDecl->getOriginalType(); 4159 if (const ArrayType *AT = 4160 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4161 // Use array's original type only if it has known number of 4162 // elements. 4163 if (!isa<ConstantArrayType>(AT)) 4164 PType = PVDecl->getType(); 4165 } else if (PType->isFunctionType()) 4166 PType = PVDecl->getType(); 4167 getObjCEncodingForType(PType, S); 4168 S += charUnitsToString(ParmOffset); 4169 ParmOffset += getObjCEncodingTypeSize(PType); 4170 } 4171 4172 return S; 4173} 4174 4175bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4176 std::string& S) { 4177 // Encode result type. 4178 getObjCEncodingForType(Decl->getResultType(), S); 4179 CharUnits ParmOffset; 4180 // Compute size of all parameters. 4181 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4182 E = Decl->param_end(); PI != E; ++PI) { 4183 QualType PType = (*PI)->getType(); 4184 CharUnits sz = getObjCEncodingTypeSize(PType); 4185 if (sz.isZero()) 4186 return true; 4187 4188 assert (sz.isPositive() && 4189 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4190 ParmOffset += sz; 4191 } 4192 S += charUnitsToString(ParmOffset); 4193 ParmOffset = CharUnits::Zero(); 4194 4195 // Argument types. 4196 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4197 E = Decl->param_end(); PI != E; ++PI) { 4198 ParmVarDecl *PVDecl = *PI; 4199 QualType PType = PVDecl->getOriginalType(); 4200 if (const ArrayType *AT = 4201 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4202 // Use array's original type only if it has known number of 4203 // elements. 4204 if (!isa<ConstantArrayType>(AT)) 4205 PType = PVDecl->getType(); 4206 } else if (PType->isFunctionType()) 4207 PType = PVDecl->getType(); 4208 getObjCEncodingForType(PType, S); 4209 S += charUnitsToString(ParmOffset); 4210 ParmOffset += getObjCEncodingTypeSize(PType); 4211 } 4212 4213 return false; 4214} 4215 4216/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4217/// method parameter or return type. If Extended, include class names and 4218/// block object types. 4219void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4220 QualType T, std::string& S, 4221 bool Extended) const { 4222 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4223 getObjCEncodingForTypeQualifier(QT, S); 4224 // Encode parameter type. 4225 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4226 true /*OutermostType*/, 4227 false /*EncodingProperty*/, 4228 false /*StructField*/, 4229 Extended /*EncodeBlockParameters*/, 4230 Extended /*EncodeClassNames*/); 4231} 4232 4233/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4234/// declaration. 4235bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4236 std::string& S, 4237 bool Extended) const { 4238 // FIXME: This is not very efficient. 4239 // Encode return type. 4240 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4241 Decl->getResultType(), S, Extended); 4242 // Compute size of all parameters. 4243 // Start with computing size of a pointer in number of bytes. 4244 // FIXME: There might(should) be a better way of doing this computation! 4245 SourceLocation Loc; 4246 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4247 // The first two arguments (self and _cmd) are pointers; account for 4248 // their size. 4249 CharUnits ParmOffset = 2 * PtrSize; 4250 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4251 E = Decl->sel_param_end(); PI != E; ++PI) { 4252 QualType PType = (*PI)->getType(); 4253 CharUnits sz = getObjCEncodingTypeSize(PType); 4254 if (sz.isZero()) 4255 return true; 4256 4257 assert (sz.isPositive() && 4258 "getObjCEncodingForMethodDecl - Incomplete param type"); 4259 ParmOffset += sz; 4260 } 4261 S += charUnitsToString(ParmOffset); 4262 S += "@0:"; 4263 S += charUnitsToString(PtrSize); 4264 4265 // Argument types. 4266 ParmOffset = 2 * PtrSize; 4267 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4268 E = Decl->sel_param_end(); PI != E; ++PI) { 4269 const ParmVarDecl *PVDecl = *PI; 4270 QualType PType = PVDecl->getOriginalType(); 4271 if (const ArrayType *AT = 4272 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4273 // Use array's original type only if it has known number of 4274 // elements. 4275 if (!isa<ConstantArrayType>(AT)) 4276 PType = PVDecl->getType(); 4277 } else if (PType->isFunctionType()) 4278 PType = PVDecl->getType(); 4279 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4280 PType, S, Extended); 4281 S += charUnitsToString(ParmOffset); 4282 ParmOffset += getObjCEncodingTypeSize(PType); 4283 } 4284 4285 return false; 4286} 4287 4288/// getObjCEncodingForPropertyDecl - Return the encoded type for this 4289/// property declaration. If non-NULL, Container must be either an 4290/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4291/// NULL when getting encodings for protocol properties. 4292/// Property attributes are stored as a comma-delimited C string. The simple 4293/// attributes readonly and bycopy are encoded as single characters. The 4294/// parametrized attributes, getter=name, setter=name, and ivar=name, are 4295/// encoded as single characters, followed by an identifier. Property types 4296/// are also encoded as a parametrized attribute. The characters used to encode 4297/// these attributes are defined by the following enumeration: 4298/// @code 4299/// enum PropertyAttributes { 4300/// kPropertyReadOnly = 'R', // property is read-only. 4301/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4302/// kPropertyByref = '&', // property is a reference to the value last assigned 4303/// kPropertyDynamic = 'D', // property is dynamic 4304/// kPropertyGetter = 'G', // followed by getter selector name 4305/// kPropertySetter = 'S', // followed by setter selector name 4306/// kPropertyInstanceVariable = 'V' // followed by instance variable name 4307/// kPropertyType = 'T' // followed by old-style type encoding. 4308/// kPropertyWeak = 'W' // 'weak' property 4309/// kPropertyStrong = 'P' // property GC'able 4310/// kPropertyNonAtomic = 'N' // property non-atomic 4311/// }; 4312/// @endcode 4313void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4314 const Decl *Container, 4315 std::string& S) const { 4316 // Collect information from the property implementation decl(s). 4317 bool Dynamic = false; 4318 ObjCPropertyImplDecl *SynthesizePID = 0; 4319 4320 // FIXME: Duplicated code due to poor abstraction. 4321 if (Container) { 4322 if (const ObjCCategoryImplDecl *CID = 4323 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4324 for (ObjCCategoryImplDecl::propimpl_iterator 4325 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4326 i != e; ++i) { 4327 ObjCPropertyImplDecl *PID = *i; 4328 if (PID->getPropertyDecl() == PD) { 4329 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4330 Dynamic = true; 4331 } else { 4332 SynthesizePID = PID; 4333 } 4334 } 4335 } 4336 } else { 4337 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4338 for (ObjCCategoryImplDecl::propimpl_iterator 4339 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4340 i != e; ++i) { 4341 ObjCPropertyImplDecl *PID = *i; 4342 if (PID->getPropertyDecl() == PD) { 4343 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4344 Dynamic = true; 4345 } else { 4346 SynthesizePID = PID; 4347 } 4348 } 4349 } 4350 } 4351 } 4352 4353 // FIXME: This is not very efficient. 4354 S = "T"; 4355 4356 // Encode result type. 4357 // GCC has some special rules regarding encoding of properties which 4358 // closely resembles encoding of ivars. 4359 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4360 true /* outermost type */, 4361 true /* encoding for property */); 4362 4363 if (PD->isReadOnly()) { 4364 S += ",R"; 4365 } else { 4366 switch (PD->getSetterKind()) { 4367 case ObjCPropertyDecl::Assign: break; 4368 case ObjCPropertyDecl::Copy: S += ",C"; break; 4369 case ObjCPropertyDecl::Retain: S += ",&"; break; 4370 case ObjCPropertyDecl::Weak: S += ",W"; break; 4371 } 4372 } 4373 4374 // It really isn't clear at all what this means, since properties 4375 // are "dynamic by default". 4376 if (Dynamic) 4377 S += ",D"; 4378 4379 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4380 S += ",N"; 4381 4382 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4383 S += ",G"; 4384 S += PD->getGetterName().getAsString(); 4385 } 4386 4387 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4388 S += ",S"; 4389 S += PD->getSetterName().getAsString(); 4390 } 4391 4392 if (SynthesizePID) { 4393 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4394 S += ",V"; 4395 S += OID->getNameAsString(); 4396 } 4397 4398 // FIXME: OBJCGC: weak & strong 4399} 4400 4401/// getLegacyIntegralTypeEncoding - 4402/// Another legacy compatibility encoding: 32-bit longs are encoded as 4403/// 'l' or 'L' , but not always. For typedefs, we need to use 4404/// 'i' or 'I' instead if encoding a struct field, or a pointer! 4405/// 4406void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 4407 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 4408 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 4409 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 4410 PointeeTy = UnsignedIntTy; 4411 else 4412 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 4413 PointeeTy = IntTy; 4414 } 4415 } 4416} 4417 4418void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 4419 const FieldDecl *Field) const { 4420 // We follow the behavior of gcc, expanding structures which are 4421 // directly pointed to, and expanding embedded structures. Note that 4422 // these rules are sufficient to prevent recursive encoding of the 4423 // same type. 4424 getObjCEncodingForTypeImpl(T, S, true, true, Field, 4425 true /* outermost type */); 4426} 4427 4428static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 4429 switch (T->getAs<BuiltinType>()->getKind()) { 4430 default: llvm_unreachable("Unhandled builtin type kind"); 4431 case BuiltinType::Void: return 'v'; 4432 case BuiltinType::Bool: return 'B'; 4433 case BuiltinType::Char_U: 4434 case BuiltinType::UChar: return 'C'; 4435 case BuiltinType::UShort: return 'S'; 4436 case BuiltinType::UInt: return 'I'; 4437 case BuiltinType::ULong: 4438 return C->getIntWidth(T) == 32 ? 'L' : 'Q'; 4439 case BuiltinType::UInt128: return 'T'; 4440 case BuiltinType::ULongLong: return 'Q'; 4441 case BuiltinType::Char_S: 4442 case BuiltinType::SChar: return 'c'; 4443 case BuiltinType::Short: return 's'; 4444 case BuiltinType::WChar_S: 4445 case BuiltinType::WChar_U: 4446 case BuiltinType::Int: return 'i'; 4447 case BuiltinType::Long: 4448 return C->getIntWidth(T) == 32 ? 'l' : 'q'; 4449 case BuiltinType::LongLong: return 'q'; 4450 case BuiltinType::Int128: return 't'; 4451 case BuiltinType::Float: return 'f'; 4452 case BuiltinType::Double: return 'd'; 4453 case BuiltinType::LongDouble: return 'D'; 4454 } 4455} 4456 4457static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 4458 EnumDecl *Enum = ET->getDecl(); 4459 4460 // The encoding of an non-fixed enum type is always 'i', regardless of size. 4461 if (!Enum->isFixed()) 4462 return 'i'; 4463 4464 // The encoding of a fixed enum type matches its fixed underlying type. 4465 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType()); 4466} 4467 4468static void EncodeBitField(const ASTContext *Ctx, std::string& S, 4469 QualType T, const FieldDecl *FD) { 4470 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 4471 S += 'b'; 4472 // The NeXT runtime encodes bit fields as b followed by the number of bits. 4473 // The GNU runtime requires more information; bitfields are encoded as b, 4474 // then the offset (in bits) of the first element, then the type of the 4475 // bitfield, then the size in bits. For example, in this structure: 4476 // 4477 // struct 4478 // { 4479 // int integer; 4480 // int flags:2; 4481 // }; 4482 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 4483 // runtime, but b32i2 for the GNU runtime. The reason for this extra 4484 // information is not especially sensible, but we're stuck with it for 4485 // compatibility with GCC, although providing it breaks anything that 4486 // actually uses runtime introspection and wants to work on both runtimes... 4487 if (!Ctx->getLangOpts().NeXTRuntime) { 4488 const RecordDecl *RD = FD->getParent(); 4489 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 4490 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 4491 if (const EnumType *ET = T->getAs<EnumType>()) 4492 S += ObjCEncodingForEnumType(Ctx, ET); 4493 else 4494 S += ObjCEncodingForPrimitiveKind(Ctx, T); 4495 } 4496 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 4497} 4498 4499// FIXME: Use SmallString for accumulating string. 4500void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 4501 bool ExpandPointedToStructures, 4502 bool ExpandStructures, 4503 const FieldDecl *FD, 4504 bool OutermostType, 4505 bool EncodingProperty, 4506 bool StructField, 4507 bool EncodeBlockParameters, 4508 bool EncodeClassNames) const { 4509 if (T->getAs<BuiltinType>()) { 4510 if (FD && FD->isBitField()) 4511 return EncodeBitField(this, S, T, FD); 4512 S += ObjCEncodingForPrimitiveKind(this, T); 4513 return; 4514 } 4515 4516 if (const ComplexType *CT = T->getAs<ComplexType>()) { 4517 S += 'j'; 4518 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 4519 false); 4520 return; 4521 } 4522 4523 // encoding for pointer or r3eference types. 4524 QualType PointeeTy; 4525 if (const PointerType *PT = T->getAs<PointerType>()) { 4526 if (PT->isObjCSelType()) { 4527 S += ':'; 4528 return; 4529 } 4530 PointeeTy = PT->getPointeeType(); 4531 } 4532 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4533 PointeeTy = RT->getPointeeType(); 4534 if (!PointeeTy.isNull()) { 4535 bool isReadOnly = false; 4536 // For historical/compatibility reasons, the read-only qualifier of the 4537 // pointee gets emitted _before_ the '^'. The read-only qualifier of 4538 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 4539 // Also, do not emit the 'r' for anything but the outermost type! 4540 if (isa<TypedefType>(T.getTypePtr())) { 4541 if (OutermostType && T.isConstQualified()) { 4542 isReadOnly = true; 4543 S += 'r'; 4544 } 4545 } else if (OutermostType) { 4546 QualType P = PointeeTy; 4547 while (P->getAs<PointerType>()) 4548 P = P->getAs<PointerType>()->getPointeeType(); 4549 if (P.isConstQualified()) { 4550 isReadOnly = true; 4551 S += 'r'; 4552 } 4553 } 4554 if (isReadOnly) { 4555 // Another legacy compatibility encoding. Some ObjC qualifier and type 4556 // combinations need to be rearranged. 4557 // Rewrite "in const" from "nr" to "rn" 4558 if (StringRef(S).endswith("nr")) 4559 S.replace(S.end()-2, S.end(), "rn"); 4560 } 4561 4562 if (PointeeTy->isCharType()) { 4563 // char pointer types should be encoded as '*' unless it is a 4564 // type that has been typedef'd to 'BOOL'. 4565 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 4566 S += '*'; 4567 return; 4568 } 4569 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 4570 // GCC binary compat: Need to convert "struct objc_class *" to "#". 4571 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 4572 S += '#'; 4573 return; 4574 } 4575 // GCC binary compat: Need to convert "struct objc_object *" to "@". 4576 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 4577 S += '@'; 4578 return; 4579 } 4580 // fall through... 4581 } 4582 S += '^'; 4583 getLegacyIntegralTypeEncoding(PointeeTy); 4584 4585 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 4586 NULL); 4587 return; 4588 } 4589 4590 if (const ArrayType *AT = 4591 // Ignore type qualifiers etc. 4592 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 4593 if (isa<IncompleteArrayType>(AT) && !StructField) { 4594 // Incomplete arrays are encoded as a pointer to the array element. 4595 S += '^'; 4596 4597 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4598 false, ExpandStructures, FD); 4599 } else { 4600 S += '['; 4601 4602 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4603 if (getTypeSize(CAT->getElementType()) == 0) 4604 S += '0'; 4605 else 4606 S += llvm::utostr(CAT->getSize().getZExtValue()); 4607 } else { 4608 //Variable length arrays are encoded as a regular array with 0 elements. 4609 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 4610 "Unknown array type!"); 4611 S += '0'; 4612 } 4613 4614 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4615 false, ExpandStructures, FD); 4616 S += ']'; 4617 } 4618 return; 4619 } 4620 4621 if (T->getAs<FunctionType>()) { 4622 S += '?'; 4623 return; 4624 } 4625 4626 if (const RecordType *RTy = T->getAs<RecordType>()) { 4627 RecordDecl *RDecl = RTy->getDecl(); 4628 S += RDecl->isUnion() ? '(' : '{'; 4629 // Anonymous structures print as '?' 4630 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 4631 S += II->getName(); 4632 if (ClassTemplateSpecializationDecl *Spec 4633 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 4634 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 4635 std::string TemplateArgsStr 4636 = TemplateSpecializationType::PrintTemplateArgumentList( 4637 TemplateArgs.data(), 4638 TemplateArgs.size(), 4639 (*this).getPrintingPolicy()); 4640 4641 S += TemplateArgsStr; 4642 } 4643 } else { 4644 S += '?'; 4645 } 4646 if (ExpandStructures) { 4647 S += '='; 4648 if (!RDecl->isUnion()) { 4649 getObjCEncodingForStructureImpl(RDecl, S, FD); 4650 } else { 4651 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4652 FieldEnd = RDecl->field_end(); 4653 Field != FieldEnd; ++Field) { 4654 if (FD) { 4655 S += '"'; 4656 S += Field->getNameAsString(); 4657 S += '"'; 4658 } 4659 4660 // Special case bit-fields. 4661 if (Field->isBitField()) { 4662 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 4663 *Field); 4664 } else { 4665 QualType qt = Field->getType(); 4666 getLegacyIntegralTypeEncoding(qt); 4667 getObjCEncodingForTypeImpl(qt, S, false, true, 4668 FD, /*OutermostType*/false, 4669 /*EncodingProperty*/false, 4670 /*StructField*/true); 4671 } 4672 } 4673 } 4674 } 4675 S += RDecl->isUnion() ? ')' : '}'; 4676 return; 4677 } 4678 4679 if (const EnumType *ET = T->getAs<EnumType>()) { 4680 if (FD && FD->isBitField()) 4681 EncodeBitField(this, S, T, FD); 4682 else 4683 S += ObjCEncodingForEnumType(this, ET); 4684 return; 4685 } 4686 4687 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 4688 S += "@?"; // Unlike a pointer-to-function, which is "^?". 4689 if (EncodeBlockParameters) { 4690 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>(); 4691 4692 S += '<'; 4693 // Block return type 4694 getObjCEncodingForTypeImpl(FT->getResultType(), S, 4695 ExpandPointedToStructures, ExpandStructures, 4696 FD, 4697 false /* OutermostType */, 4698 EncodingProperty, 4699 false /* StructField */, 4700 EncodeBlockParameters, 4701 EncodeClassNames); 4702 // Block self 4703 S += "@?"; 4704 // Block parameters 4705 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 4706 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 4707 E = FPT->arg_type_end(); I && (I != E); ++I) { 4708 getObjCEncodingForTypeImpl(*I, S, 4709 ExpandPointedToStructures, 4710 ExpandStructures, 4711 FD, 4712 false /* OutermostType */, 4713 EncodingProperty, 4714 false /* StructField */, 4715 EncodeBlockParameters, 4716 EncodeClassNames); 4717 } 4718 } 4719 S += '>'; 4720 } 4721 return; 4722 } 4723 4724 // Ignore protocol qualifiers when mangling at this level. 4725 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 4726 T = OT->getBaseType(); 4727 4728 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4729 // @encode(class_name) 4730 ObjCInterfaceDecl *OI = OIT->getDecl(); 4731 S += '{'; 4732 const IdentifierInfo *II = OI->getIdentifier(); 4733 S += II->getName(); 4734 S += '='; 4735 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4736 DeepCollectObjCIvars(OI, true, Ivars); 4737 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4738 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4739 if (Field->isBitField()) 4740 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4741 else 4742 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4743 } 4744 S += '}'; 4745 return; 4746 } 4747 4748 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4749 if (OPT->isObjCIdType()) { 4750 S += '@'; 4751 return; 4752 } 4753 4754 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4755 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4756 // Since this is a binary compatibility issue, need to consult with runtime 4757 // folks. Fortunately, this is a *very* obsure construct. 4758 S += '#'; 4759 return; 4760 } 4761 4762 if (OPT->isObjCQualifiedIdType()) { 4763 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4764 ExpandPointedToStructures, 4765 ExpandStructures, FD); 4766 if (FD || EncodingProperty || EncodeClassNames) { 4767 // Note that we do extended encoding of protocol qualifer list 4768 // Only when doing ivar or property encoding. 4769 S += '"'; 4770 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4771 E = OPT->qual_end(); I != E; ++I) { 4772 S += '<'; 4773 S += (*I)->getNameAsString(); 4774 S += '>'; 4775 } 4776 S += '"'; 4777 } 4778 return; 4779 } 4780 4781 QualType PointeeTy = OPT->getPointeeType(); 4782 if (!EncodingProperty && 4783 isa<TypedefType>(PointeeTy.getTypePtr())) { 4784 // Another historical/compatibility reason. 4785 // We encode the underlying type which comes out as 4786 // {...}; 4787 S += '^'; 4788 getObjCEncodingForTypeImpl(PointeeTy, S, 4789 false, ExpandPointedToStructures, 4790 NULL); 4791 return; 4792 } 4793 4794 S += '@'; 4795 if (OPT->getInterfaceDecl() && 4796 (FD || EncodingProperty || EncodeClassNames)) { 4797 S += '"'; 4798 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 4799 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4800 E = OPT->qual_end(); I != E; ++I) { 4801 S += '<'; 4802 S += (*I)->getNameAsString(); 4803 S += '>'; 4804 } 4805 S += '"'; 4806 } 4807 return; 4808 } 4809 4810 // gcc just blithely ignores member pointers. 4811 // TODO: maybe there should be a mangling for these 4812 if (T->getAs<MemberPointerType>()) 4813 return; 4814 4815 if (T->isVectorType()) { 4816 // This matches gcc's encoding, even though technically it is 4817 // insufficient. 4818 // FIXME. We should do a better job than gcc. 4819 return; 4820 } 4821 4822 llvm_unreachable("@encode for type not implemented!"); 4823} 4824 4825void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 4826 std::string &S, 4827 const FieldDecl *FD, 4828 bool includeVBases) const { 4829 assert(RDecl && "Expected non-null RecordDecl"); 4830 assert(!RDecl->isUnion() && "Should not be called for unions"); 4831 if (!RDecl->getDefinition()) 4832 return; 4833 4834 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 4835 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 4836 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 4837 4838 if (CXXRec) { 4839 for (CXXRecordDecl::base_class_iterator 4840 BI = CXXRec->bases_begin(), 4841 BE = CXXRec->bases_end(); BI != BE; ++BI) { 4842 if (!BI->isVirtual()) { 4843 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4844 if (base->isEmpty()) 4845 continue; 4846 uint64_t offs = layout.getBaseClassOffsetInBits(base); 4847 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4848 std::make_pair(offs, base)); 4849 } 4850 } 4851 } 4852 4853 unsigned i = 0; 4854 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4855 FieldEnd = RDecl->field_end(); 4856 Field != FieldEnd; ++Field, ++i) { 4857 uint64_t offs = layout.getFieldOffset(i); 4858 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4859 std::make_pair(offs, *Field)); 4860 } 4861 4862 if (CXXRec && includeVBases) { 4863 for (CXXRecordDecl::base_class_iterator 4864 BI = CXXRec->vbases_begin(), 4865 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 4866 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4867 if (base->isEmpty()) 4868 continue; 4869 uint64_t offs = layout.getVBaseClassOffsetInBits(base); 4870 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 4871 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 4872 std::make_pair(offs, base)); 4873 } 4874 } 4875 4876 CharUnits size; 4877 if (CXXRec) { 4878 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 4879 } else { 4880 size = layout.getSize(); 4881 } 4882 4883 uint64_t CurOffs = 0; 4884 std::multimap<uint64_t, NamedDecl *>::iterator 4885 CurLayObj = FieldOrBaseOffsets.begin(); 4886 4887 if (CXXRec && CXXRec->isDynamicClass() && 4888 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 4889 if (FD) { 4890 S += "\"_vptr$"; 4891 std::string recname = CXXRec->getNameAsString(); 4892 if (recname.empty()) recname = "?"; 4893 S += recname; 4894 S += '"'; 4895 } 4896 S += "^^?"; 4897 CurOffs += getTypeSize(VoidPtrTy); 4898 } 4899 4900 if (!RDecl->hasFlexibleArrayMember()) { 4901 // Mark the end of the structure. 4902 uint64_t offs = toBits(size); 4903 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4904 std::make_pair(offs, (NamedDecl*)0)); 4905 } 4906 4907 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 4908 assert(CurOffs <= CurLayObj->first); 4909 4910 if (CurOffs < CurLayObj->first) { 4911 uint64_t padding = CurLayObj->first - CurOffs; 4912 // FIXME: There doesn't seem to be a way to indicate in the encoding that 4913 // packing/alignment of members is different that normal, in which case 4914 // the encoding will be out-of-sync with the real layout. 4915 // If the runtime switches to just consider the size of types without 4916 // taking into account alignment, we could make padding explicit in the 4917 // encoding (e.g. using arrays of chars). The encoding strings would be 4918 // longer then though. 4919 CurOffs += padding; 4920 } 4921 4922 NamedDecl *dcl = CurLayObj->second; 4923 if (dcl == 0) 4924 break; // reached end of structure. 4925 4926 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 4927 // We expand the bases without their virtual bases since those are going 4928 // in the initial structure. Note that this differs from gcc which 4929 // expands virtual bases each time one is encountered in the hierarchy, 4930 // making the encoding type bigger than it really is. 4931 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false); 4932 assert(!base->isEmpty()); 4933 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 4934 } else { 4935 FieldDecl *field = cast<FieldDecl>(dcl); 4936 if (FD) { 4937 S += '"'; 4938 S += field->getNameAsString(); 4939 S += '"'; 4940 } 4941 4942 if (field->isBitField()) { 4943 EncodeBitField(this, S, field->getType(), field); 4944 CurOffs += field->getBitWidthValue(*this); 4945 } else { 4946 QualType qt = field->getType(); 4947 getLegacyIntegralTypeEncoding(qt); 4948 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 4949 /*OutermostType*/false, 4950 /*EncodingProperty*/false, 4951 /*StructField*/true); 4952 CurOffs += getTypeSize(field->getType()); 4953 } 4954 } 4955 } 4956} 4957 4958void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 4959 std::string& S) const { 4960 if (QT & Decl::OBJC_TQ_In) 4961 S += 'n'; 4962 if (QT & Decl::OBJC_TQ_Inout) 4963 S += 'N'; 4964 if (QT & Decl::OBJC_TQ_Out) 4965 S += 'o'; 4966 if (QT & Decl::OBJC_TQ_Bycopy) 4967 S += 'O'; 4968 if (QT & Decl::OBJC_TQ_Byref) 4969 S += 'R'; 4970 if (QT & Decl::OBJC_TQ_Oneway) 4971 S += 'V'; 4972} 4973 4974TypedefDecl *ASTContext::getObjCIdDecl() const { 4975 if (!ObjCIdDecl) { 4976 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0); 4977 T = getObjCObjectPointerType(T); 4978 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T); 4979 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4980 getTranslationUnitDecl(), 4981 SourceLocation(), SourceLocation(), 4982 &Idents.get("id"), IdInfo); 4983 } 4984 4985 return ObjCIdDecl; 4986} 4987 4988TypedefDecl *ASTContext::getObjCSelDecl() const { 4989 if (!ObjCSelDecl) { 4990 QualType SelT = getPointerType(ObjCBuiltinSelTy); 4991 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT); 4992 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 4993 getTranslationUnitDecl(), 4994 SourceLocation(), SourceLocation(), 4995 &Idents.get("SEL"), SelInfo); 4996 } 4997 return ObjCSelDecl; 4998} 4999 5000TypedefDecl *ASTContext::getObjCClassDecl() const { 5001 if (!ObjCClassDecl) { 5002 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0); 5003 T = getObjCObjectPointerType(T); 5004 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T); 5005 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5006 getTranslationUnitDecl(), 5007 SourceLocation(), SourceLocation(), 5008 &Idents.get("Class"), ClassInfo); 5009 } 5010 5011 return ObjCClassDecl; 5012} 5013 5014ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5015 if (!ObjCProtocolClassDecl) { 5016 ObjCProtocolClassDecl 5017 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5018 SourceLocation(), 5019 &Idents.get("Protocol"), 5020 /*PrevDecl=*/0, 5021 SourceLocation(), true); 5022 } 5023 5024 return ObjCProtocolClassDecl; 5025} 5026 5027//===----------------------------------------------------------------------===// 5028// __builtin_va_list Construction Functions 5029//===----------------------------------------------------------------------===// 5030 5031static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5032 // typedef char* __builtin_va_list; 5033 QualType CharPtrType = Context->getPointerType(Context->CharTy); 5034 TypeSourceInfo *TInfo 5035 = Context->getTrivialTypeSourceInfo(CharPtrType); 5036 5037 TypedefDecl *VaListTypeDecl 5038 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5039 Context->getTranslationUnitDecl(), 5040 SourceLocation(), SourceLocation(), 5041 &Context->Idents.get("__builtin_va_list"), 5042 TInfo); 5043 return VaListTypeDecl; 5044} 5045 5046static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5047 // typedef void* __builtin_va_list; 5048 QualType VoidPtrType = Context->getPointerType(Context->VoidTy); 5049 TypeSourceInfo *TInfo 5050 = Context->getTrivialTypeSourceInfo(VoidPtrType); 5051 5052 TypedefDecl *VaListTypeDecl 5053 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5054 Context->getTranslationUnitDecl(), 5055 SourceLocation(), SourceLocation(), 5056 &Context->Idents.get("__builtin_va_list"), 5057 TInfo); 5058 return VaListTypeDecl; 5059} 5060 5061static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5062 // typedef struct __va_list_tag { 5063 RecordDecl *VaListTagDecl; 5064 5065 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5066 Context->getTranslationUnitDecl(), 5067 &Context->Idents.get("__va_list_tag")); 5068 VaListTagDecl->startDefinition(); 5069 5070 const size_t NumFields = 5; 5071 QualType FieldTypes[NumFields]; 5072 const char *FieldNames[NumFields]; 5073 5074 // unsigned char gpr; 5075 FieldTypes[0] = Context->UnsignedCharTy; 5076 FieldNames[0] = "gpr"; 5077 5078 // unsigned char fpr; 5079 FieldTypes[1] = Context->UnsignedCharTy; 5080 FieldNames[1] = "fpr"; 5081 5082 // unsigned short reserved; 5083 FieldTypes[2] = Context->UnsignedShortTy; 5084 FieldNames[2] = "reserved"; 5085 5086 // void* overflow_arg_area; 5087 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5088 FieldNames[3] = "overflow_arg_area"; 5089 5090 // void* reg_save_area; 5091 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5092 FieldNames[4] = "reg_save_area"; 5093 5094 // Create fields 5095 for (unsigned i = 0; i < NumFields; ++i) { 5096 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5097 SourceLocation(), 5098 SourceLocation(), 5099 &Context->Idents.get(FieldNames[i]), 5100 FieldTypes[i], /*TInfo=*/0, 5101 /*BitWidth=*/0, 5102 /*Mutable=*/false, 5103 ICIS_NoInit); 5104 Field->setAccess(AS_public); 5105 VaListTagDecl->addDecl(Field); 5106 } 5107 VaListTagDecl->completeDefinition(); 5108 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5109 5110 // } __va_list_tag; 5111 TypedefDecl *VaListTagTypedefDecl 5112 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5113 Context->getTranslationUnitDecl(), 5114 SourceLocation(), SourceLocation(), 5115 &Context->Idents.get("__va_list_tag"), 5116 Context->getTrivialTypeSourceInfo(VaListTagType)); 5117 QualType VaListTagTypedefType = 5118 Context->getTypedefType(VaListTagTypedefDecl); 5119 5120 // typedef __va_list_tag __builtin_va_list[1]; 5121 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5122 QualType VaListTagArrayType 5123 = Context->getConstantArrayType(VaListTagTypedefType, 5124 Size, ArrayType::Normal, 0); 5125 TypeSourceInfo *TInfo 5126 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5127 TypedefDecl *VaListTypedefDecl 5128 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5129 Context->getTranslationUnitDecl(), 5130 SourceLocation(), SourceLocation(), 5131 &Context->Idents.get("__builtin_va_list"), 5132 TInfo); 5133 5134 return VaListTypedefDecl; 5135} 5136 5137static TypedefDecl * 5138CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 5139 // typedef struct __va_list_tag { 5140 RecordDecl *VaListTagDecl; 5141 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5142 Context->getTranslationUnitDecl(), 5143 &Context->Idents.get("__va_list_tag")); 5144 VaListTagDecl->startDefinition(); 5145 5146 const size_t NumFields = 4; 5147 QualType FieldTypes[NumFields]; 5148 const char *FieldNames[NumFields]; 5149 5150 // unsigned gp_offset; 5151 FieldTypes[0] = Context->UnsignedIntTy; 5152 FieldNames[0] = "gp_offset"; 5153 5154 // unsigned fp_offset; 5155 FieldTypes[1] = Context->UnsignedIntTy; 5156 FieldNames[1] = "fp_offset"; 5157 5158 // void* overflow_arg_area; 5159 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5160 FieldNames[2] = "overflow_arg_area"; 5161 5162 // void* reg_save_area; 5163 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5164 FieldNames[3] = "reg_save_area"; 5165 5166 // Create fields 5167 for (unsigned i = 0; i < NumFields; ++i) { 5168 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5169 VaListTagDecl, 5170 SourceLocation(), 5171 SourceLocation(), 5172 &Context->Idents.get(FieldNames[i]), 5173 FieldTypes[i], /*TInfo=*/0, 5174 /*BitWidth=*/0, 5175 /*Mutable=*/false, 5176 ICIS_NoInit); 5177 Field->setAccess(AS_public); 5178 VaListTagDecl->addDecl(Field); 5179 } 5180 VaListTagDecl->completeDefinition(); 5181 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5182 5183 // } __va_list_tag; 5184 TypedefDecl *VaListTagTypedefDecl 5185 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5186 Context->getTranslationUnitDecl(), 5187 SourceLocation(), SourceLocation(), 5188 &Context->Idents.get("__va_list_tag"), 5189 Context->getTrivialTypeSourceInfo(VaListTagType)); 5190 QualType VaListTagTypedefType = 5191 Context->getTypedefType(VaListTagTypedefDecl); 5192 5193 // typedef __va_list_tag __builtin_va_list[1]; 5194 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5195 QualType VaListTagArrayType 5196 = Context->getConstantArrayType(VaListTagTypedefType, 5197 Size, ArrayType::Normal,0); 5198 TypeSourceInfo *TInfo 5199 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5200 TypedefDecl *VaListTypedefDecl 5201 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5202 Context->getTranslationUnitDecl(), 5203 SourceLocation(), SourceLocation(), 5204 &Context->Idents.get("__builtin_va_list"), 5205 TInfo); 5206 5207 return VaListTypedefDecl; 5208} 5209 5210static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 5211 // typedef int __builtin_va_list[4]; 5212 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 5213 QualType IntArrayType 5214 = Context->getConstantArrayType(Context->IntTy, 5215 Size, ArrayType::Normal, 0); 5216 TypedefDecl *VaListTypedefDecl 5217 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5218 Context->getTranslationUnitDecl(), 5219 SourceLocation(), SourceLocation(), 5220 &Context->Idents.get("__builtin_va_list"), 5221 Context->getTrivialTypeSourceInfo(IntArrayType)); 5222 5223 return VaListTypedefDecl; 5224} 5225 5226static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 5227 TargetInfo::BuiltinVaListKind Kind) { 5228 switch (Kind) { 5229 case TargetInfo::CharPtrBuiltinVaList: 5230 return CreateCharPtrBuiltinVaListDecl(Context); 5231 case TargetInfo::VoidPtrBuiltinVaList: 5232 return CreateVoidPtrBuiltinVaListDecl(Context); 5233 case TargetInfo::PowerABIBuiltinVaList: 5234 return CreatePowerABIBuiltinVaListDecl(Context); 5235 case TargetInfo::X86_64ABIBuiltinVaList: 5236 return CreateX86_64ABIBuiltinVaListDecl(Context); 5237 case TargetInfo::PNaClABIBuiltinVaList: 5238 return CreatePNaClABIBuiltinVaListDecl(Context); 5239 } 5240 5241 llvm_unreachable("Unhandled __builtin_va_list type kind"); 5242} 5243 5244TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 5245 if (!BuiltinVaListDecl) 5246 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 5247 5248 return BuiltinVaListDecl; 5249} 5250 5251void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 5252 assert(ObjCConstantStringType.isNull() && 5253 "'NSConstantString' type already set!"); 5254 5255 ObjCConstantStringType = getObjCInterfaceType(Decl); 5256} 5257 5258/// \brief Retrieve the template name that corresponds to a non-empty 5259/// lookup. 5260TemplateName 5261ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 5262 UnresolvedSetIterator End) const { 5263 unsigned size = End - Begin; 5264 assert(size > 1 && "set is not overloaded!"); 5265 5266 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 5267 size * sizeof(FunctionTemplateDecl*)); 5268 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 5269 5270 NamedDecl **Storage = OT->getStorage(); 5271 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 5272 NamedDecl *D = *I; 5273 assert(isa<FunctionTemplateDecl>(D) || 5274 (isa<UsingShadowDecl>(D) && 5275 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 5276 *Storage++ = D; 5277 } 5278 5279 return TemplateName(OT); 5280} 5281 5282/// \brief Retrieve the template name that represents a qualified 5283/// template name such as \c std::vector. 5284TemplateName 5285ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 5286 bool TemplateKeyword, 5287 TemplateDecl *Template) const { 5288 assert(NNS && "Missing nested-name-specifier in qualified template name"); 5289 5290 // FIXME: Canonicalization? 5291 llvm::FoldingSetNodeID ID; 5292 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 5293 5294 void *InsertPos = 0; 5295 QualifiedTemplateName *QTN = 5296 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5297 if (!QTN) { 5298 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 5299 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 5300 } 5301 5302 return TemplateName(QTN); 5303} 5304 5305/// \brief Retrieve the template name that represents a dependent 5306/// template name such as \c MetaFun::template apply. 5307TemplateName 5308ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5309 const IdentifierInfo *Name) const { 5310 assert((!NNS || NNS->isDependent()) && 5311 "Nested name specifier must be dependent"); 5312 5313 llvm::FoldingSetNodeID ID; 5314 DependentTemplateName::Profile(ID, NNS, Name); 5315 5316 void *InsertPos = 0; 5317 DependentTemplateName *QTN = 5318 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5319 5320 if (QTN) 5321 return TemplateName(QTN); 5322 5323 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5324 if (CanonNNS == NNS) { 5325 QTN = new (*this,4) DependentTemplateName(NNS, Name); 5326 } else { 5327 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 5328 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 5329 DependentTemplateName *CheckQTN = 5330 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5331 assert(!CheckQTN && "Dependent type name canonicalization broken"); 5332 (void)CheckQTN; 5333 } 5334 5335 DependentTemplateNames.InsertNode(QTN, InsertPos); 5336 return TemplateName(QTN); 5337} 5338 5339/// \brief Retrieve the template name that represents a dependent 5340/// template name such as \c MetaFun::template operator+. 5341TemplateName 5342ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5343 OverloadedOperatorKind Operator) const { 5344 assert((!NNS || NNS->isDependent()) && 5345 "Nested name specifier must be dependent"); 5346 5347 llvm::FoldingSetNodeID ID; 5348 DependentTemplateName::Profile(ID, NNS, Operator); 5349 5350 void *InsertPos = 0; 5351 DependentTemplateName *QTN 5352 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5353 5354 if (QTN) 5355 return TemplateName(QTN); 5356 5357 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5358 if (CanonNNS == NNS) { 5359 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 5360 } else { 5361 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 5362 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 5363 5364 DependentTemplateName *CheckQTN 5365 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5366 assert(!CheckQTN && "Dependent template name canonicalization broken"); 5367 (void)CheckQTN; 5368 } 5369 5370 DependentTemplateNames.InsertNode(QTN, InsertPos); 5371 return TemplateName(QTN); 5372} 5373 5374TemplateName 5375ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 5376 TemplateName replacement) const { 5377 llvm::FoldingSetNodeID ID; 5378 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 5379 5380 void *insertPos = 0; 5381 SubstTemplateTemplateParmStorage *subst 5382 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 5383 5384 if (!subst) { 5385 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 5386 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 5387 } 5388 5389 return TemplateName(subst); 5390} 5391 5392TemplateName 5393ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 5394 const TemplateArgument &ArgPack) const { 5395 ASTContext &Self = const_cast<ASTContext &>(*this); 5396 llvm::FoldingSetNodeID ID; 5397 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 5398 5399 void *InsertPos = 0; 5400 SubstTemplateTemplateParmPackStorage *Subst 5401 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 5402 5403 if (!Subst) { 5404 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 5405 ArgPack.pack_size(), 5406 ArgPack.pack_begin()); 5407 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 5408 } 5409 5410 return TemplateName(Subst); 5411} 5412 5413/// getFromTargetType - Given one of the integer types provided by 5414/// TargetInfo, produce the corresponding type. The unsigned @p Type 5415/// is actually a value of type @c TargetInfo::IntType. 5416CanQualType ASTContext::getFromTargetType(unsigned Type) const { 5417 switch (Type) { 5418 case TargetInfo::NoInt: return CanQualType(); 5419 case TargetInfo::SignedShort: return ShortTy; 5420 case TargetInfo::UnsignedShort: return UnsignedShortTy; 5421 case TargetInfo::SignedInt: return IntTy; 5422 case TargetInfo::UnsignedInt: return UnsignedIntTy; 5423 case TargetInfo::SignedLong: return LongTy; 5424 case TargetInfo::UnsignedLong: return UnsignedLongTy; 5425 case TargetInfo::SignedLongLong: return LongLongTy; 5426 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 5427 } 5428 5429 llvm_unreachable("Unhandled TargetInfo::IntType value"); 5430} 5431 5432//===----------------------------------------------------------------------===// 5433// Type Predicates. 5434//===----------------------------------------------------------------------===// 5435 5436/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 5437/// garbage collection attribute. 5438/// 5439Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 5440 if (getLangOpts().getGC() == LangOptions::NonGC) 5441 return Qualifiers::GCNone; 5442 5443 assert(getLangOpts().ObjC1); 5444 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 5445 5446 // Default behaviour under objective-C's gc is for ObjC pointers 5447 // (or pointers to them) be treated as though they were declared 5448 // as __strong. 5449 if (GCAttrs == Qualifiers::GCNone) { 5450 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 5451 return Qualifiers::Strong; 5452 else if (Ty->isPointerType()) 5453 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 5454 } else { 5455 // It's not valid to set GC attributes on anything that isn't a 5456 // pointer. 5457#ifndef NDEBUG 5458 QualType CT = Ty->getCanonicalTypeInternal(); 5459 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 5460 CT = AT->getElementType(); 5461 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 5462#endif 5463 } 5464 return GCAttrs; 5465} 5466 5467//===----------------------------------------------------------------------===// 5468// Type Compatibility Testing 5469//===----------------------------------------------------------------------===// 5470 5471/// areCompatVectorTypes - Return true if the two specified vector types are 5472/// compatible. 5473static bool areCompatVectorTypes(const VectorType *LHS, 5474 const VectorType *RHS) { 5475 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 5476 return LHS->getElementType() == RHS->getElementType() && 5477 LHS->getNumElements() == RHS->getNumElements(); 5478} 5479 5480bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 5481 QualType SecondVec) { 5482 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 5483 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 5484 5485 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 5486 return true; 5487 5488 // Treat Neon vector types and most AltiVec vector types as if they are the 5489 // equivalent GCC vector types. 5490 const VectorType *First = FirstVec->getAs<VectorType>(); 5491 const VectorType *Second = SecondVec->getAs<VectorType>(); 5492 if (First->getNumElements() == Second->getNumElements() && 5493 hasSameType(First->getElementType(), Second->getElementType()) && 5494 First->getVectorKind() != VectorType::AltiVecPixel && 5495 First->getVectorKind() != VectorType::AltiVecBool && 5496 Second->getVectorKind() != VectorType::AltiVecPixel && 5497 Second->getVectorKind() != VectorType::AltiVecBool) 5498 return true; 5499 5500 return false; 5501} 5502 5503//===----------------------------------------------------------------------===// 5504// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 5505//===----------------------------------------------------------------------===// 5506 5507/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 5508/// inheritance hierarchy of 'rProto'. 5509bool 5510ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 5511 ObjCProtocolDecl *rProto) const { 5512 if (declaresSameEntity(lProto, rProto)) 5513 return true; 5514 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 5515 E = rProto->protocol_end(); PI != E; ++PI) 5516 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 5517 return true; 5518 return false; 5519} 5520 5521/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 5522/// return true if lhs's protocols conform to rhs's protocol; false 5523/// otherwise. 5524bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 5525 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 5526 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 5527 return false; 5528} 5529 5530/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 5531/// Class<p1, ...>. 5532bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 5533 QualType rhs) { 5534 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 5535 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5536 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 5537 5538 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5539 E = lhsQID->qual_end(); I != E; ++I) { 5540 bool match = false; 5541 ObjCProtocolDecl *lhsProto = *I; 5542 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5543 E = rhsOPT->qual_end(); J != E; ++J) { 5544 ObjCProtocolDecl *rhsProto = *J; 5545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 5546 match = true; 5547 break; 5548 } 5549 } 5550 if (!match) 5551 return false; 5552 } 5553 return true; 5554} 5555 5556/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 5557/// ObjCQualifiedIDType. 5558bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 5559 bool compare) { 5560 // Allow id<P..> and an 'id' or void* type in all cases. 5561 if (lhs->isVoidPointerType() || 5562 lhs->isObjCIdType() || lhs->isObjCClassType()) 5563 return true; 5564 else if (rhs->isVoidPointerType() || 5565 rhs->isObjCIdType() || rhs->isObjCClassType()) 5566 return true; 5567 5568 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 5569 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5570 5571 if (!rhsOPT) return false; 5572 5573 if (rhsOPT->qual_empty()) { 5574 // If the RHS is a unqualified interface pointer "NSString*", 5575 // make sure we check the class hierarchy. 5576 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5577 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5578 E = lhsQID->qual_end(); I != E; ++I) { 5579 // when comparing an id<P> on lhs with a static type on rhs, 5580 // see if static class implements all of id's protocols, directly or 5581 // through its super class and categories. 5582 if (!rhsID->ClassImplementsProtocol(*I, true)) 5583 return false; 5584 } 5585 } 5586 // If there are no qualifiers and no interface, we have an 'id'. 5587 return true; 5588 } 5589 // Both the right and left sides have qualifiers. 5590 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5591 E = lhsQID->qual_end(); I != E; ++I) { 5592 ObjCProtocolDecl *lhsProto = *I; 5593 bool match = false; 5594 5595 // when comparing an id<P> on lhs with a static type on rhs, 5596 // see if static class implements all of id's protocols, directly or 5597 // through its super class and categories. 5598 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5599 E = rhsOPT->qual_end(); J != E; ++J) { 5600 ObjCProtocolDecl *rhsProto = *J; 5601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5602 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5603 match = true; 5604 break; 5605 } 5606 } 5607 // If the RHS is a qualified interface pointer "NSString<P>*", 5608 // make sure we check the class hierarchy. 5609 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5610 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5611 E = lhsQID->qual_end(); I != E; ++I) { 5612 // when comparing an id<P> on lhs with a static type on rhs, 5613 // see if static class implements all of id's protocols, directly or 5614 // through its super class and categories. 5615 if (rhsID->ClassImplementsProtocol(*I, true)) { 5616 match = true; 5617 break; 5618 } 5619 } 5620 } 5621 if (!match) 5622 return false; 5623 } 5624 5625 return true; 5626 } 5627 5628 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 5629 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 5630 5631 if (const ObjCObjectPointerType *lhsOPT = 5632 lhs->getAsObjCInterfacePointerType()) { 5633 // If both the right and left sides have qualifiers. 5634 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 5635 E = lhsOPT->qual_end(); I != E; ++I) { 5636 ObjCProtocolDecl *lhsProto = *I; 5637 bool match = false; 5638 5639 // when comparing an id<P> on rhs with a static type on lhs, 5640 // see if static class implements all of id's protocols, directly or 5641 // through its super class and categories. 5642 // First, lhs protocols in the qualifier list must be found, direct 5643 // or indirect in rhs's qualifier list or it is a mismatch. 5644 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5645 E = rhsQID->qual_end(); J != E; ++J) { 5646 ObjCProtocolDecl *rhsProto = *J; 5647 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5648 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5649 match = true; 5650 break; 5651 } 5652 } 5653 if (!match) 5654 return false; 5655 } 5656 5657 // Static class's protocols, or its super class or category protocols 5658 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 5659 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 5660 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5661 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 5662 // This is rather dubious but matches gcc's behavior. If lhs has 5663 // no type qualifier and its class has no static protocol(s) 5664 // assume that it is mismatch. 5665 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 5666 return false; 5667 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5668 LHSInheritedProtocols.begin(), 5669 E = LHSInheritedProtocols.end(); I != E; ++I) { 5670 bool match = false; 5671 ObjCProtocolDecl *lhsProto = (*I); 5672 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5673 E = rhsQID->qual_end(); J != E; ++J) { 5674 ObjCProtocolDecl *rhsProto = *J; 5675 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5676 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5677 match = true; 5678 break; 5679 } 5680 } 5681 if (!match) 5682 return false; 5683 } 5684 } 5685 return true; 5686 } 5687 return false; 5688} 5689 5690/// canAssignObjCInterfaces - Return true if the two interface types are 5691/// compatible for assignment from RHS to LHS. This handles validation of any 5692/// protocol qualifiers on the LHS or RHS. 5693/// 5694bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 5695 const ObjCObjectPointerType *RHSOPT) { 5696 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5697 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5698 5699 // If either type represents the built-in 'id' or 'Class' types, return true. 5700 if (LHS->isObjCUnqualifiedIdOrClass() || 5701 RHS->isObjCUnqualifiedIdOrClass()) 5702 return true; 5703 5704 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 5705 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5706 QualType(RHSOPT,0), 5707 false); 5708 5709 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 5710 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 5711 QualType(RHSOPT,0)); 5712 5713 // If we have 2 user-defined types, fall into that path. 5714 if (LHS->getInterface() && RHS->getInterface()) 5715 return canAssignObjCInterfaces(LHS, RHS); 5716 5717 return false; 5718} 5719 5720/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 5721/// for providing type-safety for objective-c pointers used to pass/return 5722/// arguments in block literals. When passed as arguments, passing 'A*' where 5723/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 5724/// not OK. For the return type, the opposite is not OK. 5725bool ASTContext::canAssignObjCInterfacesInBlockPointer( 5726 const ObjCObjectPointerType *LHSOPT, 5727 const ObjCObjectPointerType *RHSOPT, 5728 bool BlockReturnType) { 5729 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 5730 return true; 5731 5732 if (LHSOPT->isObjCBuiltinType()) { 5733 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 5734 } 5735 5736 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 5737 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5738 QualType(RHSOPT,0), 5739 false); 5740 5741 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 5742 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 5743 if (LHS && RHS) { // We have 2 user-defined types. 5744 if (LHS != RHS) { 5745 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 5746 return BlockReturnType; 5747 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 5748 return !BlockReturnType; 5749 } 5750 else 5751 return true; 5752 } 5753 return false; 5754} 5755 5756/// getIntersectionOfProtocols - This routine finds the intersection of set 5757/// of protocols inherited from two distinct objective-c pointer objects. 5758/// It is used to build composite qualifier list of the composite type of 5759/// the conditional expression involving two objective-c pointer objects. 5760static 5761void getIntersectionOfProtocols(ASTContext &Context, 5762 const ObjCObjectPointerType *LHSOPT, 5763 const ObjCObjectPointerType *RHSOPT, 5764 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 5765 5766 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5767 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5768 assert(LHS->getInterface() && "LHS must have an interface base"); 5769 assert(RHS->getInterface() && "RHS must have an interface base"); 5770 5771 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 5772 unsigned LHSNumProtocols = LHS->getNumProtocols(); 5773 if (LHSNumProtocols > 0) 5774 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 5775 else { 5776 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5777 Context.CollectInheritedProtocols(LHS->getInterface(), 5778 LHSInheritedProtocols); 5779 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 5780 LHSInheritedProtocols.end()); 5781 } 5782 5783 unsigned RHSNumProtocols = RHS->getNumProtocols(); 5784 if (RHSNumProtocols > 0) { 5785 ObjCProtocolDecl **RHSProtocols = 5786 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 5787 for (unsigned i = 0; i < RHSNumProtocols; ++i) 5788 if (InheritedProtocolSet.count(RHSProtocols[i])) 5789 IntersectionOfProtocols.push_back(RHSProtocols[i]); 5790 } else { 5791 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 5792 Context.CollectInheritedProtocols(RHS->getInterface(), 5793 RHSInheritedProtocols); 5794 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5795 RHSInheritedProtocols.begin(), 5796 E = RHSInheritedProtocols.end(); I != E; ++I) 5797 if (InheritedProtocolSet.count((*I))) 5798 IntersectionOfProtocols.push_back((*I)); 5799 } 5800} 5801 5802/// areCommonBaseCompatible - Returns common base class of the two classes if 5803/// one found. Note that this is O'2 algorithm. But it will be called as the 5804/// last type comparison in a ?-exp of ObjC pointer types before a 5805/// warning is issued. So, its invokation is extremely rare. 5806QualType ASTContext::areCommonBaseCompatible( 5807 const ObjCObjectPointerType *Lptr, 5808 const ObjCObjectPointerType *Rptr) { 5809 const ObjCObjectType *LHS = Lptr->getObjectType(); 5810 const ObjCObjectType *RHS = Rptr->getObjectType(); 5811 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 5812 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 5813 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 5814 return QualType(); 5815 5816 do { 5817 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 5818 if (canAssignObjCInterfaces(LHS, RHS)) { 5819 SmallVector<ObjCProtocolDecl *, 8> Protocols; 5820 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 5821 5822 QualType Result = QualType(LHS, 0); 5823 if (!Protocols.empty()) 5824 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 5825 Result = getObjCObjectPointerType(Result); 5826 return Result; 5827 } 5828 } while ((LDecl = LDecl->getSuperClass())); 5829 5830 return QualType(); 5831} 5832 5833bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 5834 const ObjCObjectType *RHS) { 5835 assert(LHS->getInterface() && "LHS is not an interface type"); 5836 assert(RHS->getInterface() && "RHS is not an interface type"); 5837 5838 // Verify that the base decls are compatible: the RHS must be a subclass of 5839 // the LHS. 5840 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 5841 return false; 5842 5843 // RHS must have a superset of the protocols in the LHS. If the LHS is not 5844 // protocol qualified at all, then we are good. 5845 if (LHS->getNumProtocols() == 0) 5846 return true; 5847 5848 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 5849 // more detailed analysis is required. 5850 if (RHS->getNumProtocols() == 0) { 5851 // OK, if LHS is a superclass of RHS *and* 5852 // this superclass is assignment compatible with LHS. 5853 // false otherwise. 5854 bool IsSuperClass = 5855 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 5856 if (IsSuperClass) { 5857 // OK if conversion of LHS to SuperClass results in narrowing of types 5858 // ; i.e., SuperClass may implement at least one of the protocols 5859 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 5860 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 5861 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 5862 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 5863 // If super class has no protocols, it is not a match. 5864 if (SuperClassInheritedProtocols.empty()) 5865 return false; 5866 5867 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5868 LHSPE = LHS->qual_end(); 5869 LHSPI != LHSPE; LHSPI++) { 5870 bool SuperImplementsProtocol = false; 5871 ObjCProtocolDecl *LHSProto = (*LHSPI); 5872 5873 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5874 SuperClassInheritedProtocols.begin(), 5875 E = SuperClassInheritedProtocols.end(); I != E; ++I) { 5876 ObjCProtocolDecl *SuperClassProto = (*I); 5877 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 5878 SuperImplementsProtocol = true; 5879 break; 5880 } 5881 } 5882 if (!SuperImplementsProtocol) 5883 return false; 5884 } 5885 return true; 5886 } 5887 return false; 5888 } 5889 5890 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5891 LHSPE = LHS->qual_end(); 5892 LHSPI != LHSPE; LHSPI++) { 5893 bool RHSImplementsProtocol = false; 5894 5895 // If the RHS doesn't implement the protocol on the left, the types 5896 // are incompatible. 5897 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 5898 RHSPE = RHS->qual_end(); 5899 RHSPI != RHSPE; RHSPI++) { 5900 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 5901 RHSImplementsProtocol = true; 5902 break; 5903 } 5904 } 5905 // FIXME: For better diagnostics, consider passing back the protocol name. 5906 if (!RHSImplementsProtocol) 5907 return false; 5908 } 5909 // The RHS implements all protocols listed on the LHS. 5910 return true; 5911} 5912 5913bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 5914 // get the "pointed to" types 5915 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 5916 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 5917 5918 if (!LHSOPT || !RHSOPT) 5919 return false; 5920 5921 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 5922 canAssignObjCInterfaces(RHSOPT, LHSOPT); 5923} 5924 5925bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 5926 return canAssignObjCInterfaces( 5927 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 5928 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 5929} 5930 5931/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 5932/// both shall have the identically qualified version of a compatible type. 5933/// C99 6.2.7p1: Two types have compatible types if their types are the 5934/// same. See 6.7.[2,3,5] for additional rules. 5935bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 5936 bool CompareUnqualified) { 5937 if (getLangOpts().CPlusPlus) 5938 return hasSameType(LHS, RHS); 5939 5940 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 5941} 5942 5943bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 5944 return typesAreCompatible(LHS, RHS); 5945} 5946 5947bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 5948 return !mergeTypes(LHS, RHS, true).isNull(); 5949} 5950 5951/// mergeTransparentUnionType - if T is a transparent union type and a member 5952/// of T is compatible with SubType, return the merged type, else return 5953/// QualType() 5954QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 5955 bool OfBlockPointer, 5956 bool Unqualified) { 5957 if (const RecordType *UT = T->getAsUnionType()) { 5958 RecordDecl *UD = UT->getDecl(); 5959 if (UD->hasAttr<TransparentUnionAttr>()) { 5960 for (RecordDecl::field_iterator it = UD->field_begin(), 5961 itend = UD->field_end(); it != itend; ++it) { 5962 QualType ET = it->getType().getUnqualifiedType(); 5963 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 5964 if (!MT.isNull()) 5965 return MT; 5966 } 5967 } 5968 } 5969 5970 return QualType(); 5971} 5972 5973/// mergeFunctionArgumentTypes - merge two types which appear as function 5974/// argument types 5975QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 5976 bool OfBlockPointer, 5977 bool Unqualified) { 5978 // GNU extension: two types are compatible if they appear as a function 5979 // argument, one of the types is a transparent union type and the other 5980 // type is compatible with a union member 5981 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 5982 Unqualified); 5983 if (!lmerge.isNull()) 5984 return lmerge; 5985 5986 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 5987 Unqualified); 5988 if (!rmerge.isNull()) 5989 return rmerge; 5990 5991 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 5992} 5993 5994QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 5995 bool OfBlockPointer, 5996 bool Unqualified) { 5997 const FunctionType *lbase = lhs->getAs<FunctionType>(); 5998 const FunctionType *rbase = rhs->getAs<FunctionType>(); 5999 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6000 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6001 bool allLTypes = true; 6002 bool allRTypes = true; 6003 6004 // Check return type 6005 QualType retType; 6006 if (OfBlockPointer) { 6007 QualType RHS = rbase->getResultType(); 6008 QualType LHS = lbase->getResultType(); 6009 bool UnqualifiedResult = Unqualified; 6010 if (!UnqualifiedResult) 6011 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6012 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6013 } 6014 else 6015 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false, 6016 Unqualified); 6017 if (retType.isNull()) return QualType(); 6018 6019 if (Unqualified) 6020 retType = retType.getUnqualifiedType(); 6021 6022 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 6023 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 6024 if (Unqualified) { 6025 LRetType = LRetType.getUnqualifiedType(); 6026 RRetType = RRetType.getUnqualifiedType(); 6027 } 6028 6029 if (getCanonicalType(retType) != LRetType) 6030 allLTypes = false; 6031 if (getCanonicalType(retType) != RRetType) 6032 allRTypes = false; 6033 6034 // FIXME: double check this 6035 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6036 // rbase->getRegParmAttr() != 0 && 6037 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6038 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6039 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6040 6041 // Compatible functions must have compatible calling conventions 6042 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC())) 6043 return QualType(); 6044 6045 // Regparm is part of the calling convention. 6046 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6047 return QualType(); 6048 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6049 return QualType(); 6050 6051 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6052 return QualType(); 6053 6054 // functypes which return are preferred over those that do not. 6055 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn()) 6056 allLTypes = false; 6057 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()) 6058 allRTypes = false; 6059 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6060 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6061 6062 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6063 6064 if (lproto && rproto) { // two C99 style function prototypes 6065 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6066 "C++ shouldn't be here"); 6067 unsigned lproto_nargs = lproto->getNumArgs(); 6068 unsigned rproto_nargs = rproto->getNumArgs(); 6069 6070 // Compatible functions must have the same number of arguments 6071 if (lproto_nargs != rproto_nargs) 6072 return QualType(); 6073 6074 // Variadic and non-variadic functions aren't compatible 6075 if (lproto->isVariadic() != rproto->isVariadic()) 6076 return QualType(); 6077 6078 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6079 return QualType(); 6080 6081 if (LangOpts.ObjCAutoRefCount && 6082 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6083 return QualType(); 6084 6085 // Check argument compatibility 6086 SmallVector<QualType, 10> types; 6087 for (unsigned i = 0; i < lproto_nargs; i++) { 6088 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 6089 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 6090 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 6091 OfBlockPointer, 6092 Unqualified); 6093 if (argtype.isNull()) return QualType(); 6094 6095 if (Unqualified) 6096 argtype = argtype.getUnqualifiedType(); 6097 6098 types.push_back(argtype); 6099 if (Unqualified) { 6100 largtype = largtype.getUnqualifiedType(); 6101 rargtype = rargtype.getUnqualifiedType(); 6102 } 6103 6104 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 6105 allLTypes = false; 6106 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 6107 allRTypes = false; 6108 } 6109 6110 if (allLTypes) return lhs; 6111 if (allRTypes) return rhs; 6112 6113 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 6114 EPI.ExtInfo = einfo; 6115 return getFunctionType(retType, types.begin(), types.size(), EPI); 6116 } 6117 6118 if (lproto) allRTypes = false; 6119 if (rproto) allLTypes = false; 6120 6121 const FunctionProtoType *proto = lproto ? lproto : rproto; 6122 if (proto) { 6123 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 6124 if (proto->isVariadic()) return QualType(); 6125 // Check that the types are compatible with the types that 6126 // would result from default argument promotions (C99 6.7.5.3p15). 6127 // The only types actually affected are promotable integer 6128 // types and floats, which would be passed as a different 6129 // type depending on whether the prototype is visible. 6130 unsigned proto_nargs = proto->getNumArgs(); 6131 for (unsigned i = 0; i < proto_nargs; ++i) { 6132 QualType argTy = proto->getArgType(i); 6133 6134 // Look at the promotion type of enum types, since that is the type used 6135 // to pass enum values. 6136 if (const EnumType *Enum = argTy->getAs<EnumType>()) 6137 argTy = Enum->getDecl()->getPromotionType(); 6138 6139 if (argTy->isPromotableIntegerType() || 6140 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 6141 return QualType(); 6142 } 6143 6144 if (allLTypes) return lhs; 6145 if (allRTypes) return rhs; 6146 6147 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 6148 EPI.ExtInfo = einfo; 6149 return getFunctionType(retType, proto->arg_type_begin(), 6150 proto->getNumArgs(), EPI); 6151 } 6152 6153 if (allLTypes) return lhs; 6154 if (allRTypes) return rhs; 6155 return getFunctionNoProtoType(retType, einfo); 6156} 6157 6158QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 6159 bool OfBlockPointer, 6160 bool Unqualified, bool BlockReturnType) { 6161 // C++ [expr]: If an expression initially has the type "reference to T", the 6162 // type is adjusted to "T" prior to any further analysis, the expression 6163 // designates the object or function denoted by the reference, and the 6164 // expression is an lvalue unless the reference is an rvalue reference and 6165 // the expression is a function call (possibly inside parentheses). 6166 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 6167 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 6168 6169 if (Unqualified) { 6170 LHS = LHS.getUnqualifiedType(); 6171 RHS = RHS.getUnqualifiedType(); 6172 } 6173 6174 QualType LHSCan = getCanonicalType(LHS), 6175 RHSCan = getCanonicalType(RHS); 6176 6177 // If two types are identical, they are compatible. 6178 if (LHSCan == RHSCan) 6179 return LHS; 6180 6181 // If the qualifiers are different, the types aren't compatible... mostly. 6182 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6183 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6184 if (LQuals != RQuals) { 6185 // If any of these qualifiers are different, we have a type 6186 // mismatch. 6187 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6188 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 6189 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 6190 return QualType(); 6191 6192 // Exactly one GC qualifier difference is allowed: __strong is 6193 // okay if the other type has no GC qualifier but is an Objective 6194 // C object pointer (i.e. implicitly strong by default). We fix 6195 // this by pretending that the unqualified type was actually 6196 // qualified __strong. 6197 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6198 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6199 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6200 6201 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6202 return QualType(); 6203 6204 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 6205 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 6206 } 6207 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 6208 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 6209 } 6210 return QualType(); 6211 } 6212 6213 // Okay, qualifiers are equal. 6214 6215 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 6216 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 6217 6218 // We want to consider the two function types to be the same for these 6219 // comparisons, just force one to the other. 6220 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 6221 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 6222 6223 // Same as above for arrays 6224 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 6225 LHSClass = Type::ConstantArray; 6226 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 6227 RHSClass = Type::ConstantArray; 6228 6229 // ObjCInterfaces are just specialized ObjCObjects. 6230 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 6231 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 6232 6233 // Canonicalize ExtVector -> Vector. 6234 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 6235 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 6236 6237 // If the canonical type classes don't match. 6238 if (LHSClass != RHSClass) { 6239 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 6240 // a signed integer type, or an unsigned integer type. 6241 // Compatibility is based on the underlying type, not the promotion 6242 // type. 6243 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 6244 QualType TINT = ETy->getDecl()->getIntegerType(); 6245 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType())) 6246 return RHS; 6247 } 6248 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 6249 QualType TINT = ETy->getDecl()->getIntegerType(); 6250 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType())) 6251 return LHS; 6252 } 6253 // allow block pointer type to match an 'id' type. 6254 if (OfBlockPointer && !BlockReturnType) { 6255 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 6256 return LHS; 6257 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 6258 return RHS; 6259 } 6260 6261 return QualType(); 6262 } 6263 6264 // The canonical type classes match. 6265 switch (LHSClass) { 6266#define TYPE(Class, Base) 6267#define ABSTRACT_TYPE(Class, Base) 6268#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 6269#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6270#define DEPENDENT_TYPE(Class, Base) case Type::Class: 6271#include "clang/AST/TypeNodes.def" 6272 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 6273 6274 case Type::LValueReference: 6275 case Type::RValueReference: 6276 case Type::MemberPointer: 6277 llvm_unreachable("C++ should never be in mergeTypes"); 6278 6279 case Type::ObjCInterface: 6280 case Type::IncompleteArray: 6281 case Type::VariableArray: 6282 case Type::FunctionProto: 6283 case Type::ExtVector: 6284 llvm_unreachable("Types are eliminated above"); 6285 6286 case Type::Pointer: 6287 { 6288 // Merge two pointer types, while trying to preserve typedef info 6289 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 6290 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 6291 if (Unqualified) { 6292 LHSPointee = LHSPointee.getUnqualifiedType(); 6293 RHSPointee = RHSPointee.getUnqualifiedType(); 6294 } 6295 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 6296 Unqualified); 6297 if (ResultType.isNull()) return QualType(); 6298 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6299 return LHS; 6300 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6301 return RHS; 6302 return getPointerType(ResultType); 6303 } 6304 case Type::BlockPointer: 6305 { 6306 // Merge two block pointer types, while trying to preserve typedef info 6307 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 6308 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 6309 if (Unqualified) { 6310 LHSPointee = LHSPointee.getUnqualifiedType(); 6311 RHSPointee = RHSPointee.getUnqualifiedType(); 6312 } 6313 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 6314 Unqualified); 6315 if (ResultType.isNull()) return QualType(); 6316 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6317 return LHS; 6318 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6319 return RHS; 6320 return getBlockPointerType(ResultType); 6321 } 6322 case Type::Atomic: 6323 { 6324 // Merge two pointer types, while trying to preserve typedef info 6325 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 6326 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 6327 if (Unqualified) { 6328 LHSValue = LHSValue.getUnqualifiedType(); 6329 RHSValue = RHSValue.getUnqualifiedType(); 6330 } 6331 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 6332 Unqualified); 6333 if (ResultType.isNull()) return QualType(); 6334 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 6335 return LHS; 6336 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 6337 return RHS; 6338 return getAtomicType(ResultType); 6339 } 6340 case Type::ConstantArray: 6341 { 6342 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 6343 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 6344 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 6345 return QualType(); 6346 6347 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 6348 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 6349 if (Unqualified) { 6350 LHSElem = LHSElem.getUnqualifiedType(); 6351 RHSElem = RHSElem.getUnqualifiedType(); 6352 } 6353 6354 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 6355 if (ResultType.isNull()) return QualType(); 6356 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6357 return LHS; 6358 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6359 return RHS; 6360 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 6361 ArrayType::ArraySizeModifier(), 0); 6362 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 6363 ArrayType::ArraySizeModifier(), 0); 6364 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 6365 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 6366 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6367 return LHS; 6368 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6369 return RHS; 6370 if (LVAT) { 6371 // FIXME: This isn't correct! But tricky to implement because 6372 // the array's size has to be the size of LHS, but the type 6373 // has to be different. 6374 return LHS; 6375 } 6376 if (RVAT) { 6377 // FIXME: This isn't correct! But tricky to implement because 6378 // the array's size has to be the size of RHS, but the type 6379 // has to be different. 6380 return RHS; 6381 } 6382 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 6383 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 6384 return getIncompleteArrayType(ResultType, 6385 ArrayType::ArraySizeModifier(), 0); 6386 } 6387 case Type::FunctionNoProto: 6388 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 6389 case Type::Record: 6390 case Type::Enum: 6391 return QualType(); 6392 case Type::Builtin: 6393 // Only exactly equal builtin types are compatible, which is tested above. 6394 return QualType(); 6395 case Type::Complex: 6396 // Distinct complex types are incompatible. 6397 return QualType(); 6398 case Type::Vector: 6399 // FIXME: The merged type should be an ExtVector! 6400 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 6401 RHSCan->getAs<VectorType>())) 6402 return LHS; 6403 return QualType(); 6404 case Type::ObjCObject: { 6405 // Check if the types are assignment compatible. 6406 // FIXME: This should be type compatibility, e.g. whether 6407 // "LHS x; RHS x;" at global scope is legal. 6408 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 6409 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 6410 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 6411 return LHS; 6412 6413 return QualType(); 6414 } 6415 case Type::ObjCObjectPointer: { 6416 if (OfBlockPointer) { 6417 if (canAssignObjCInterfacesInBlockPointer( 6418 LHS->getAs<ObjCObjectPointerType>(), 6419 RHS->getAs<ObjCObjectPointerType>(), 6420 BlockReturnType)) 6421 return LHS; 6422 return QualType(); 6423 } 6424 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 6425 RHS->getAs<ObjCObjectPointerType>())) 6426 return LHS; 6427 6428 return QualType(); 6429 } 6430 } 6431 6432 llvm_unreachable("Invalid Type::Class!"); 6433} 6434 6435bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 6436 const FunctionProtoType *FromFunctionType, 6437 const FunctionProtoType *ToFunctionType) { 6438 if (FromFunctionType->hasAnyConsumedArgs() != 6439 ToFunctionType->hasAnyConsumedArgs()) 6440 return false; 6441 FunctionProtoType::ExtProtoInfo FromEPI = 6442 FromFunctionType->getExtProtoInfo(); 6443 FunctionProtoType::ExtProtoInfo ToEPI = 6444 ToFunctionType->getExtProtoInfo(); 6445 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments) 6446 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 6447 ArgIdx != NumArgs; ++ArgIdx) { 6448 if (FromEPI.ConsumedArguments[ArgIdx] != 6449 ToEPI.ConsumedArguments[ArgIdx]) 6450 return false; 6451 } 6452 return true; 6453} 6454 6455/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 6456/// 'RHS' attributes and returns the merged version; including for function 6457/// return types. 6458QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 6459 QualType LHSCan = getCanonicalType(LHS), 6460 RHSCan = getCanonicalType(RHS); 6461 // If two types are identical, they are compatible. 6462 if (LHSCan == RHSCan) 6463 return LHS; 6464 if (RHSCan->isFunctionType()) { 6465 if (!LHSCan->isFunctionType()) 6466 return QualType(); 6467 QualType OldReturnType = 6468 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 6469 QualType NewReturnType = 6470 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 6471 QualType ResReturnType = 6472 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 6473 if (ResReturnType.isNull()) 6474 return QualType(); 6475 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 6476 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 6477 // In either case, use OldReturnType to build the new function type. 6478 const FunctionType *F = LHS->getAs<FunctionType>(); 6479 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 6480 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6481 EPI.ExtInfo = getFunctionExtInfo(LHS); 6482 QualType ResultType 6483 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 6484 FPT->getNumArgs(), EPI); 6485 return ResultType; 6486 } 6487 } 6488 return QualType(); 6489 } 6490 6491 // If the qualifiers are different, the types can still be merged. 6492 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6493 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6494 if (LQuals != RQuals) { 6495 // If any of these qualifiers are different, we have a type mismatch. 6496 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6497 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 6498 return QualType(); 6499 6500 // Exactly one GC qualifier difference is allowed: __strong is 6501 // okay if the other type has no GC qualifier but is an Objective 6502 // C object pointer (i.e. implicitly strong by default). We fix 6503 // this by pretending that the unqualified type was actually 6504 // qualified __strong. 6505 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6506 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6507 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6508 6509 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6510 return QualType(); 6511 6512 if (GC_L == Qualifiers::Strong) 6513 return LHS; 6514 if (GC_R == Qualifiers::Strong) 6515 return RHS; 6516 return QualType(); 6517 } 6518 6519 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 6520 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6521 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6522 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 6523 if (ResQT == LHSBaseQT) 6524 return LHS; 6525 if (ResQT == RHSBaseQT) 6526 return RHS; 6527 } 6528 return QualType(); 6529} 6530 6531//===----------------------------------------------------------------------===// 6532// Integer Predicates 6533//===----------------------------------------------------------------------===// 6534 6535unsigned ASTContext::getIntWidth(QualType T) const { 6536 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6537 T = ET->getDecl()->getIntegerType(); 6538 if (T->isBooleanType()) 6539 return 1; 6540 // For builtin types, just use the standard type sizing method 6541 return (unsigned)getTypeSize(T); 6542} 6543 6544QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 6545 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 6546 6547 // Turn <4 x signed int> -> <4 x unsigned int> 6548 if (const VectorType *VTy = T->getAs<VectorType>()) 6549 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 6550 VTy->getNumElements(), VTy->getVectorKind()); 6551 6552 // For enums, we return the unsigned version of the base type. 6553 if (const EnumType *ETy = T->getAs<EnumType>()) 6554 T = ETy->getDecl()->getIntegerType(); 6555 6556 const BuiltinType *BTy = T->getAs<BuiltinType>(); 6557 assert(BTy && "Unexpected signed integer type"); 6558 switch (BTy->getKind()) { 6559 case BuiltinType::Char_S: 6560 case BuiltinType::SChar: 6561 return UnsignedCharTy; 6562 case BuiltinType::Short: 6563 return UnsignedShortTy; 6564 case BuiltinType::Int: 6565 return UnsignedIntTy; 6566 case BuiltinType::Long: 6567 return UnsignedLongTy; 6568 case BuiltinType::LongLong: 6569 return UnsignedLongLongTy; 6570 case BuiltinType::Int128: 6571 return UnsignedInt128Ty; 6572 default: 6573 llvm_unreachable("Unexpected signed integer type"); 6574 } 6575} 6576 6577ASTMutationListener::~ASTMutationListener() { } 6578 6579 6580//===----------------------------------------------------------------------===// 6581// Builtin Type Computation 6582//===----------------------------------------------------------------------===// 6583 6584/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 6585/// pointer over the consumed characters. This returns the resultant type. If 6586/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 6587/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 6588/// a vector of "i*". 6589/// 6590/// RequiresICE is filled in on return to indicate whether the value is required 6591/// to be an Integer Constant Expression. 6592static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 6593 ASTContext::GetBuiltinTypeError &Error, 6594 bool &RequiresICE, 6595 bool AllowTypeModifiers) { 6596 // Modifiers. 6597 int HowLong = 0; 6598 bool Signed = false, Unsigned = false; 6599 RequiresICE = false; 6600 6601 // Read the prefixed modifiers first. 6602 bool Done = false; 6603 while (!Done) { 6604 switch (*Str++) { 6605 default: Done = true; --Str; break; 6606 case 'I': 6607 RequiresICE = true; 6608 break; 6609 case 'S': 6610 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 6611 assert(!Signed && "Can't use 'S' modifier multiple times!"); 6612 Signed = true; 6613 break; 6614 case 'U': 6615 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 6616 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 6617 Unsigned = true; 6618 break; 6619 case 'L': 6620 assert(HowLong <= 2 && "Can't have LLLL modifier"); 6621 ++HowLong; 6622 break; 6623 } 6624 } 6625 6626 QualType Type; 6627 6628 // Read the base type. 6629 switch (*Str++) { 6630 default: llvm_unreachable("Unknown builtin type letter!"); 6631 case 'v': 6632 assert(HowLong == 0 && !Signed && !Unsigned && 6633 "Bad modifiers used with 'v'!"); 6634 Type = Context.VoidTy; 6635 break; 6636 case 'f': 6637 assert(HowLong == 0 && !Signed && !Unsigned && 6638 "Bad modifiers used with 'f'!"); 6639 Type = Context.FloatTy; 6640 break; 6641 case 'd': 6642 assert(HowLong < 2 && !Signed && !Unsigned && 6643 "Bad modifiers used with 'd'!"); 6644 if (HowLong) 6645 Type = Context.LongDoubleTy; 6646 else 6647 Type = Context.DoubleTy; 6648 break; 6649 case 's': 6650 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 6651 if (Unsigned) 6652 Type = Context.UnsignedShortTy; 6653 else 6654 Type = Context.ShortTy; 6655 break; 6656 case 'i': 6657 if (HowLong == 3) 6658 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 6659 else if (HowLong == 2) 6660 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 6661 else if (HowLong == 1) 6662 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 6663 else 6664 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 6665 break; 6666 case 'c': 6667 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 6668 if (Signed) 6669 Type = Context.SignedCharTy; 6670 else if (Unsigned) 6671 Type = Context.UnsignedCharTy; 6672 else 6673 Type = Context.CharTy; 6674 break; 6675 case 'b': // boolean 6676 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 6677 Type = Context.BoolTy; 6678 break; 6679 case 'z': // size_t. 6680 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 6681 Type = Context.getSizeType(); 6682 break; 6683 case 'F': 6684 Type = Context.getCFConstantStringType(); 6685 break; 6686 case 'G': 6687 Type = Context.getObjCIdType(); 6688 break; 6689 case 'H': 6690 Type = Context.getObjCSelType(); 6691 break; 6692 case 'a': 6693 Type = Context.getBuiltinVaListType(); 6694 assert(!Type.isNull() && "builtin va list type not initialized!"); 6695 break; 6696 case 'A': 6697 // This is a "reference" to a va_list; however, what exactly 6698 // this means depends on how va_list is defined. There are two 6699 // different kinds of va_list: ones passed by value, and ones 6700 // passed by reference. An example of a by-value va_list is 6701 // x86, where va_list is a char*. An example of by-ref va_list 6702 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 6703 // we want this argument to be a char*&; for x86-64, we want 6704 // it to be a __va_list_tag*. 6705 Type = Context.getBuiltinVaListType(); 6706 assert(!Type.isNull() && "builtin va list type not initialized!"); 6707 if (Type->isArrayType()) 6708 Type = Context.getArrayDecayedType(Type); 6709 else 6710 Type = Context.getLValueReferenceType(Type); 6711 break; 6712 case 'V': { 6713 char *End; 6714 unsigned NumElements = strtoul(Str, &End, 10); 6715 assert(End != Str && "Missing vector size"); 6716 Str = End; 6717 6718 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 6719 RequiresICE, false); 6720 assert(!RequiresICE && "Can't require vector ICE"); 6721 6722 // TODO: No way to make AltiVec vectors in builtins yet. 6723 Type = Context.getVectorType(ElementType, NumElements, 6724 VectorType::GenericVector); 6725 break; 6726 } 6727 case 'E': { 6728 char *End; 6729 6730 unsigned NumElements = strtoul(Str, &End, 10); 6731 assert(End != Str && "Missing vector size"); 6732 6733 Str = End; 6734 6735 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6736 false); 6737 Type = Context.getExtVectorType(ElementType, NumElements); 6738 break; 6739 } 6740 case 'X': { 6741 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6742 false); 6743 assert(!RequiresICE && "Can't require complex ICE"); 6744 Type = Context.getComplexType(ElementType); 6745 break; 6746 } 6747 case 'Y' : { 6748 Type = Context.getPointerDiffType(); 6749 break; 6750 } 6751 case 'P': 6752 Type = Context.getFILEType(); 6753 if (Type.isNull()) { 6754 Error = ASTContext::GE_Missing_stdio; 6755 return QualType(); 6756 } 6757 break; 6758 case 'J': 6759 if (Signed) 6760 Type = Context.getsigjmp_bufType(); 6761 else 6762 Type = Context.getjmp_bufType(); 6763 6764 if (Type.isNull()) { 6765 Error = ASTContext::GE_Missing_setjmp; 6766 return QualType(); 6767 } 6768 break; 6769 case 'K': 6770 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 6771 Type = Context.getucontext_tType(); 6772 6773 if (Type.isNull()) { 6774 Error = ASTContext::GE_Missing_ucontext; 6775 return QualType(); 6776 } 6777 break; 6778 } 6779 6780 // If there are modifiers and if we're allowed to parse them, go for it. 6781 Done = !AllowTypeModifiers; 6782 while (!Done) { 6783 switch (char c = *Str++) { 6784 default: Done = true; --Str; break; 6785 case '*': 6786 case '&': { 6787 // Both pointers and references can have their pointee types 6788 // qualified with an address space. 6789 char *End; 6790 unsigned AddrSpace = strtoul(Str, &End, 10); 6791 if (End != Str && AddrSpace != 0) { 6792 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 6793 Str = End; 6794 } 6795 if (c == '*') 6796 Type = Context.getPointerType(Type); 6797 else 6798 Type = Context.getLValueReferenceType(Type); 6799 break; 6800 } 6801 // FIXME: There's no way to have a built-in with an rvalue ref arg. 6802 case 'C': 6803 Type = Type.withConst(); 6804 break; 6805 case 'D': 6806 Type = Context.getVolatileType(Type); 6807 break; 6808 case 'R': 6809 Type = Type.withRestrict(); 6810 break; 6811 } 6812 } 6813 6814 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 6815 "Integer constant 'I' type must be an integer"); 6816 6817 return Type; 6818} 6819 6820/// GetBuiltinType - Return the type for the specified builtin. 6821QualType ASTContext::GetBuiltinType(unsigned Id, 6822 GetBuiltinTypeError &Error, 6823 unsigned *IntegerConstantArgs) const { 6824 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 6825 6826 SmallVector<QualType, 8> ArgTypes; 6827 6828 bool RequiresICE = false; 6829 Error = GE_None; 6830 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 6831 RequiresICE, true); 6832 if (Error != GE_None) 6833 return QualType(); 6834 6835 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 6836 6837 while (TypeStr[0] && TypeStr[0] != '.') { 6838 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 6839 if (Error != GE_None) 6840 return QualType(); 6841 6842 // If this argument is required to be an IntegerConstantExpression and the 6843 // caller cares, fill in the bitmask we return. 6844 if (RequiresICE && IntegerConstantArgs) 6845 *IntegerConstantArgs |= 1 << ArgTypes.size(); 6846 6847 // Do array -> pointer decay. The builtin should use the decayed type. 6848 if (Ty->isArrayType()) 6849 Ty = getArrayDecayedType(Ty); 6850 6851 ArgTypes.push_back(Ty); 6852 } 6853 6854 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 6855 "'.' should only occur at end of builtin type list!"); 6856 6857 FunctionType::ExtInfo EI; 6858 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 6859 6860 bool Variadic = (TypeStr[0] == '.'); 6861 6862 // We really shouldn't be making a no-proto type here, especially in C++. 6863 if (ArgTypes.empty() && Variadic) 6864 return getFunctionNoProtoType(ResType, EI); 6865 6866 FunctionProtoType::ExtProtoInfo EPI; 6867 EPI.ExtInfo = EI; 6868 EPI.Variadic = Variadic; 6869 6870 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI); 6871} 6872 6873GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 6874 GVALinkage External = GVA_StrongExternal; 6875 6876 Linkage L = FD->getLinkage(); 6877 switch (L) { 6878 case NoLinkage: 6879 case InternalLinkage: 6880 case UniqueExternalLinkage: 6881 return GVA_Internal; 6882 6883 case ExternalLinkage: 6884 switch (FD->getTemplateSpecializationKind()) { 6885 case TSK_Undeclared: 6886 case TSK_ExplicitSpecialization: 6887 External = GVA_StrongExternal; 6888 break; 6889 6890 case TSK_ExplicitInstantiationDefinition: 6891 return GVA_ExplicitTemplateInstantiation; 6892 6893 case TSK_ExplicitInstantiationDeclaration: 6894 case TSK_ImplicitInstantiation: 6895 External = GVA_TemplateInstantiation; 6896 break; 6897 } 6898 } 6899 6900 if (!FD->isInlined()) 6901 return External; 6902 6903 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 6904 // GNU or C99 inline semantics. Determine whether this symbol should be 6905 // externally visible. 6906 if (FD->isInlineDefinitionExternallyVisible()) 6907 return External; 6908 6909 // C99 inline semantics, where the symbol is not externally visible. 6910 return GVA_C99Inline; 6911 } 6912 6913 // C++0x [temp.explicit]p9: 6914 // [ Note: The intent is that an inline function that is the subject of 6915 // an explicit instantiation declaration will still be implicitly 6916 // instantiated when used so that the body can be considered for 6917 // inlining, but that no out-of-line copy of the inline function would be 6918 // generated in the translation unit. -- end note ] 6919 if (FD->getTemplateSpecializationKind() 6920 == TSK_ExplicitInstantiationDeclaration) 6921 return GVA_C99Inline; 6922 6923 return GVA_CXXInline; 6924} 6925 6926GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 6927 // If this is a static data member, compute the kind of template 6928 // specialization. Otherwise, this variable is not part of a 6929 // template. 6930 TemplateSpecializationKind TSK = TSK_Undeclared; 6931 if (VD->isStaticDataMember()) 6932 TSK = VD->getTemplateSpecializationKind(); 6933 6934 Linkage L = VD->getLinkage(); 6935 if (L == ExternalLinkage && getLangOpts().CPlusPlus && 6936 VD->getType()->getLinkage() == UniqueExternalLinkage) 6937 L = UniqueExternalLinkage; 6938 6939 switch (L) { 6940 case NoLinkage: 6941 case InternalLinkage: 6942 case UniqueExternalLinkage: 6943 return GVA_Internal; 6944 6945 case ExternalLinkage: 6946 switch (TSK) { 6947 case TSK_Undeclared: 6948 case TSK_ExplicitSpecialization: 6949 return GVA_StrongExternal; 6950 6951 case TSK_ExplicitInstantiationDeclaration: 6952 llvm_unreachable("Variable should not be instantiated"); 6953 // Fall through to treat this like any other instantiation. 6954 6955 case TSK_ExplicitInstantiationDefinition: 6956 return GVA_ExplicitTemplateInstantiation; 6957 6958 case TSK_ImplicitInstantiation: 6959 return GVA_TemplateInstantiation; 6960 } 6961 } 6962 6963 llvm_unreachable("Invalid Linkage!"); 6964} 6965 6966bool ASTContext::DeclMustBeEmitted(const Decl *D) { 6967 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6968 if (!VD->isFileVarDecl()) 6969 return false; 6970 } else if (!isa<FunctionDecl>(D)) 6971 return false; 6972 6973 // Weak references don't produce any output by themselves. 6974 if (D->hasAttr<WeakRefAttr>()) 6975 return false; 6976 6977 // Aliases and used decls are required. 6978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 6979 return true; 6980 6981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6982 // Forward declarations aren't required. 6983 if (!FD->doesThisDeclarationHaveABody()) 6984 return FD->doesDeclarationForceExternallyVisibleDefinition(); 6985 6986 // Constructors and destructors are required. 6987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 6988 return true; 6989 6990 // The key function for a class is required. 6991 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6992 const CXXRecordDecl *RD = MD->getParent(); 6993 if (MD->isOutOfLine() && RD->isDynamicClass()) { 6994 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 6995 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 6996 return true; 6997 } 6998 } 6999 7000 GVALinkage Linkage = GetGVALinkageForFunction(FD); 7001 7002 // static, static inline, always_inline, and extern inline functions can 7003 // always be deferred. Normal inline functions can be deferred in C99/C++. 7004 // Implicit template instantiations can also be deferred in C++. 7005 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 7006 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 7007 return false; 7008 return true; 7009 } 7010 7011 const VarDecl *VD = cast<VarDecl>(D); 7012 assert(VD->isFileVarDecl() && "Expected file scoped var"); 7013 7014 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 7015 return false; 7016 7017 // Structs that have non-trivial constructors or destructors are required. 7018 7019 // FIXME: Handle references. 7020 // FIXME: Be more selective about which constructors we care about. 7021 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 7022 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 7023 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() && 7024 RD->hasTrivialCopyConstructor() && 7025 RD->hasTrivialMoveConstructor() && 7026 RD->hasTrivialDestructor())) 7027 return true; 7028 } 7029 } 7030 7031 GVALinkage L = GetGVALinkageForVariable(VD); 7032 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 7033 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 7034 return false; 7035 } 7036 7037 return true; 7038} 7039 7040CallingConv ASTContext::getDefaultMethodCallConv() { 7041 // Pass through to the C++ ABI object 7042 return ABI->getDefaultMethodCallConv(); 7043} 7044 7045bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 7046 // Pass through to the C++ ABI object 7047 return ABI->isNearlyEmpty(RD); 7048} 7049 7050MangleContext *ASTContext::createMangleContext() { 7051 switch (Target->getCXXABI()) { 7052 case CXXABI_ARM: 7053 case CXXABI_Itanium: 7054 return createItaniumMangleContext(*this, getDiagnostics()); 7055 case CXXABI_Microsoft: 7056 return createMicrosoftMangleContext(*this, getDiagnostics()); 7057 } 7058 llvm_unreachable("Unsupported ABI"); 7059} 7060 7061CXXABI::~CXXABI() {} 7062 7063size_t ASTContext::getSideTableAllocatedMemory() const { 7064 return ASTRecordLayouts.getMemorySize() 7065 + llvm::capacity_in_bytes(ObjCLayouts) 7066 + llvm::capacity_in_bytes(KeyFunctions) 7067 + llvm::capacity_in_bytes(ObjCImpls) 7068 + llvm::capacity_in_bytes(BlockVarCopyInits) 7069 + llvm::capacity_in_bytes(DeclAttrs) 7070 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember) 7071 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) 7072 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) 7073 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) 7074 + llvm::capacity_in_bytes(OverriddenMethods) 7075 + llvm::capacity_in_bytes(Types) 7076 + llvm::capacity_in_bytes(VariableArrayTypes) 7077 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 7078} 7079 7080unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) { 7081 CXXRecordDecl *Lambda = CallOperator->getParent(); 7082 return LambdaMangleContexts[Lambda->getDeclContext()] 7083 .getManglingNumber(CallOperator); 7084} 7085 7086 7087void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 7088 ParamIndices[D] = index; 7089} 7090 7091unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 7092 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 7093 assert(I != ParamIndices.end() && 7094 "ParmIndices lacks entry set by ParmVarDecl"); 7095 return I->second; 7096} 7097