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