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