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