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