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