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