Decl.cpp revision 4ba2a17694148e16eaa8d3917f657ffcd3667be4
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===// 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 Decl subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Decl.h" 15#include "clang/AST/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/Stmt.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/PrettyPrinter.h" 24#include "clang/AST/ASTMutationListener.h" 25#include "clang/Basic/Builtins.h" 26#include "clang/Basic/IdentifierTable.h" 27#include "clang/Basic/Specifiers.h" 28#include "llvm/Support/ErrorHandling.h" 29 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// NamedDecl Implementation 34//===----------------------------------------------------------------------===// 35 36static const VisibilityAttr *GetExplicitVisibility(const Decl *d) { 37 // Use the most recent declaration of a variable. 38 if (const VarDecl *var = dyn_cast<VarDecl>(d)) 39 return var->getMostRecentDeclaration()->getAttr<VisibilityAttr>(); 40 41 // Use the most recent declaration of a function, and also handle 42 // function template specializations. 43 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(d)) { 44 if (const VisibilityAttr *attr 45 = fn->getMostRecentDeclaration()->getAttr<VisibilityAttr>()) 46 return attr; 47 48 // If the function is a specialization of a template with an 49 // explicit visibility attribute, use that. 50 if (FunctionTemplateSpecializationInfo *templateInfo 51 = fn->getTemplateSpecializationInfo()) 52 return templateInfo->getTemplate()->getTemplatedDecl() 53 ->getAttr<VisibilityAttr>(); 54 55 return 0; 56 } 57 58 // Otherwise, just check the declaration itself first. 59 if (const VisibilityAttr *attr = d->getAttr<VisibilityAttr>()) 60 return attr; 61 62 // If there wasn't explicit visibility there, and this is a 63 // specialization of a class template, check for visibility 64 // on the pattern. 65 if (const ClassTemplateSpecializationDecl *spec 66 = dyn_cast<ClassTemplateSpecializationDecl>(d)) 67 return spec->getSpecializedTemplate()->getTemplatedDecl() 68 ->getAttr<VisibilityAttr>(); 69 70 return 0; 71} 72 73static Visibility GetVisibilityFromAttr(const VisibilityAttr *A) { 74 switch (A->getVisibility()) { 75 case VisibilityAttr::Default: 76 return DefaultVisibility; 77 case VisibilityAttr::Hidden: 78 return HiddenVisibility; 79 case VisibilityAttr::Protected: 80 return ProtectedVisibility; 81 } 82 return DefaultVisibility; 83} 84 85typedef NamedDecl::LinkageInfo LinkageInfo; 86typedef std::pair<Linkage,Visibility> LVPair; 87 88static LVPair merge(LVPair L, LVPair R) { 89 return LVPair(minLinkage(L.first, R.first), 90 minVisibility(L.second, R.second)); 91} 92 93static LVPair merge(LVPair L, LinkageInfo R) { 94 return LVPair(minLinkage(L.first, R.linkage()), 95 minVisibility(L.second, R.visibility())); 96} 97 98namespace { 99/// Flags controlling the computation of linkage and visibility. 100struct LVFlags { 101 bool ConsiderGlobalVisibility; 102 bool ConsiderVisibilityAttributes; 103 104 LVFlags() : ConsiderGlobalVisibility(true), 105 ConsiderVisibilityAttributes(true) { 106 } 107 108 /// \brief Returns a set of flags that is only useful for computing the 109 /// linkage, not the visibility, of a declaration. 110 static LVFlags CreateOnlyDeclLinkage() { 111 LVFlags F; 112 F.ConsiderGlobalVisibility = false; 113 F.ConsiderVisibilityAttributes = false; 114 return F; 115 } 116 117 /// Returns a set of flags, otherwise based on these, which ignores 118 /// off all sources of visibility except template arguments. 119 LVFlags onlyTemplateVisibility() const { 120 LVFlags F = *this; 121 F.ConsiderGlobalVisibility = false; 122 F.ConsiderVisibilityAttributes = false; 123 return F; 124 } 125}; 126} // end anonymous namespace 127 128/// \brief Get the most restrictive linkage for the types in the given 129/// template parameter list. 130static LVPair 131getLVForTemplateParameterList(const TemplateParameterList *Params) { 132 LVPair LV(ExternalLinkage, DefaultVisibility); 133 for (TemplateParameterList::const_iterator P = Params->begin(), 134 PEnd = Params->end(); 135 P != PEnd; ++P) { 136 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) 137 if (!NTTP->getType()->isDependentType()) { 138 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility()); 139 continue; 140 } 141 142 if (TemplateTemplateParmDecl *TTP 143 = dyn_cast<TemplateTemplateParmDecl>(*P)) { 144 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters())); 145 } 146 } 147 148 return LV; 149} 150 151/// getLVForDecl - Get the linkage and visibility for the given declaration. 152static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F); 153 154/// \brief Get the most restrictive linkage for the types and 155/// declarations in the given template argument list. 156static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args, 157 unsigned NumArgs, 158 LVFlags &F) { 159 LVPair LV(ExternalLinkage, DefaultVisibility); 160 161 for (unsigned I = 0; I != NumArgs; ++I) { 162 switch (Args[I].getKind()) { 163 case TemplateArgument::Null: 164 case TemplateArgument::Integral: 165 case TemplateArgument::Expression: 166 break; 167 168 case TemplateArgument::Type: 169 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility()); 170 break; 171 172 case TemplateArgument::Declaration: 173 // The decl can validly be null as the representation of nullptr 174 // arguments, valid only in C++0x. 175 if (Decl *D = Args[I].getAsDecl()) { 176 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 177 LV = merge(LV, getLVForDecl(ND, F)); 178 } 179 break; 180 181 case TemplateArgument::Template: 182 case TemplateArgument::TemplateExpansion: 183 if (TemplateDecl *Template 184 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 185 LV = merge(LV, getLVForDecl(Template, F)); 186 break; 187 188 case TemplateArgument::Pack: 189 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(), 190 Args[I].pack_size(), 191 F)); 192 break; 193 } 194 } 195 196 return LV; 197} 198 199static LVPair 200getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 201 LVFlags &F) { 202 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F); 203} 204 205static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) { 206 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 207 "Not a name having namespace scope"); 208 ASTContext &Context = D->getASTContext(); 209 210 // C++ [basic.link]p3: 211 // A name having namespace scope (3.3.6) has internal linkage if it 212 // is the name of 213 // - an object, reference, function or function template that is 214 // explicitly declared static; or, 215 // (This bullet corresponds to C99 6.2.2p3.) 216 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 217 // Explicitly declared static. 218 if (Var->getStorageClass() == SC_Static) 219 return LinkageInfo::internal(); 220 221 // - an object or reference that is explicitly declared const 222 // and neither explicitly declared extern nor previously 223 // declared to have external linkage; or 224 // (there is no equivalent in C99) 225 if (Context.getLangOptions().CPlusPlus && 226 Var->getType().isConstant(Context) && 227 Var->getStorageClass() != SC_Extern && 228 Var->getStorageClass() != SC_PrivateExtern) { 229 bool FoundExtern = false; 230 for (const VarDecl *PrevVar = Var->getPreviousDeclaration(); 231 PrevVar && !FoundExtern; 232 PrevVar = PrevVar->getPreviousDeclaration()) 233 if (isExternalLinkage(PrevVar->getLinkage())) 234 FoundExtern = true; 235 236 if (!FoundExtern) 237 return LinkageInfo::internal(); 238 } 239 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 240 // C++ [temp]p4: 241 // A non-member function template can have internal linkage; any 242 // other template name shall have external linkage. 243 const FunctionDecl *Function = 0; 244 if (const FunctionTemplateDecl *FunTmpl 245 = dyn_cast<FunctionTemplateDecl>(D)) 246 Function = FunTmpl->getTemplatedDecl(); 247 else 248 Function = cast<FunctionDecl>(D); 249 250 // Explicitly declared static. 251 if (Function->getStorageClass() == SC_Static) 252 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 253 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 254 // - a data member of an anonymous union. 255 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 256 return LinkageInfo::internal(); 257 } 258 259 if (D->isInAnonymousNamespace()) 260 return LinkageInfo::uniqueExternal(); 261 262 // Set up the defaults. 263 264 // C99 6.2.2p5: 265 // If the declaration of an identifier for an object has file 266 // scope and no storage-class specifier, its linkage is 267 // external. 268 LinkageInfo LV; 269 270 if (F.ConsiderVisibilityAttributes) { 271 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) { 272 LV.setVisibility(GetVisibilityFromAttr(VA), true); 273 F.ConsiderGlobalVisibility = false; 274 } else { 275 // If we're declared in a namespace with a visibility attribute, 276 // use that namespace's visibility, but don't call it explicit. 277 for (const DeclContext *DC = D->getDeclContext(); 278 !isa<TranslationUnitDecl>(DC); 279 DC = DC->getParent()) { 280 if (!isa<NamespaceDecl>(DC)) continue; 281 if (const VisibilityAttr *VA = 282 cast<NamespaceDecl>(DC)->getAttr<VisibilityAttr>()) { 283 LV.setVisibility(GetVisibilityFromAttr(VA), false); 284 F.ConsiderGlobalVisibility = false; 285 break; 286 } 287 } 288 } 289 } 290 291 // C++ [basic.link]p4: 292 293 // A name having namespace scope has external linkage if it is the 294 // name of 295 // 296 // - an object or reference, unless it has internal linkage; or 297 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 298 // GCC applies the following optimization to variables and static 299 // data members, but not to functions: 300 // 301 // Modify the variable's LV by the LV of its type unless this is 302 // C or extern "C". This follows from [basic.link]p9: 303 // A type without linkage shall not be used as the type of a 304 // variable or function with external linkage unless 305 // - the entity has C language linkage, or 306 // - the entity is declared within an unnamed namespace, or 307 // - the entity is not used or is defined in the same 308 // translation unit. 309 // and [basic.link]p10: 310 // ...the types specified by all declarations referring to a 311 // given variable or function shall be identical... 312 // C does not have an equivalent rule. 313 // 314 // Ignore this if we've got an explicit attribute; the user 315 // probably knows what they're doing. 316 // 317 // Note that we don't want to make the variable non-external 318 // because of this, but unique-external linkage suits us. 319 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) { 320 LVPair TypeLV = Var->getType()->getLinkageAndVisibility(); 321 if (TypeLV.first != ExternalLinkage) 322 return LinkageInfo::uniqueExternal(); 323 if (!LV.visibilityExplicit()) 324 LV.mergeVisibility(TypeLV.second); 325 } 326 327 if (Var->getStorageClass() == SC_PrivateExtern) 328 LV.setVisibility(HiddenVisibility, true); 329 330 if (!Context.getLangOptions().CPlusPlus && 331 (Var->getStorageClass() == SC_Extern || 332 Var->getStorageClass() == SC_PrivateExtern)) { 333 334 // C99 6.2.2p4: 335 // For an identifier declared with the storage-class specifier 336 // extern in a scope in which a prior declaration of that 337 // identifier is visible, if the prior declaration specifies 338 // internal or external linkage, the linkage of the identifier 339 // at the later declaration is the same as the linkage 340 // specified at the prior declaration. If no prior declaration 341 // is visible, or if the prior declaration specifies no 342 // linkage, then the identifier has external linkage. 343 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) { 344 LinkageInfo PrevLV = getLVForDecl(PrevVar, F); 345 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 346 LV.mergeVisibility(PrevLV); 347 } 348 } 349 350 // - a function, unless it has internal linkage; or 351 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 352 // In theory, we can modify the function's LV by the LV of its 353 // type unless it has C linkage (see comment above about variables 354 // for justification). In practice, GCC doesn't do this, so it's 355 // just too painful to make work. 356 357 if (Function->getStorageClass() == SC_PrivateExtern) 358 LV.setVisibility(HiddenVisibility, true); 359 360 // C99 6.2.2p5: 361 // If the declaration of an identifier for a function has no 362 // storage-class specifier, its linkage is determined exactly 363 // as if it were declared with the storage-class specifier 364 // extern. 365 if (!Context.getLangOptions().CPlusPlus && 366 (Function->getStorageClass() == SC_Extern || 367 Function->getStorageClass() == SC_PrivateExtern || 368 Function->getStorageClass() == SC_None)) { 369 // C99 6.2.2p4: 370 // For an identifier declared with the storage-class specifier 371 // extern in a scope in which a prior declaration of that 372 // identifier is visible, if the prior declaration specifies 373 // internal or external linkage, the linkage of the identifier 374 // at the later declaration is the same as the linkage 375 // specified at the prior declaration. If no prior declaration 376 // is visible, or if the prior declaration specifies no 377 // linkage, then the identifier has external linkage. 378 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) { 379 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F); 380 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 381 LV.mergeVisibility(PrevLV); 382 } 383 } 384 385 if (FunctionTemplateSpecializationInfo *SpecInfo 386 = Function->getTemplateSpecializationInfo()) { 387 LV.merge(getLVForDecl(SpecInfo->getTemplate(), 388 F.onlyTemplateVisibility())); 389 const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments; 390 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F)); 391 } 392 393 // - a named class (Clause 9), or an unnamed class defined in a 394 // typedef declaration in which the class has the typedef name 395 // for linkage purposes (7.1.3); or 396 // - a named enumeration (7.2), or an unnamed enumeration 397 // defined in a typedef declaration in which the enumeration 398 // has the typedef name for linkage purposes (7.1.3); or 399 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) { 400 // Unnamed tags have no linkage. 401 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) 402 return LinkageInfo::none(); 403 404 // If this is a class template specialization, consider the 405 // linkage of the template and template arguments. 406 if (const ClassTemplateSpecializationDecl *Spec 407 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 408 // From the template. 409 LV.merge(getLVForDecl(Spec->getSpecializedTemplate(), 410 F.onlyTemplateVisibility())); 411 412 // The arguments at which the template was instantiated. 413 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 414 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F)); 415 } 416 417 // Consider -fvisibility unless the type has C linkage. 418 if (F.ConsiderGlobalVisibility) 419 F.ConsiderGlobalVisibility = 420 (Context.getLangOptions().CPlusPlus && 421 !Tag->getDeclContext()->isExternCContext()); 422 423 // - an enumerator belonging to an enumeration with external linkage; 424 } else if (isa<EnumConstantDecl>(D)) { 425 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F); 426 if (!isExternalLinkage(EnumLV.linkage())) 427 return LinkageInfo::none(); 428 LV.merge(EnumLV); 429 430 // - a template, unless it is a function template that has 431 // internal linkage (Clause 14); 432 } else if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 433 LV.merge(getLVForTemplateParameterList(Template->getTemplateParameters())); 434 435 // - a namespace (7.3), unless it is declared within an unnamed 436 // namespace. 437 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) { 438 return LV; 439 440 // By extension, we assign external linkage to Objective-C 441 // interfaces. 442 } else if (isa<ObjCInterfaceDecl>(D)) { 443 // fallout 444 445 // Everything not covered here has no linkage. 446 } else { 447 return LinkageInfo::none(); 448 } 449 450 // If we ended up with non-external linkage, visibility should 451 // always be default. 452 if (LV.linkage() != ExternalLinkage) 453 return LinkageInfo(LV.linkage(), DefaultVisibility, false); 454 455 // If we didn't end up with hidden visibility, consider attributes 456 // and -fvisibility. 457 if (F.ConsiderGlobalVisibility) 458 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode()); 459 460 return LV; 461} 462 463static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) { 464 // Only certain class members have linkage. Note that fields don't 465 // really have linkage, but it's convenient to say they do for the 466 // purposes of calculating linkage of pointer-to-data-member 467 // template arguments. 468 if (!(isa<CXXMethodDecl>(D) || 469 isa<VarDecl>(D) || 470 isa<FieldDecl>(D) || 471 (isa<TagDecl>(D) && 472 (D->getDeclName() || cast<TagDecl>(D)->getTypedefForAnonDecl())))) 473 return LinkageInfo::none(); 474 475 LinkageInfo LV; 476 477 // The flags we're going to use to compute the class's visibility. 478 LVFlags ClassF = F; 479 480 // If we have an explicit visibility attribute, merge that in. 481 if (F.ConsiderVisibilityAttributes) { 482 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) { 483 LV.mergeVisibility(GetVisibilityFromAttr(VA), true); 484 485 // Ignore global visibility later, but not this attribute. 486 F.ConsiderGlobalVisibility = false; 487 488 // Ignore both global visibility and attributes when computing our 489 // parent's visibility. 490 ClassF = F.onlyTemplateVisibility(); 491 } 492 } 493 494 // Class members only have linkage if their class has external 495 // linkage. 496 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF)); 497 if (!isExternalLinkage(LV.linkage())) 498 return LinkageInfo::none(); 499 500 // If the class already has unique-external linkage, we can't improve. 501 if (LV.linkage() == UniqueExternalLinkage) 502 return LinkageInfo::uniqueExternal(); 503 504 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 505 TemplateSpecializationKind TSK = TSK_Undeclared; 506 507 // If this is a method template specialization, use the linkage for 508 // the template parameters and arguments. 509 if (FunctionTemplateSpecializationInfo *Spec 510 = MD->getTemplateSpecializationInfo()) { 511 LV.merge(getLVForTemplateArgumentList(*Spec->TemplateArguments, F)); 512 LV.merge(getLVForTemplateParameterList( 513 Spec->getTemplate()->getTemplateParameters())); 514 515 TSK = Spec->getTemplateSpecializationKind(); 516 } else if (MemberSpecializationInfo *MSI = 517 MD->getMemberSpecializationInfo()) { 518 TSK = MSI->getTemplateSpecializationKind(); 519 } 520 521 // If we're paying attention to global visibility, apply 522 // -finline-visibility-hidden if this is an inline method. 523 // 524 // Note that ConsiderGlobalVisibility doesn't yet have information 525 // about whether containing classes have visibility attributes, 526 // and that's intentional. 527 if (TSK != TSK_ExplicitInstantiationDeclaration && 528 F.ConsiderGlobalVisibility && 529 MD->getASTContext().getLangOptions().InlineVisibilityHidden) { 530 // InlineVisibilityHidden only applies to definitions, and 531 // isInlined() only gives meaningful answers on definitions 532 // anyway. 533 const FunctionDecl *Def = 0; 534 if (MD->hasBody(Def) && Def->isInlined()) 535 LV.setVisibility(HiddenVisibility); 536 } 537 538 // Note that in contrast to basically every other situation, we 539 // *do* apply -fvisibility to method declarations. 540 541 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 542 if (const ClassTemplateSpecializationDecl *Spec 543 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 544 // Merge template argument/parameter information for member 545 // class template specializations. 546 LV.merge(getLVForTemplateArgumentList(Spec->getTemplateArgs(), F)); 547 LV.merge(getLVForTemplateParameterList( 548 Spec->getSpecializedTemplate()->getTemplateParameters())); 549 } 550 551 // Static data members. 552 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 553 // Modify the variable's linkage by its type, but ignore the 554 // type's visibility unless it's a definition. 555 LVPair TypeLV = VD->getType()->getLinkageAndVisibility(); 556 if (TypeLV.first != ExternalLinkage) 557 LV.mergeLinkage(UniqueExternalLinkage); 558 if (!LV.visibilityExplicit()) 559 LV.mergeVisibility(TypeLV.second); 560 } 561 562 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit(); 563 564 // Apply -fvisibility if desired. 565 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) { 566 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode()); 567 } 568 569 return LV; 570} 571 572Linkage NamedDecl::getLinkage() const { 573 if (HasCachedLinkage) { 574 assert(Linkage(CachedLinkage) == 575 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage()); 576 return Linkage(CachedLinkage); 577 } 578 579 CachedLinkage = getLVForDecl(this, 580 LVFlags::CreateOnlyDeclLinkage()).linkage(); 581 HasCachedLinkage = 1; 582 return Linkage(CachedLinkage); 583} 584 585LinkageInfo NamedDecl::getLinkageAndVisibility() const { 586 LinkageInfo LI = getLVForDecl(this, LVFlags()); 587 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage()); 588 HasCachedLinkage = 1; 589 CachedLinkage = LI.linkage(); 590 return LI; 591} 592 593static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) { 594 // Objective-C: treat all Objective-C declarations as having external 595 // linkage. 596 switch (D->getKind()) { 597 default: 598 break; 599 case Decl::TemplateTemplateParm: // count these as external 600 case Decl::NonTypeTemplateParm: 601 case Decl::ObjCAtDefsField: 602 case Decl::ObjCCategory: 603 case Decl::ObjCCategoryImpl: 604 case Decl::ObjCCompatibleAlias: 605 case Decl::ObjCForwardProtocol: 606 case Decl::ObjCImplementation: 607 case Decl::ObjCMethod: 608 case Decl::ObjCProperty: 609 case Decl::ObjCPropertyImpl: 610 case Decl::ObjCProtocol: 611 return LinkageInfo::external(); 612 } 613 614 // Handle linkage for namespace-scope names. 615 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 616 return getLVForNamespaceScopeDecl(D, Flags); 617 618 // C++ [basic.link]p5: 619 // In addition, a member function, static data member, a named 620 // class or enumeration of class scope, or an unnamed class or 621 // enumeration defined in a class-scope typedef declaration such 622 // that the class or enumeration has the typedef name for linkage 623 // purposes (7.1.3), has external linkage if the name of the class 624 // has external linkage. 625 if (D->getDeclContext()->isRecord()) 626 return getLVForClassMember(D, Flags); 627 628 // C++ [basic.link]p6: 629 // The name of a function declared in block scope and the name of 630 // an object declared by a block scope extern declaration have 631 // linkage. If there is a visible declaration of an entity with 632 // linkage having the same name and type, ignoring entities 633 // declared outside the innermost enclosing namespace scope, the 634 // block scope declaration declares that same entity and receives 635 // the linkage of the previous declaration. If there is more than 636 // one such matching entity, the program is ill-formed. Otherwise, 637 // if no matching entity is found, the block scope entity receives 638 // external linkage. 639 if (D->getLexicalDeclContext()->isFunctionOrMethod()) { 640 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 641 if (Function->isInAnonymousNamespace()) 642 return LinkageInfo::uniqueExternal(); 643 644 LinkageInfo LV; 645 if (Flags.ConsiderVisibilityAttributes) { 646 if (const VisibilityAttr *VA = GetExplicitVisibility(Function)) 647 LV.setVisibility(GetVisibilityFromAttr(VA)); 648 } 649 650 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) { 651 LinkageInfo PrevLV = getLVForDecl(Prev, Flags); 652 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 653 LV.mergeVisibility(PrevLV); 654 } 655 656 return LV; 657 } 658 659 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) 660 if (Var->getStorageClass() == SC_Extern || 661 Var->getStorageClass() == SC_PrivateExtern) { 662 if (Var->isInAnonymousNamespace()) 663 return LinkageInfo::uniqueExternal(); 664 665 LinkageInfo LV; 666 if (Var->getStorageClass() == SC_PrivateExtern) 667 LV.setVisibility(HiddenVisibility); 668 else if (Flags.ConsiderVisibilityAttributes) { 669 if (const VisibilityAttr *VA = GetExplicitVisibility(Var)) 670 LV.setVisibility(GetVisibilityFromAttr(VA)); 671 } 672 673 if (const VarDecl *Prev = Var->getPreviousDeclaration()) { 674 LinkageInfo PrevLV = getLVForDecl(Prev, Flags); 675 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 676 LV.mergeVisibility(PrevLV); 677 } 678 679 return LV; 680 } 681 } 682 683 // C++ [basic.link]p6: 684 // Names not covered by these rules have no linkage. 685 return LinkageInfo::none(); 686} 687 688std::string NamedDecl::getQualifiedNameAsString() const { 689 return getQualifiedNameAsString(getASTContext().getLangOptions()); 690} 691 692std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 693 const DeclContext *Ctx = getDeclContext(); 694 695 if (Ctx->isFunctionOrMethod()) 696 return getNameAsString(); 697 698 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy; 699 ContextsTy Contexts; 700 701 // Collect contexts. 702 while (Ctx && isa<NamedDecl>(Ctx)) { 703 Contexts.push_back(Ctx); 704 Ctx = Ctx->getParent(); 705 }; 706 707 std::string QualName; 708 llvm::raw_string_ostream OS(QualName); 709 710 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 711 I != E; ++I) { 712 if (const ClassTemplateSpecializationDecl *Spec 713 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 714 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 715 std::string TemplateArgsStr 716 = TemplateSpecializationType::PrintTemplateArgumentList( 717 TemplateArgs.data(), 718 TemplateArgs.size(), 719 P); 720 OS << Spec->getName() << TemplateArgsStr; 721 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 722 if (ND->isAnonymousNamespace()) 723 OS << "<anonymous namespace>"; 724 else 725 OS << ND; 726 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 727 if (!RD->getIdentifier()) 728 OS << "<anonymous " << RD->getKindName() << '>'; 729 else 730 OS << RD; 731 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 732 const FunctionProtoType *FT = 0; 733 if (FD->hasWrittenPrototype()) 734 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 735 736 OS << FD << '('; 737 if (FT) { 738 unsigned NumParams = FD->getNumParams(); 739 for (unsigned i = 0; i < NumParams; ++i) { 740 if (i) 741 OS << ", "; 742 std::string Param; 743 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P); 744 OS << Param; 745 } 746 747 if (FT->isVariadic()) { 748 if (NumParams > 0) 749 OS << ", "; 750 OS << "..."; 751 } 752 } 753 OS << ')'; 754 } else { 755 OS << cast<NamedDecl>(*I); 756 } 757 OS << "::"; 758 } 759 760 if (getDeclName()) 761 OS << this; 762 else 763 OS << "<anonymous>"; 764 765 return OS.str(); 766} 767 768bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 769 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 770 771 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 772 // We want to keep it, unless it nominates same namespace. 773 if (getKind() == Decl::UsingDirective) { 774 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() == 775 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace(); 776 } 777 778 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 779 // For function declarations, we keep track of redeclarations. 780 return FD->getPreviousDeclaration() == OldD; 781 782 // For function templates, the underlying function declarations are linked. 783 if (const FunctionTemplateDecl *FunctionTemplate 784 = dyn_cast<FunctionTemplateDecl>(this)) 785 if (const FunctionTemplateDecl *OldFunctionTemplate 786 = dyn_cast<FunctionTemplateDecl>(OldD)) 787 return FunctionTemplate->getTemplatedDecl() 788 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 789 790 // For method declarations, we keep track of redeclarations. 791 if (isa<ObjCMethodDecl>(this)) 792 return false; 793 794 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 795 return true; 796 797 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 798 return cast<UsingShadowDecl>(this)->getTargetDecl() == 799 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 800 801 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) 802 return cast<UsingDecl>(this)->getTargetNestedNameDecl() == 803 cast<UsingDecl>(OldD)->getTargetNestedNameDecl(); 804 805 // For non-function declarations, if the declarations are of the 806 // same kind then this must be a redeclaration, or semantic analysis 807 // would not have given us the new declaration. 808 return this->getKind() == OldD->getKind(); 809} 810 811bool NamedDecl::hasLinkage() const { 812 return getLinkage() != NoLinkage; 813} 814 815NamedDecl *NamedDecl::getUnderlyingDecl() { 816 NamedDecl *ND = this; 817 while (true) { 818 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 819 ND = UD->getTargetDecl(); 820 else if (ObjCCompatibleAliasDecl *AD 821 = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 822 return AD->getClassInterface(); 823 else 824 return ND; 825 } 826} 827 828bool NamedDecl::isCXXInstanceMember() const { 829 assert(isCXXClassMember() && 830 "checking whether non-member is instance member"); 831 832 const NamedDecl *D = this; 833 if (isa<UsingShadowDecl>(D)) 834 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 835 836 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 837 return true; 838 if (isa<CXXMethodDecl>(D)) 839 return cast<CXXMethodDecl>(D)->isInstance(); 840 if (isa<FunctionTemplateDecl>(D)) 841 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 842 ->getTemplatedDecl())->isInstance(); 843 return false; 844} 845 846//===----------------------------------------------------------------------===// 847// DeclaratorDecl Implementation 848//===----------------------------------------------------------------------===// 849 850template <typename DeclT> 851static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 852 if (decl->getNumTemplateParameterLists() > 0) 853 return decl->getTemplateParameterList(0)->getTemplateLoc(); 854 else 855 return decl->getInnerLocStart(); 856} 857 858SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 859 TypeSourceInfo *TSI = getTypeSourceInfo(); 860 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 861 return SourceLocation(); 862} 863 864void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 865 SourceRange QualifierRange) { 866 if (Qualifier) { 867 // Make sure the extended decl info is allocated. 868 if (!hasExtInfo()) { 869 // Save (non-extended) type source info pointer. 870 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 871 // Allocate external info struct. 872 DeclInfo = new (getASTContext()) ExtInfo; 873 // Restore savedTInfo into (extended) decl info. 874 getExtInfo()->TInfo = savedTInfo; 875 } 876 // Set qualifier info. 877 getExtInfo()->NNS = Qualifier; 878 getExtInfo()->NNSRange = QualifierRange; 879 } 880 else { 881 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 882 assert(QualifierRange.isInvalid()); 883 if (hasExtInfo()) { 884 // Save type source info pointer. 885 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 886 // Deallocate the extended decl info. 887 getASTContext().Deallocate(getExtInfo()); 888 // Restore savedTInfo into (non-extended) decl info. 889 DeclInfo = savedTInfo; 890 } 891 } 892} 893 894SourceLocation DeclaratorDecl::getOuterLocStart() const { 895 return getTemplateOrInnerLocStart(this); 896} 897 898void 899QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 900 unsigned NumTPLists, 901 TemplateParameterList **TPLists) { 902 assert((NumTPLists == 0 || TPLists != 0) && 903 "Empty array of template parameters with positive size!"); 904 assert((NumTPLists == 0 || NNS) && 905 "Nonempty array of template parameters with no qualifier!"); 906 907 // Free previous template parameters (if any). 908 if (NumTemplParamLists > 0) { 909 Context.Deallocate(TemplParamLists); 910 TemplParamLists = 0; 911 NumTemplParamLists = 0; 912 } 913 // Set info on matched template parameter lists (if any). 914 if (NumTPLists > 0) { 915 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 916 NumTemplParamLists = NumTPLists; 917 for (unsigned i = NumTPLists; i-- > 0; ) 918 TemplParamLists[i] = TPLists[i]; 919 } 920} 921 922//===----------------------------------------------------------------------===// 923// VarDecl Implementation 924//===----------------------------------------------------------------------===// 925 926const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 927 switch (SC) { 928 case SC_None: break; 929 case SC_Auto: return "auto"; break; 930 case SC_Extern: return "extern"; break; 931 case SC_PrivateExtern: return "__private_extern__"; break; 932 case SC_Register: return "register"; break; 933 case SC_Static: return "static"; break; 934 } 935 936 assert(0 && "Invalid storage class"); 937 return 0; 938} 939 940VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 941 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 942 StorageClass S, StorageClass SCAsWritten) { 943 return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten); 944} 945 946void VarDecl::setStorageClass(StorageClass SC) { 947 assert(isLegalForVariable(SC)); 948 if (getStorageClass() != SC) 949 ClearLinkageCache(); 950 951 SClass = SC; 952} 953 954SourceLocation VarDecl::getInnerLocStart() const { 955 SourceLocation Start = getTypeSpecStartLoc(); 956 if (Start.isInvalid()) 957 Start = getLocation(); 958 return Start; 959} 960 961SourceRange VarDecl::getSourceRange() const { 962 if (getInit()) 963 return SourceRange(getOuterLocStart(), getInit()->getLocEnd()); 964 return SourceRange(getOuterLocStart(), getLocation()); 965} 966 967bool VarDecl::isExternC() const { 968 ASTContext &Context = getASTContext(); 969 if (!Context.getLangOptions().CPlusPlus) 970 return (getDeclContext()->isTranslationUnit() && 971 getStorageClass() != SC_Static) || 972 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); 973 974 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 975 DC = DC->getParent()) { 976 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 977 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 978 return getStorageClass() != SC_Static; 979 980 break; 981 } 982 983 if (DC->isFunctionOrMethod()) 984 return false; 985 } 986 987 return false; 988} 989 990VarDecl *VarDecl::getCanonicalDecl() { 991 return getFirstDeclaration(); 992} 993 994VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const { 995 // C++ [basic.def]p2: 996 // A declaration is a definition unless [...] it contains the 'extern' 997 // specifier or a linkage-specification and neither an initializer [...], 998 // it declares a static data member in a class declaration [...]. 999 // C++ [temp.expl.spec]p15: 1000 // An explicit specialization of a static data member of a template is a 1001 // definition if the declaration includes an initializer; otherwise, it is 1002 // a declaration. 1003 if (isStaticDataMember()) { 1004 if (isOutOfLine() && (hasInit() || 1005 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 1006 return Definition; 1007 else 1008 return DeclarationOnly; 1009 } 1010 // C99 6.7p5: 1011 // A definition of an identifier is a declaration for that identifier that 1012 // [...] causes storage to be reserved for that object. 1013 // Note: that applies for all non-file-scope objects. 1014 // C99 6.9.2p1: 1015 // If the declaration of an identifier for an object has file scope and an 1016 // initializer, the declaration is an external definition for the identifier 1017 if (hasInit()) 1018 return Definition; 1019 // AST for 'extern "C" int foo;' is annotated with 'extern'. 1020 if (hasExternalStorage()) 1021 return DeclarationOnly; 1022 1023 if (getStorageClassAsWritten() == SC_Extern || 1024 getStorageClassAsWritten() == SC_PrivateExtern) { 1025 for (const VarDecl *PrevVar = getPreviousDeclaration(); 1026 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) { 1027 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit()) 1028 return DeclarationOnly; 1029 } 1030 } 1031 // C99 6.9.2p2: 1032 // A declaration of an object that has file scope without an initializer, 1033 // and without a storage class specifier or the scs 'static', constitutes 1034 // a tentative definition. 1035 // No such thing in C++. 1036 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl()) 1037 return TentativeDefinition; 1038 1039 // What's left is (in C, block-scope) declarations without initializers or 1040 // external storage. These are definitions. 1041 return Definition; 1042} 1043 1044VarDecl *VarDecl::getActingDefinition() { 1045 DefinitionKind Kind = isThisDeclarationADefinition(); 1046 if (Kind != TentativeDefinition) 1047 return 0; 1048 1049 VarDecl *LastTentative = 0; 1050 VarDecl *First = getFirstDeclaration(); 1051 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1052 I != E; ++I) { 1053 Kind = (*I)->isThisDeclarationADefinition(); 1054 if (Kind == Definition) 1055 return 0; 1056 else if (Kind == TentativeDefinition) 1057 LastTentative = *I; 1058 } 1059 return LastTentative; 1060} 1061 1062bool VarDecl::isTentativeDefinitionNow() const { 1063 DefinitionKind Kind = isThisDeclarationADefinition(); 1064 if (Kind != TentativeDefinition) 1065 return false; 1066 1067 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1068 if ((*I)->isThisDeclarationADefinition() == Definition) 1069 return false; 1070 } 1071 return true; 1072} 1073 1074VarDecl *VarDecl::getDefinition() { 1075 VarDecl *First = getFirstDeclaration(); 1076 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1077 I != E; ++I) { 1078 if ((*I)->isThisDeclarationADefinition() == Definition) 1079 return *I; 1080 } 1081 return 0; 1082} 1083 1084VarDecl::DefinitionKind VarDecl::hasDefinition() const { 1085 DefinitionKind Kind = DeclarationOnly; 1086 1087 const VarDecl *First = getFirstDeclaration(); 1088 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1089 I != E; ++I) 1090 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition()); 1091 1092 return Kind; 1093} 1094 1095const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 1096 redecl_iterator I = redecls_begin(), E = redecls_end(); 1097 while (I != E && !I->getInit()) 1098 ++I; 1099 1100 if (I != E) { 1101 D = *I; 1102 return I->getInit(); 1103 } 1104 return 0; 1105} 1106 1107bool VarDecl::isOutOfLine() const { 1108 if (Decl::isOutOfLine()) 1109 return true; 1110 1111 if (!isStaticDataMember()) 1112 return false; 1113 1114 // If this static data member was instantiated from a static data member of 1115 // a class template, check whether that static data member was defined 1116 // out-of-line. 1117 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 1118 return VD->isOutOfLine(); 1119 1120 return false; 1121} 1122 1123VarDecl *VarDecl::getOutOfLineDefinition() { 1124 if (!isStaticDataMember()) 1125 return 0; 1126 1127 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 1128 RD != RDEnd; ++RD) { 1129 if (RD->getLexicalDeclContext()->isFileContext()) 1130 return *RD; 1131 } 1132 1133 return 0; 1134} 1135 1136void VarDecl::setInit(Expr *I) { 1137 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 1138 Eval->~EvaluatedStmt(); 1139 getASTContext().Deallocate(Eval); 1140 } 1141 1142 Init = I; 1143} 1144 1145VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 1146 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1147 return cast<VarDecl>(MSI->getInstantiatedFrom()); 1148 1149 return 0; 1150} 1151 1152TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 1153 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1154 return MSI->getTemplateSpecializationKind(); 1155 1156 return TSK_Undeclared; 1157} 1158 1159MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 1160 return getASTContext().getInstantiatedFromStaticDataMember(this); 1161} 1162 1163void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1164 SourceLocation PointOfInstantiation) { 1165 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 1166 assert(MSI && "Not an instantiated static data member?"); 1167 MSI->setTemplateSpecializationKind(TSK); 1168 if (TSK != TSK_ExplicitSpecialization && 1169 PointOfInstantiation.isValid() && 1170 MSI->getPointOfInstantiation().isInvalid()) 1171 MSI->setPointOfInstantiation(PointOfInstantiation); 1172} 1173 1174//===----------------------------------------------------------------------===// 1175// ParmVarDecl Implementation 1176//===----------------------------------------------------------------------===// 1177 1178ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 1179 SourceLocation L, IdentifierInfo *Id, 1180 QualType T, TypeSourceInfo *TInfo, 1181 StorageClass S, StorageClass SCAsWritten, 1182 Expr *DefArg) { 1183 return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo, 1184 S, SCAsWritten, DefArg); 1185} 1186 1187Expr *ParmVarDecl::getDefaultArg() { 1188 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 1189 assert(!hasUninstantiatedDefaultArg() && 1190 "Default argument is not yet instantiated!"); 1191 1192 Expr *Arg = getInit(); 1193 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 1194 return E->getSubExpr(); 1195 1196 return Arg; 1197} 1198 1199unsigned ParmVarDecl::getNumDefaultArgTemporaries() const { 1200 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit())) 1201 return E->getNumTemporaries(); 1202 1203 return 0; 1204} 1205 1206CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) { 1207 assert(getNumDefaultArgTemporaries() && 1208 "Default arguments does not have any temporaries!"); 1209 1210 ExprWithCleanups *E = cast<ExprWithCleanups>(getInit()); 1211 return E->getTemporary(i); 1212} 1213 1214SourceRange ParmVarDecl::getDefaultArgRange() const { 1215 if (const Expr *E = getInit()) 1216 return E->getSourceRange(); 1217 1218 if (hasUninstantiatedDefaultArg()) 1219 return getUninstantiatedDefaultArg()->getSourceRange(); 1220 1221 return SourceRange(); 1222} 1223 1224bool ParmVarDecl::isParameterPack() const { 1225 return isa<PackExpansionType>(getType()); 1226} 1227 1228//===----------------------------------------------------------------------===// 1229// FunctionDecl Implementation 1230//===----------------------------------------------------------------------===// 1231 1232void FunctionDecl::getNameForDiagnostic(std::string &S, 1233 const PrintingPolicy &Policy, 1234 bool Qualified) const { 1235 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 1236 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 1237 if (TemplateArgs) 1238 S += TemplateSpecializationType::PrintTemplateArgumentList( 1239 TemplateArgs->data(), 1240 TemplateArgs->size(), 1241 Policy); 1242 1243} 1244 1245bool FunctionDecl::isVariadic() const { 1246 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 1247 return FT->isVariadic(); 1248 return false; 1249} 1250 1251bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 1252 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1253 if (I->Body) { 1254 Definition = *I; 1255 return true; 1256 } 1257 } 1258 1259 return false; 1260} 1261 1262Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 1263 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1264 if (I->Body) { 1265 Definition = *I; 1266 return I->Body.get(getASTContext().getExternalSource()); 1267 } 1268 } 1269 1270 return 0; 1271} 1272 1273void FunctionDecl::setBody(Stmt *B) { 1274 Body = B; 1275 if (B) 1276 EndRangeLoc = B->getLocEnd(); 1277} 1278 1279void FunctionDecl::setPure(bool P) { 1280 IsPure = P; 1281 if (P) 1282 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 1283 Parent->markedVirtualFunctionPure(); 1284} 1285 1286bool FunctionDecl::isMain() const { 1287 ASTContext &Context = getASTContext(); 1288 return !Context.getLangOptions().Freestanding && 1289 getDeclContext()->getRedeclContext()->isTranslationUnit() && 1290 getIdentifier() && getIdentifier()->isStr("main"); 1291} 1292 1293bool FunctionDecl::isExternC() const { 1294 ASTContext &Context = getASTContext(); 1295 // In C, any non-static, non-overloadable function has external 1296 // linkage. 1297 if (!Context.getLangOptions().CPlusPlus) 1298 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>(); 1299 1300 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 1301 DC = DC->getParent()) { 1302 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 1303 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 1304 return getStorageClass() != SC_Static && 1305 !getAttr<OverloadableAttr>(); 1306 1307 break; 1308 } 1309 1310 if (DC->isRecord()) 1311 break; 1312 } 1313 1314 return isMain(); 1315} 1316 1317bool FunctionDecl::isGlobal() const { 1318 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 1319 return Method->isStatic(); 1320 1321 if (getStorageClass() == SC_Static) 1322 return false; 1323 1324 for (const DeclContext *DC = getDeclContext(); 1325 DC->isNamespace(); 1326 DC = DC->getParent()) { 1327 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 1328 if (!Namespace->getDeclName()) 1329 return false; 1330 break; 1331 } 1332 } 1333 1334 return true; 1335} 1336 1337void 1338FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 1339 redeclarable_base::setPreviousDeclaration(PrevDecl); 1340 1341 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 1342 FunctionTemplateDecl *PrevFunTmpl 1343 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 1344 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 1345 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 1346 } 1347 1348 if (PrevDecl->IsInline) 1349 IsInline = true; 1350} 1351 1352const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 1353 return getFirstDeclaration(); 1354} 1355 1356FunctionDecl *FunctionDecl::getCanonicalDecl() { 1357 return getFirstDeclaration(); 1358} 1359 1360void FunctionDecl::setStorageClass(StorageClass SC) { 1361 assert(isLegalForFunction(SC)); 1362 if (getStorageClass() != SC) 1363 ClearLinkageCache(); 1364 1365 SClass = SC; 1366} 1367 1368/// \brief Returns a value indicating whether this function 1369/// corresponds to a builtin function. 1370/// 1371/// The function corresponds to a built-in function if it is 1372/// declared at translation scope or within an extern "C" block and 1373/// its name matches with the name of a builtin. The returned value 1374/// will be 0 for functions that do not correspond to a builtin, a 1375/// value of type \c Builtin::ID if in the target-independent range 1376/// \c [1,Builtin::First), or a target-specific builtin value. 1377unsigned FunctionDecl::getBuiltinID() const { 1378 ASTContext &Context = getASTContext(); 1379 if (!getIdentifier() || !getIdentifier()->getBuiltinID()) 1380 return 0; 1381 1382 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1383 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1384 return BuiltinID; 1385 1386 // This function has the name of a known C library 1387 // function. Determine whether it actually refers to the C library 1388 // function or whether it just has the same name. 1389 1390 // If this is a static function, it's not a builtin. 1391 if (getStorageClass() == SC_Static) 1392 return 0; 1393 1394 // If this function is at translation-unit scope and we're not in 1395 // C++, it refers to the C library function. 1396 if (!Context.getLangOptions().CPlusPlus && 1397 getDeclContext()->isTranslationUnit()) 1398 return BuiltinID; 1399 1400 // If the function is in an extern "C" linkage specification and is 1401 // not marked "overloadable", it's the real function. 1402 if (isa<LinkageSpecDecl>(getDeclContext()) && 1403 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1404 == LinkageSpecDecl::lang_c && 1405 !getAttr<OverloadableAttr>()) 1406 return BuiltinID; 1407 1408 // Not a builtin 1409 return 0; 1410} 1411 1412 1413/// getNumParams - Return the number of parameters this function must have 1414/// based on its FunctionType. This is the length of the ParamInfo array 1415/// after it has been created. 1416unsigned FunctionDecl::getNumParams() const { 1417 const FunctionType *FT = getType()->getAs<FunctionType>(); 1418 if (isa<FunctionNoProtoType>(FT)) 1419 return 0; 1420 return cast<FunctionProtoType>(FT)->getNumArgs(); 1421 1422} 1423 1424void FunctionDecl::setParams(ASTContext &C, 1425 ParmVarDecl **NewParamInfo, unsigned NumParams) { 1426 assert(ParamInfo == 0 && "Already has param info!"); 1427 assert(NumParams == getNumParams() && "Parameter count mismatch!"); 1428 1429 // Zero params -> null pointer. 1430 if (NumParams) { 1431 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); 1432 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1433 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1434 1435 // Update source range. The check below allows us to set EndRangeLoc before 1436 // setting the parameters. 1437 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation()) 1438 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd(); 1439 } 1440} 1441 1442/// getMinRequiredArguments - Returns the minimum number of arguments 1443/// needed to call this function. This may be fewer than the number of 1444/// function parameters, if some of the parameters have default 1445/// arguments (in C++) or the last parameter is a parameter pack. 1446unsigned FunctionDecl::getMinRequiredArguments() const { 1447 if (!getASTContext().getLangOptions().CPlusPlus) 1448 return getNumParams(); 1449 1450 unsigned NumRequiredArgs = getNumParams(); 1451 1452 // If the last parameter is a parameter pack, we don't need an argument for 1453 // it. 1454 if (NumRequiredArgs > 0 && 1455 getParamDecl(NumRequiredArgs - 1)->isParameterPack()) 1456 --NumRequiredArgs; 1457 1458 // If this parameter has a default argument, we don't need an argument for 1459 // it. 1460 while (NumRequiredArgs > 0 && 1461 getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1462 --NumRequiredArgs; 1463 1464 // We might have parameter packs before the end. These can't be deduced, 1465 // but they can still handle multiple arguments. 1466 unsigned ArgIdx = NumRequiredArgs; 1467 while (ArgIdx > 0) { 1468 if (getParamDecl(ArgIdx - 1)->isParameterPack()) 1469 NumRequiredArgs = ArgIdx; 1470 1471 --ArgIdx; 1472 } 1473 1474 return NumRequiredArgs; 1475} 1476 1477bool FunctionDecl::isInlined() const { 1478 if (IsInline) 1479 return true; 1480 1481 if (isa<CXXMethodDecl>(this)) { 1482 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1483 return true; 1484 } 1485 1486 switch (getTemplateSpecializationKind()) { 1487 case TSK_Undeclared: 1488 case TSK_ExplicitSpecialization: 1489 return false; 1490 1491 case TSK_ImplicitInstantiation: 1492 case TSK_ExplicitInstantiationDeclaration: 1493 case TSK_ExplicitInstantiationDefinition: 1494 // Handle below. 1495 break; 1496 } 1497 1498 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1499 bool HasPattern = false; 1500 if (PatternDecl) 1501 HasPattern = PatternDecl->hasBody(PatternDecl); 1502 1503 if (HasPattern && PatternDecl) 1504 return PatternDecl->isInlined(); 1505 1506 return false; 1507} 1508 1509/// \brief For an inline function definition in C or C++, determine whether the 1510/// definition will be externally visible. 1511/// 1512/// Inline function definitions are always available for inlining optimizations. 1513/// However, depending on the language dialect, declaration specifiers, and 1514/// attributes, the definition of an inline function may or may not be 1515/// "externally" visible to other translation units in the program. 1516/// 1517/// In C99, inline definitions are not externally visible by default. However, 1518/// if even one of the global-scope declarations is marked "extern inline", the 1519/// inline definition becomes externally visible (C99 6.7.4p6). 1520/// 1521/// In GNU89 mode, or if the gnu_inline attribute is attached to the function 1522/// definition, we use the GNU semantics for inline, which are nearly the 1523/// opposite of C99 semantics. In particular, "inline" by itself will create 1524/// an externally visible symbol, but "extern inline" will not create an 1525/// externally visible symbol. 1526bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 1527 assert(isThisDeclarationADefinition() && "Must have the function definition"); 1528 assert(isInlined() && "Function must be inline"); 1529 ASTContext &Context = getASTContext(); 1530 1531 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) { 1532 // If it's not the case that both 'inline' and 'extern' are 1533 // specified on the definition, then this inline definition is 1534 // externally visible. 1535 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern)) 1536 return true; 1537 1538 // If any declaration is 'inline' but not 'extern', then this definition 1539 // is externally visible. 1540 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1541 Redecl != RedeclEnd; 1542 ++Redecl) { 1543 if (Redecl->isInlineSpecified() && 1544 Redecl->getStorageClassAsWritten() != SC_Extern) 1545 return true; 1546 } 1547 1548 return false; 1549 } 1550 1551 // C99 6.7.4p6: 1552 // [...] If all of the file scope declarations for a function in a 1553 // translation unit include the inline function specifier without extern, 1554 // then the definition in that translation unit is an inline definition. 1555 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1556 Redecl != RedeclEnd; 1557 ++Redecl) { 1558 // Only consider file-scope declarations in this test. 1559 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1560 continue; 1561 1562 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 1563 return true; // Not an inline definition 1564 } 1565 1566 // C99 6.7.4p6: 1567 // An inline definition does not provide an external definition for the 1568 // function, and does not forbid an external definition in another 1569 // translation unit. 1570 return false; 1571} 1572 1573/// getOverloadedOperator - Which C++ overloaded operator this 1574/// function represents, if any. 1575OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 1576 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 1577 return getDeclName().getCXXOverloadedOperator(); 1578 else 1579 return OO_None; 1580} 1581 1582/// getLiteralIdentifier - The literal suffix identifier this function 1583/// represents, if any. 1584const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 1585 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 1586 return getDeclName().getCXXLiteralIdentifier(); 1587 else 1588 return 0; 1589} 1590 1591FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 1592 if (TemplateOrSpecialization.isNull()) 1593 return TK_NonTemplate; 1594 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 1595 return TK_FunctionTemplate; 1596 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 1597 return TK_MemberSpecialization; 1598 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 1599 return TK_FunctionTemplateSpecialization; 1600 if (TemplateOrSpecialization.is 1601 <DependentFunctionTemplateSpecializationInfo*>()) 1602 return TK_DependentFunctionTemplateSpecialization; 1603 1604 assert(false && "Did we miss a TemplateOrSpecialization type?"); 1605 return TK_NonTemplate; 1606} 1607 1608FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 1609 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 1610 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 1611 1612 return 0; 1613} 1614 1615MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 1616 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1617} 1618 1619void 1620FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 1621 FunctionDecl *FD, 1622 TemplateSpecializationKind TSK) { 1623 assert(TemplateOrSpecialization.isNull() && 1624 "Member function is already a specialization"); 1625 MemberSpecializationInfo *Info 1626 = new (C) MemberSpecializationInfo(FD, TSK); 1627 TemplateOrSpecialization = Info; 1628} 1629 1630bool FunctionDecl::isImplicitlyInstantiable() const { 1631 // If the function is invalid, it can't be implicitly instantiated. 1632 if (isInvalidDecl()) 1633 return false; 1634 1635 switch (getTemplateSpecializationKind()) { 1636 case TSK_Undeclared: 1637 case TSK_ExplicitSpecialization: 1638 case TSK_ExplicitInstantiationDefinition: 1639 return false; 1640 1641 case TSK_ImplicitInstantiation: 1642 return true; 1643 1644 case TSK_ExplicitInstantiationDeclaration: 1645 // Handled below. 1646 break; 1647 } 1648 1649 // Find the actual template from which we will instantiate. 1650 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1651 bool HasPattern = false; 1652 if (PatternDecl) 1653 HasPattern = PatternDecl->hasBody(PatternDecl); 1654 1655 // C++0x [temp.explicit]p9: 1656 // Except for inline functions, other explicit instantiation declarations 1657 // have the effect of suppressing the implicit instantiation of the entity 1658 // to which they refer. 1659 if (!HasPattern || !PatternDecl) 1660 return true; 1661 1662 return PatternDecl->isInlined(); 1663} 1664 1665FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 1666 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 1667 while (Primary->getInstantiatedFromMemberTemplate()) { 1668 // If we have hit a point where the user provided a specialization of 1669 // this template, we're done looking. 1670 if (Primary->isMemberSpecialization()) 1671 break; 1672 1673 Primary = Primary->getInstantiatedFromMemberTemplate(); 1674 } 1675 1676 return Primary->getTemplatedDecl(); 1677 } 1678 1679 return getInstantiatedFromMemberFunction(); 1680} 1681 1682FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 1683 if (FunctionTemplateSpecializationInfo *Info 1684 = TemplateOrSpecialization 1685 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1686 return Info->Template.getPointer(); 1687 } 1688 return 0; 1689} 1690 1691const TemplateArgumentList * 1692FunctionDecl::getTemplateSpecializationArgs() const { 1693 if (FunctionTemplateSpecializationInfo *Info 1694 = TemplateOrSpecialization 1695 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1696 return Info->TemplateArguments; 1697 } 1698 return 0; 1699} 1700 1701const TemplateArgumentListInfo * 1702FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 1703 if (FunctionTemplateSpecializationInfo *Info 1704 = TemplateOrSpecialization 1705 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1706 return Info->TemplateArgumentsAsWritten; 1707 } 1708 return 0; 1709} 1710 1711void 1712FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 1713 FunctionTemplateDecl *Template, 1714 const TemplateArgumentList *TemplateArgs, 1715 void *InsertPos, 1716 TemplateSpecializationKind TSK, 1717 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1718 SourceLocation PointOfInstantiation) { 1719 assert(TSK != TSK_Undeclared && 1720 "Must specify the type of function template specialization"); 1721 FunctionTemplateSpecializationInfo *Info 1722 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1723 if (!Info) 1724 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 1725 TemplateArgs, 1726 TemplateArgsAsWritten, 1727 PointOfInstantiation); 1728 TemplateOrSpecialization = Info; 1729 1730 // Insert this function template specialization into the set of known 1731 // function template specializations. 1732 if (InsertPos) 1733 Template->getSpecializations().InsertNode(Info, InsertPos); 1734 else { 1735 // Try to insert the new node. If there is an existing node, leave it, the 1736 // set will contain the canonical decls while 1737 // FunctionTemplateDecl::findSpecialization will return 1738 // the most recent redeclarations. 1739 FunctionTemplateSpecializationInfo *Existing 1740 = Template->getSpecializations().GetOrInsertNode(Info); 1741 (void)Existing; 1742 assert((!Existing || Existing->Function->isCanonicalDecl()) && 1743 "Set is supposed to only contain canonical decls"); 1744 } 1745} 1746 1747void 1748FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 1749 const UnresolvedSetImpl &Templates, 1750 const TemplateArgumentListInfo &TemplateArgs) { 1751 assert(TemplateOrSpecialization.isNull()); 1752 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 1753 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 1754 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 1755 void *Buffer = Context.Allocate(Size); 1756 DependentFunctionTemplateSpecializationInfo *Info = 1757 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 1758 TemplateArgs); 1759 TemplateOrSpecialization = Info; 1760} 1761 1762DependentFunctionTemplateSpecializationInfo:: 1763DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 1764 const TemplateArgumentListInfo &TArgs) 1765 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 1766 1767 d.NumTemplates = Ts.size(); 1768 d.NumArgs = TArgs.size(); 1769 1770 FunctionTemplateDecl **TsArray = 1771 const_cast<FunctionTemplateDecl**>(getTemplates()); 1772 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 1773 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 1774 1775 TemplateArgumentLoc *ArgsArray = 1776 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 1777 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 1778 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 1779} 1780 1781TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 1782 // For a function template specialization, query the specialization 1783 // information object. 1784 FunctionTemplateSpecializationInfo *FTSInfo 1785 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1786 if (FTSInfo) 1787 return FTSInfo->getTemplateSpecializationKind(); 1788 1789 MemberSpecializationInfo *MSInfo 1790 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1791 if (MSInfo) 1792 return MSInfo->getTemplateSpecializationKind(); 1793 1794 return TSK_Undeclared; 1795} 1796 1797void 1798FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1799 SourceLocation PointOfInstantiation) { 1800 if (FunctionTemplateSpecializationInfo *FTSInfo 1801 = TemplateOrSpecialization.dyn_cast< 1802 FunctionTemplateSpecializationInfo*>()) { 1803 FTSInfo->setTemplateSpecializationKind(TSK); 1804 if (TSK != TSK_ExplicitSpecialization && 1805 PointOfInstantiation.isValid() && 1806 FTSInfo->getPointOfInstantiation().isInvalid()) 1807 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 1808 } else if (MemberSpecializationInfo *MSInfo 1809 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 1810 MSInfo->setTemplateSpecializationKind(TSK); 1811 if (TSK != TSK_ExplicitSpecialization && 1812 PointOfInstantiation.isValid() && 1813 MSInfo->getPointOfInstantiation().isInvalid()) 1814 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1815 } else 1816 assert(false && "Function cannot have a template specialization kind"); 1817} 1818 1819SourceLocation FunctionDecl::getPointOfInstantiation() const { 1820 if (FunctionTemplateSpecializationInfo *FTSInfo 1821 = TemplateOrSpecialization.dyn_cast< 1822 FunctionTemplateSpecializationInfo*>()) 1823 return FTSInfo->getPointOfInstantiation(); 1824 else if (MemberSpecializationInfo *MSInfo 1825 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 1826 return MSInfo->getPointOfInstantiation(); 1827 1828 return SourceLocation(); 1829} 1830 1831bool FunctionDecl::isOutOfLine() const { 1832 if (Decl::isOutOfLine()) 1833 return true; 1834 1835 // If this function was instantiated from a member function of a 1836 // class template, check whether that member function was defined out-of-line. 1837 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 1838 const FunctionDecl *Definition; 1839 if (FD->hasBody(Definition)) 1840 return Definition->isOutOfLine(); 1841 } 1842 1843 // If this function was instantiated from a function template, 1844 // check whether that function template was defined out-of-line. 1845 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 1846 const FunctionDecl *Definition; 1847 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 1848 return Definition->isOutOfLine(); 1849 } 1850 1851 return false; 1852} 1853 1854//===----------------------------------------------------------------------===// 1855// FieldDecl Implementation 1856//===----------------------------------------------------------------------===// 1857 1858FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 1859 SourceLocation L, IdentifierInfo *Id, QualType T, 1860 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) { 1861 return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable); 1862} 1863 1864bool FieldDecl::isAnonymousStructOrUnion() const { 1865 if (!isImplicit() || getDeclName()) 1866 return false; 1867 1868 if (const RecordType *Record = getType()->getAs<RecordType>()) 1869 return Record->getDecl()->isAnonymousStructOrUnion(); 1870 1871 return false; 1872} 1873 1874//===----------------------------------------------------------------------===// 1875// TagDecl Implementation 1876//===----------------------------------------------------------------------===// 1877 1878SourceLocation TagDecl::getOuterLocStart() const { 1879 return getTemplateOrInnerLocStart(this); 1880} 1881 1882SourceRange TagDecl::getSourceRange() const { 1883 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 1884 return SourceRange(getOuterLocStart(), E); 1885} 1886 1887TagDecl* TagDecl::getCanonicalDecl() { 1888 return getFirstDeclaration(); 1889} 1890 1891void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) { 1892 TypedefDeclOrQualifier = TDD; 1893 if (TypeForDecl) 1894 TypeForDecl->ClearLinkageCache(); 1895 ClearLinkageCache(); 1896} 1897 1898void TagDecl::startDefinition() { 1899 IsBeingDefined = true; 1900 1901 if (isa<CXXRecordDecl>(this)) { 1902 CXXRecordDecl *D = cast<CXXRecordDecl>(this); 1903 struct CXXRecordDecl::DefinitionData *Data = 1904 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 1905 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 1906 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 1907 } 1908} 1909 1910void TagDecl::completeDefinition() { 1911 assert((!isa<CXXRecordDecl>(this) || 1912 cast<CXXRecordDecl>(this)->hasDefinition()) && 1913 "definition completed but not started"); 1914 1915 IsDefinition = true; 1916 IsBeingDefined = false; 1917 1918 if (ASTMutationListener *L = getASTMutationListener()) 1919 L->CompletedTagDefinition(this); 1920} 1921 1922TagDecl* TagDecl::getDefinition() const { 1923 if (isDefinition()) 1924 return const_cast<TagDecl *>(this); 1925 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 1926 return CXXRD->getDefinition(); 1927 1928 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 1929 R != REnd; ++R) 1930 if (R->isDefinition()) 1931 return *R; 1932 1933 return 0; 1934} 1935 1936void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 1937 SourceRange QualifierRange) { 1938 if (Qualifier) { 1939 // Make sure the extended qualifier info is allocated. 1940 if (!hasExtInfo()) 1941 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo; 1942 // Set qualifier info. 1943 getExtInfo()->NNS = Qualifier; 1944 getExtInfo()->NNSRange = QualifierRange; 1945 } 1946 else { 1947 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1948 assert(QualifierRange.isInvalid()); 1949 if (hasExtInfo()) { 1950 getASTContext().Deallocate(getExtInfo()); 1951 TypedefDeclOrQualifier = (TypedefDecl*) 0; 1952 } 1953 } 1954} 1955 1956//===----------------------------------------------------------------------===// 1957// EnumDecl Implementation 1958//===----------------------------------------------------------------------===// 1959 1960EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 1961 IdentifierInfo *Id, SourceLocation TKL, 1962 EnumDecl *PrevDecl, bool IsScoped, 1963 bool IsScopedUsingClassTag, bool IsFixed) { 1964 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL, 1965 IsScoped, IsScopedUsingClassTag, IsFixed); 1966 C.getTypeDeclType(Enum, PrevDecl); 1967 return Enum; 1968} 1969 1970EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) { 1971 return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation(), 1972 false, false, false); 1973} 1974 1975void EnumDecl::completeDefinition(QualType NewType, 1976 QualType NewPromotionType, 1977 unsigned NumPositiveBits, 1978 unsigned NumNegativeBits) { 1979 assert(!isDefinition() && "Cannot redefine enums!"); 1980 if (!IntegerType) 1981 IntegerType = NewType.getTypePtr(); 1982 PromotionType = NewPromotionType; 1983 setNumPositiveBits(NumPositiveBits); 1984 setNumNegativeBits(NumNegativeBits); 1985 TagDecl::completeDefinition(); 1986} 1987 1988//===----------------------------------------------------------------------===// 1989// RecordDecl Implementation 1990//===----------------------------------------------------------------------===// 1991 1992RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, 1993 IdentifierInfo *Id, RecordDecl *PrevDecl, 1994 SourceLocation TKL) 1995 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) { 1996 HasFlexibleArrayMember = false; 1997 AnonymousStructOrUnion = false; 1998 HasObjectMember = false; 1999 LoadedFieldsFromExternalStorage = false; 2000 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 2001} 2002 2003RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2004 SourceLocation L, IdentifierInfo *Id, 2005 SourceLocation TKL, RecordDecl* PrevDecl) { 2006 2007 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); 2008 C.getTypeDeclType(R, PrevDecl); 2009 return R; 2010} 2011 2012RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) { 2013 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0, 2014 SourceLocation()); 2015} 2016 2017bool RecordDecl::isInjectedClassName() const { 2018 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 2019 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 2020} 2021 2022RecordDecl::field_iterator RecordDecl::field_begin() const { 2023 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 2024 LoadFieldsFromExternalStorage(); 2025 2026 return field_iterator(decl_iterator(FirstDecl)); 2027} 2028 2029/// completeDefinition - Notes that the definition of this type is now 2030/// complete. 2031void RecordDecl::completeDefinition() { 2032 assert(!isDefinition() && "Cannot redefine record!"); 2033 TagDecl::completeDefinition(); 2034} 2035 2036void RecordDecl::LoadFieldsFromExternalStorage() const { 2037 ExternalASTSource *Source = getASTContext().getExternalSource(); 2038 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 2039 2040 // Notify that we have a RecordDecl doing some initialization. 2041 ExternalASTSource::Deserializing TheFields(Source); 2042 2043 llvm::SmallVector<Decl*, 64> Decls; 2044 if (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) 2045 return; 2046 2047#ifndef NDEBUG 2048 // Check that all decls we got were FieldDecls. 2049 for (unsigned i=0, e=Decls.size(); i != e; ++i) 2050 assert(isa<FieldDecl>(Decls[i])); 2051#endif 2052 2053 LoadedFieldsFromExternalStorage = true; 2054 2055 if (Decls.empty()) 2056 return; 2057 2058 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls); 2059} 2060 2061//===----------------------------------------------------------------------===// 2062// BlockDecl Implementation 2063//===----------------------------------------------------------------------===// 2064 2065void BlockDecl::setParams(ParmVarDecl **NewParamInfo, 2066 unsigned NParms) { 2067 assert(ParamInfo == 0 && "Already has param info!"); 2068 2069 // Zero params -> null pointer. 2070 if (NParms) { 2071 NumParams = NParms; 2072 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 2073 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 2074 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 2075 } 2076} 2077 2078unsigned BlockDecl::getNumParams() const { 2079 return NumParams; 2080} 2081 2082SourceRange BlockDecl::getSourceRange() const { 2083 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 2084} 2085 2086//===----------------------------------------------------------------------===// 2087// Other Decl Allocation/Deallocation Method Implementations 2088//===----------------------------------------------------------------------===// 2089 2090TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 2091 return new (C) TranslationUnitDecl(C); 2092} 2093 2094NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2095 SourceLocation L, IdentifierInfo *Id) { 2096 return new (C) NamespaceDecl(DC, L, Id); 2097} 2098 2099NamespaceDecl *NamespaceDecl::getNextNamespace() { 2100 return dyn_cast_or_null<NamespaceDecl>( 2101 NextNamespace.get(getASTContext().getExternalSource())); 2102} 2103 2104ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 2105 SourceLocation L, IdentifierInfo *Id, QualType T) { 2106 return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T); 2107} 2108 2109FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 2110 const DeclarationNameInfo &NameInfo, 2111 QualType T, TypeSourceInfo *TInfo, 2112 StorageClass S, StorageClass SCAsWritten, 2113 bool isInlineSpecified, 2114 bool hasWrittenPrototype) { 2115 FunctionDecl *New = new (C) FunctionDecl(Function, DC, NameInfo, T, TInfo, 2116 S, SCAsWritten, isInlineSpecified); 2117 New->HasWrittenPrototype = hasWrittenPrototype; 2118 return New; 2119} 2120 2121BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 2122 return new (C) BlockDecl(DC, L); 2123} 2124 2125EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 2126 SourceLocation L, 2127 IdentifierInfo *Id, QualType T, 2128 Expr *E, const llvm::APSInt &V) { 2129 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 2130} 2131 2132IndirectFieldDecl * 2133IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2134 IdentifierInfo *Id, QualType T, NamedDecl **CH, 2135 unsigned CHS) { 2136 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 2137} 2138 2139SourceRange EnumConstantDecl::getSourceRange() const { 2140 SourceLocation End = getLocation(); 2141 if (Init) 2142 End = Init->getLocEnd(); 2143 return SourceRange(getLocation(), End); 2144} 2145 2146TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 2147 SourceLocation L, IdentifierInfo *Id, 2148 TypeSourceInfo *TInfo) { 2149 return new (C) TypedefDecl(DC, L, Id, TInfo); 2150} 2151 2152FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 2153 SourceLocation L, 2154 StringLiteral *Str) { 2155 return new (C) FileScopeAsmDecl(DC, L, Str); 2156} 2157