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