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 "Linkage.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CanonicalType.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclOpenMP.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/DeclarationName.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExternalASTSource.h" 29 #include "clang/AST/PrettyPrinter.h" 30 #include "clang/AST/Redeclarable.h" 31 #include "clang/AST/Stmt.h" 32 #include "clang/AST/TemplateBase.h" 33 #include "clang/AST/Type.h" 34 #include "clang/AST/TypeLoc.h" 35 #include "clang/Basic/Builtins.h" 36 #include "clang/Basic/IdentifierTable.h" 37 #include "clang/Basic/LLVM.h" 38 #include "clang/Basic/LangOptions.h" 39 #include "clang/Basic/Linkage.h" 40 #include "clang/Basic/Module.h" 41 #include "clang/Basic/PartialDiagnostic.h" 42 #include "clang/Basic/SanitizerBlacklist.h" 43 #include "clang/Basic/Sanitizers.h" 44 #include "clang/Basic/SourceLocation.h" 45 #include "clang/Basic/SourceManager.h" 46 #include "clang/Basic/Specifiers.h" 47 #include "clang/Basic/TargetCXXABI.h" 48 #include "clang/Basic/TargetInfo.h" 49 #include "clang/Basic/Visibility.h" 50 #include "clang/Frontend/FrontendDiagnostic.h" 51 #include "llvm/ADT/APSInt.h" 52 #include "llvm/ADT/ArrayRef.h" 53 #include "llvm/ADT/None.h" 54 #include "llvm/ADT/Optional.h" 55 #include "llvm/ADT/STLExtras.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringSwitch.h" 58 #include "llvm/ADT/StringRef.h" 59 #include "llvm/ADT/Triple.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <algorithm> 64 #include <cassert> 65 #include <cstddef> 66 #include <cstring> 67 #include <memory> 68 #include <string> 69 #include <tuple> 70 #include <type_traits> 71 72 using namespace clang; 73 74 Decl *clang::getPrimaryMergedDecl(Decl *D) { 75 return D->getASTContext().getPrimaryMergedDecl(D); 76 } 77 78 // Defined here so that it can be inlined into its direct callers. 79 bool Decl::isOutOfLine() const { 80 return !getLexicalDeclContext()->Equals(getDeclContext()); 81 } 82 83 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx) 84 : Decl(TranslationUnit, nullptr, SourceLocation()), 85 DeclContext(TranslationUnit), Ctx(ctx) {} 86 87 //===----------------------------------------------------------------------===// 88 // NamedDecl Implementation 89 //===----------------------------------------------------------------------===// 90 91 // Visibility rules aren't rigorously externally specified, but here 92 // are the basic principles behind what we implement: 93 // 94 // 1. An explicit visibility attribute is generally a direct expression 95 // of the user's intent and should be honored. Only the innermost 96 // visibility attribute applies. If no visibility attribute applies, 97 // global visibility settings are considered. 98 // 99 // 2. There is one caveat to the above: on or in a template pattern, 100 // an explicit visibility attribute is just a default rule, and 101 // visibility can be decreased by the visibility of template 102 // arguments. But this, too, has an exception: an attribute on an 103 // explicit specialization or instantiation causes all the visibility 104 // restrictions of the template arguments to be ignored. 105 // 106 // 3. A variable that does not otherwise have explicit visibility can 107 // be restricted by the visibility of its type. 108 // 109 // 4. A visibility restriction is explicit if it comes from an 110 // attribute (or something like it), not a global visibility setting. 111 // When emitting a reference to an external symbol, visibility 112 // restrictions are ignored unless they are explicit. 113 // 114 // 5. When computing the visibility of a non-type, including a 115 // non-type member of a class, only non-type visibility restrictions 116 // are considered: the 'visibility' attribute, global value-visibility 117 // settings, and a few special cases like __private_extern. 118 // 119 // 6. When computing the visibility of a type, including a type member 120 // of a class, only type visibility restrictions are considered: 121 // the 'type_visibility' attribute and global type-visibility settings. 122 // However, a 'visibility' attribute counts as a 'type_visibility' 123 // attribute on any declaration that only has the former. 124 // 125 // The visibility of a "secondary" entity, like a template argument, 126 // is computed using the kind of that entity, not the kind of the 127 // primary entity for which we are computing visibility. For example, 128 // the visibility of a specialization of either of these templates: 129 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); 130 // template <class T, bool (&compare)(T, X)> class matcher; 131 // is restricted according to the type visibility of the argument 'T', 132 // the type visibility of 'bool(&)(T,X)', and the value visibility of 133 // the argument function 'compare'. That 'has_match' is a value 134 // and 'matcher' is a type only matters when looking for attributes 135 // and settings from the immediate context. 136 137 /// Does this computation kind permit us to consider additional 138 /// visibility settings from attributes and the like? 139 static bool hasExplicitVisibilityAlready(LVComputationKind computation) { 140 return computation.IgnoreExplicitVisibility; 141 } 142 143 /// Given an LVComputationKind, return one of the same type/value sort 144 /// that records that it already has explicit visibility. 145 static LVComputationKind 146 withExplicitVisibilityAlready(LVComputationKind Kind) { 147 Kind.IgnoreExplicitVisibility = true; 148 return Kind; 149 } 150 151 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D, 152 LVComputationKind kind) { 153 assert(!kind.IgnoreExplicitVisibility && 154 "asking for explicit visibility when we shouldn't be"); 155 return D->getExplicitVisibility(kind.getExplicitVisibilityKind()); 156 } 157 158 /// Is the given declaration a "type" or a "value" for the purposes of 159 /// visibility computation? 160 static bool usesTypeVisibility(const NamedDecl *D) { 161 return isa<TypeDecl>(D) || 162 isa<ClassTemplateDecl>(D) || 163 isa<ObjCInterfaceDecl>(D); 164 } 165 166 /// Does the given declaration have member specialization information, 167 /// and if so, is it an explicit specialization? 168 template <class T> static typename 169 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type 170 isExplicitMemberSpecialization(const T *D) { 171 if (const MemberSpecializationInfo *member = 172 D->getMemberSpecializationInfo()) { 173 return member->isExplicitSpecialization(); 174 } 175 return false; 176 } 177 178 /// For templates, this question is easier: a member template can't be 179 /// explicitly instantiated, so there's a single bit indicating whether 180 /// or not this is an explicit member specialization. 181 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { 182 return D->isMemberSpecialization(); 183 } 184 185 /// Given a visibility attribute, return the explicit visibility 186 /// associated with it. 187 template <class T> 188 static Visibility getVisibilityFromAttr(const T *attr) { 189 switch (attr->getVisibility()) { 190 case T::Default: 191 return DefaultVisibility; 192 case T::Hidden: 193 return HiddenVisibility; 194 case T::Protected: 195 return ProtectedVisibility; 196 } 197 llvm_unreachable("bad visibility kind"); 198 } 199 200 /// Return the explicit visibility of the given declaration. 201 static Optional<Visibility> getVisibilityOf(const NamedDecl *D, 202 NamedDecl::ExplicitVisibilityKind kind) { 203 // If we're ultimately computing the visibility of a type, look for 204 // a 'type_visibility' attribute before looking for 'visibility'. 205 if (kind == NamedDecl::VisibilityForType) { 206 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) { 207 return getVisibilityFromAttr(A); 208 } 209 } 210 211 // If this declaration has an explicit visibility attribute, use it. 212 if (const auto *A = D->getAttr<VisibilityAttr>()) { 213 return getVisibilityFromAttr(A); 214 } 215 216 return None; 217 } 218 219 LinkageInfo LinkageComputer::getLVForType(const Type &T, 220 LVComputationKind computation) { 221 if (computation.IgnoreAllVisibility) 222 return LinkageInfo(T.getLinkage(), DefaultVisibility, true); 223 return getTypeLinkageAndVisibility(&T); 224 } 225 226 /// \brief Get the most restrictive linkage for the types in the given 227 /// template parameter list. For visibility purposes, template 228 /// parameters are part of the signature of a template. 229 LinkageInfo LinkageComputer::getLVForTemplateParameterList( 230 const TemplateParameterList *Params, LVComputationKind computation) { 231 LinkageInfo LV; 232 for (const NamedDecl *P : *Params) { 233 // Template type parameters are the most common and never 234 // contribute to visibility, pack or not. 235 if (isa<TemplateTypeParmDecl>(P)) 236 continue; 237 238 // Non-type template parameters can be restricted by the value type, e.g. 239 // template <enum X> class A { ... }; 240 // We have to be careful here, though, because we can be dealing with 241 // dependent types. 242 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 243 // Handle the non-pack case first. 244 if (!NTTP->isExpandedParameterPack()) { 245 if (!NTTP->getType()->isDependentType()) { 246 LV.merge(getLVForType(*NTTP->getType(), computation)); 247 } 248 continue; 249 } 250 251 // Look at all the types in an expanded pack. 252 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { 253 QualType type = NTTP->getExpansionType(i); 254 if (!type->isDependentType()) 255 LV.merge(getTypeLinkageAndVisibility(type)); 256 } 257 continue; 258 } 259 260 // Template template parameters can be restricted by their 261 // template parameters, recursively. 262 const auto *TTP = cast<TemplateTemplateParmDecl>(P); 263 264 // Handle the non-pack case first. 265 if (!TTP->isExpandedParameterPack()) { 266 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(), 267 computation)); 268 continue; 269 } 270 271 // Look at all expansions in an expanded pack. 272 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); 273 i != n; ++i) { 274 LV.merge(getLVForTemplateParameterList( 275 TTP->getExpansionTemplateParameters(i), computation)); 276 } 277 } 278 279 return LV; 280 } 281 282 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { 283 const Decl *Ret = nullptr; 284 const DeclContext *DC = D->getDeclContext(); 285 while (DC->getDeclKind() != Decl::TranslationUnit) { 286 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC)) 287 Ret = cast<Decl>(DC); 288 DC = DC->getParent(); 289 } 290 return Ret; 291 } 292 293 /// \brief Get the most restrictive linkage for the types and 294 /// declarations in the given template argument list. 295 /// 296 /// Note that we don't take an LVComputationKind because we always 297 /// want to honor the visibility of template arguments in the same way. 298 LinkageInfo 299 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args, 300 LVComputationKind computation) { 301 LinkageInfo LV; 302 303 for (const TemplateArgument &Arg : Args) { 304 switch (Arg.getKind()) { 305 case TemplateArgument::Null: 306 case TemplateArgument::Integral: 307 case TemplateArgument::Expression: 308 continue; 309 310 case TemplateArgument::Type: 311 LV.merge(getLVForType(*Arg.getAsType(), computation)); 312 continue; 313 314 case TemplateArgument::Declaration: 315 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) { 316 assert(!usesTypeVisibility(ND)); 317 LV.merge(getLVForDecl(ND, computation)); 318 } 319 continue; 320 321 case TemplateArgument::NullPtr: 322 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType())); 323 continue; 324 325 case TemplateArgument::Template: 326 case TemplateArgument::TemplateExpansion: 327 if (TemplateDecl *Template = 328 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 329 LV.merge(getLVForDecl(Template, computation)); 330 continue; 331 332 case TemplateArgument::Pack: 333 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation)); 334 continue; 335 } 336 llvm_unreachable("bad template argument kind"); 337 } 338 339 return LV; 340 } 341 342 LinkageInfo 343 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 344 LVComputationKind computation) { 345 return getLVForTemplateArgumentList(TArgs.asArray(), computation); 346 } 347 348 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, 349 const FunctionTemplateSpecializationInfo *specInfo) { 350 // Include visibility from the template parameters and arguments 351 // only if this is not an explicit instantiation or specialization 352 // with direct explicit visibility. (Implicit instantiations won't 353 // have a direct attribute.) 354 if (!specInfo->isExplicitInstantiationOrSpecialization()) 355 return true; 356 357 return !fn->hasAttr<VisibilityAttr>(); 358 } 359 360 /// Merge in template-related linkage and visibility for the given 361 /// function template specialization. 362 /// 363 /// We don't need a computation kind here because we can assume 364 /// LVForValue. 365 /// 366 /// \param[out] LV the computation to use for the parent 367 void LinkageComputer::mergeTemplateLV( 368 LinkageInfo &LV, const FunctionDecl *fn, 369 const FunctionTemplateSpecializationInfo *specInfo, 370 LVComputationKind computation) { 371 bool considerVisibility = 372 shouldConsiderTemplateVisibility(fn, specInfo); 373 374 // Merge information from the template parameters. 375 FunctionTemplateDecl *temp = specInfo->getTemplate(); 376 LinkageInfo tempLV = 377 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 378 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 379 380 // Merge information from the template arguments. 381 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 382 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 383 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 384 } 385 386 /// Does the given declaration have a direct visibility attribute 387 /// that would match the given rules? 388 static bool hasDirectVisibilityAttribute(const NamedDecl *D, 389 LVComputationKind computation) { 390 if (computation.IgnoreAllVisibility) 391 return false; 392 393 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) || 394 D->hasAttr<VisibilityAttr>(); 395 } 396 397 /// Should we consider visibility associated with the template 398 /// arguments and parameters of the given class template specialization? 399 static bool shouldConsiderTemplateVisibility( 400 const ClassTemplateSpecializationDecl *spec, 401 LVComputationKind computation) { 402 // Include visibility from the template parameters and arguments 403 // only if this is not an explicit instantiation or specialization 404 // with direct explicit visibility (and note that implicit 405 // instantiations won't have a direct attribute). 406 // 407 // Furthermore, we want to ignore template parameters and arguments 408 // for an explicit specialization when computing the visibility of a 409 // member thereof with explicit visibility. 410 // 411 // This is a bit complex; let's unpack it. 412 // 413 // An explicit class specialization is an independent, top-level 414 // declaration. As such, if it or any of its members has an 415 // explicit visibility attribute, that must directly express the 416 // user's intent, and we should honor it. The same logic applies to 417 // an explicit instantiation of a member of such a thing. 418 419 // Fast path: if this is not an explicit instantiation or 420 // specialization, we always want to consider template-related 421 // visibility restrictions. 422 if (!spec->isExplicitInstantiationOrSpecialization()) 423 return true; 424 425 // This is the 'member thereof' check. 426 if (spec->isExplicitSpecialization() && 427 hasExplicitVisibilityAlready(computation)) 428 return false; 429 430 return !hasDirectVisibilityAttribute(spec, computation); 431 } 432 433 /// Merge in template-related linkage and visibility for the given 434 /// class template specialization. 435 void LinkageComputer::mergeTemplateLV( 436 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec, 437 LVComputationKind computation) { 438 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 439 440 // Merge information from the template parameters, but ignore 441 // visibility if we're only considering template arguments. 442 443 ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 444 LinkageInfo tempLV = 445 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 446 LV.mergeMaybeWithVisibility(tempLV, 447 considerVisibility && !hasExplicitVisibilityAlready(computation)); 448 449 // Merge information from the template arguments. We ignore 450 // template-argument visibility if we've got an explicit 451 // instantiation with a visibility attribute. 452 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 453 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 454 if (considerVisibility) 455 LV.mergeVisibility(argsLV); 456 LV.mergeExternalVisibility(argsLV); 457 } 458 459 /// Should we consider visibility associated with the template 460 /// arguments and parameters of the given variable template 461 /// specialization? As usual, follow class template specialization 462 /// logic up to initialization. 463 static bool shouldConsiderTemplateVisibility( 464 const VarTemplateSpecializationDecl *spec, 465 LVComputationKind computation) { 466 // Include visibility from the template parameters and arguments 467 // only if this is not an explicit instantiation or specialization 468 // with direct explicit visibility (and note that implicit 469 // instantiations won't have a direct attribute). 470 if (!spec->isExplicitInstantiationOrSpecialization()) 471 return true; 472 473 // An explicit variable specialization is an independent, top-level 474 // declaration. As such, if it has an explicit visibility attribute, 475 // that must directly express the user's intent, and we should honor 476 // it. 477 if (spec->isExplicitSpecialization() && 478 hasExplicitVisibilityAlready(computation)) 479 return false; 480 481 return !hasDirectVisibilityAttribute(spec, computation); 482 } 483 484 /// Merge in template-related linkage and visibility for the given 485 /// variable template specialization. As usual, follow class template 486 /// specialization logic up to initialization. 487 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV, 488 const VarTemplateSpecializationDecl *spec, 489 LVComputationKind computation) { 490 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 491 492 // Merge information from the template parameters, but ignore 493 // visibility if we're only considering template arguments. 494 495 VarTemplateDecl *temp = spec->getSpecializedTemplate(); 496 LinkageInfo tempLV = 497 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 498 LV.mergeMaybeWithVisibility(tempLV, 499 considerVisibility && !hasExplicitVisibilityAlready(computation)); 500 501 // Merge information from the template arguments. We ignore 502 // template-argument visibility if we've got an explicit 503 // instantiation with a visibility attribute. 504 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 505 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 506 if (considerVisibility) 507 LV.mergeVisibility(argsLV); 508 LV.mergeExternalVisibility(argsLV); 509 } 510 511 static bool useInlineVisibilityHidden(const NamedDecl *D) { 512 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 513 const LangOptions &Opts = D->getASTContext().getLangOpts(); 514 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 515 return false; 516 517 const auto *FD = dyn_cast<FunctionDecl>(D); 518 if (!FD) 519 return false; 520 521 TemplateSpecializationKind TSK = TSK_Undeclared; 522 if (FunctionTemplateSpecializationInfo *spec 523 = FD->getTemplateSpecializationInfo()) { 524 TSK = spec->getTemplateSpecializationKind(); 525 } else if (MemberSpecializationInfo *MSI = 526 FD->getMemberSpecializationInfo()) { 527 TSK = MSI->getTemplateSpecializationKind(); 528 } 529 530 const FunctionDecl *Def = nullptr; 531 // InlineVisibilityHidden only applies to definitions, and 532 // isInlined() only gives meaningful answers on definitions 533 // anyway. 534 return TSK != TSK_ExplicitInstantiationDeclaration && 535 TSK != TSK_ExplicitInstantiationDefinition && 536 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 537 } 538 539 template <typename T> static bool isFirstInExternCContext(T *D) { 540 const T *First = D->getFirstDecl(); 541 return First->isInExternCContext(); 542 } 543 544 static bool isSingleLineLanguageLinkage(const Decl &D) { 545 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext())) 546 if (!SD->hasBraces()) 547 return true; 548 return false; 549 } 550 551 static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) { 552 // FIXME: Handle isModulePrivate. 553 switch (D->getModuleOwnershipKind()) { 554 case Decl::ModuleOwnershipKind::Unowned: 555 case Decl::ModuleOwnershipKind::ModulePrivate: 556 return false; 557 case Decl::ModuleOwnershipKind::Visible: 558 case Decl::ModuleOwnershipKind::VisibleWhenImported: 559 if (auto *M = D->getOwningModule()) 560 return M->Kind == Module::ModuleInterfaceUnit; 561 } 562 llvm_unreachable("unexpected module ownership kind"); 563 } 564 565 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) { 566 // Internal linkage declarations within a module interface unit are modeled 567 // as "module-internal linkage", which means that they have internal linkage 568 // formally but can be indirectly accessed from outside the module via inline 569 // functions and templates defined within the module. 570 if (auto *M = D->getOwningModule()) 571 if (M->Kind == Module::ModuleInterfaceUnit) 572 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false); 573 574 return LinkageInfo::internal(); 575 } 576 577 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) { 578 // C++ Modules TS [basic.link]/6.8: 579 // - A name declared at namespace scope that does not have internal linkage 580 // by the previous rules and that is introduced by a non-exported 581 // declaration has module linkage. 582 if (auto *M = D->getOwningModule()) 583 if (M->Kind == Module::ModuleInterfaceUnit) 584 if (!isExportedFromModuleIntefaceUnit( 585 cast<NamedDecl>(D->getCanonicalDecl()))) 586 return LinkageInfo(ModuleLinkage, DefaultVisibility, false); 587 588 return LinkageInfo::external(); 589 } 590 591 LinkageInfo 592 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, 593 LVComputationKind computation, 594 bool IgnoreVarTypeLinkage) { 595 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 596 "Not a name having namespace scope"); 597 ASTContext &Context = D->getASTContext(); 598 599 // C++ [basic.link]p3: 600 // A name having namespace scope (3.3.6) has internal linkage if it 601 // is the name of 602 // - an object, reference, function or function template that is 603 // explicitly declared static; or, 604 // (This bullet corresponds to C99 6.2.2p3.) 605 if (const auto *Var = dyn_cast<VarDecl>(D)) { 606 // Explicitly declared static. 607 if (Var->getStorageClass() == SC_Static) 608 return getInternalLinkageFor(Var); 609 610 // - a non-inline, non-volatile object or reference that is explicitly 611 // declared const or constexpr and neither explicitly declared extern 612 // nor previously declared to have external linkage; or (there is no 613 // equivalent in C99) 614 // The C++ modules TS adds "non-exported" to this list. 615 if (Context.getLangOpts().CPlusPlus && 616 Var->getType().isConstQualified() && 617 !Var->getType().isVolatileQualified() && 618 !Var->isInline() && 619 !isExportedFromModuleIntefaceUnit(Var)) { 620 const VarDecl *PrevVar = Var->getPreviousDecl(); 621 if (PrevVar) 622 return getLVForDecl(PrevVar, computation); 623 624 if (Var->getStorageClass() != SC_Extern && 625 Var->getStorageClass() != SC_PrivateExtern && 626 !isSingleLineLanguageLinkage(*Var)) 627 return getInternalLinkageFor(Var); 628 } 629 630 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; 631 PrevVar = PrevVar->getPreviousDecl()) { 632 if (PrevVar->getStorageClass() == SC_PrivateExtern && 633 Var->getStorageClass() == SC_None) 634 return getDeclLinkageAndVisibility(PrevVar); 635 // Explicitly declared static. 636 if (PrevVar->getStorageClass() == SC_Static) 637 return getInternalLinkageFor(Var); 638 } 639 } else if (const FunctionDecl *Function = D->getAsFunction()) { 640 // C++ [temp]p4: 641 // A non-member function template can have internal linkage; any 642 // other template name shall have external linkage. 643 644 // Explicitly declared static. 645 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 646 return getInternalLinkageFor(Function); 647 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) { 648 // - a data member of an anonymous union. 649 const VarDecl *VD = IFD->getVarDecl(); 650 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); 651 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage); 652 } 653 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"); 654 655 if (D->isInAnonymousNamespace()) { 656 const auto *Var = dyn_cast<VarDecl>(D); 657 const auto *Func = dyn_cast<FunctionDecl>(D); 658 // FIXME: The check for extern "C" here is not justified by the standard 659 // wording, but we retain it from the pre-DR1113 model to avoid breaking 660 // code. 661 // 662 // C++11 [basic.link]p4: 663 // An unnamed namespace or a namespace declared directly or indirectly 664 // within an unnamed namespace has internal linkage. 665 if ((!Var || !isFirstInExternCContext(Var)) && 666 (!Func || !isFirstInExternCContext(Func))) 667 return getInternalLinkageFor(D); 668 } 669 670 // Set up the defaults. 671 672 // C99 6.2.2p5: 673 // If the declaration of an identifier for an object has file 674 // scope and no storage-class specifier, its linkage is 675 // external. 676 LinkageInfo LV = getExternalLinkageFor(D); 677 678 if (!hasExplicitVisibilityAlready(computation)) { 679 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) { 680 LV.mergeVisibility(*Vis, true); 681 } else { 682 // If we're declared in a namespace with a visibility attribute, 683 // use that namespace's visibility, and it still counts as explicit. 684 for (const DeclContext *DC = D->getDeclContext(); 685 !isa<TranslationUnitDecl>(DC); 686 DC = DC->getParent()) { 687 const auto *ND = dyn_cast<NamespaceDecl>(DC); 688 if (!ND) continue; 689 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) { 690 LV.mergeVisibility(*Vis, true); 691 break; 692 } 693 } 694 } 695 696 // Add in global settings if the above didn't give us direct visibility. 697 if (!LV.isVisibilityExplicit()) { 698 // Use global type/value visibility as appropriate. 699 Visibility globalVisibility = 700 computation.isValueVisibility() 701 ? Context.getLangOpts().getValueVisibilityMode() 702 : Context.getLangOpts().getTypeVisibilityMode(); 703 LV.mergeVisibility(globalVisibility, /*explicit*/ false); 704 705 // If we're paying attention to global visibility, apply 706 // -finline-visibility-hidden if this is an inline method. 707 if (useInlineVisibilityHidden(D)) 708 LV.mergeVisibility(HiddenVisibility, true); 709 } 710 } 711 712 // C++ [basic.link]p4: 713 714 // A name having namespace scope has external linkage if it is the 715 // name of 716 // 717 // - an object or reference, unless it has internal linkage; or 718 if (const auto *Var = dyn_cast<VarDecl>(D)) { 719 // GCC applies the following optimization to variables and static 720 // data members, but not to functions: 721 // 722 // Modify the variable's LV by the LV of its type unless this is 723 // C or extern "C". This follows from [basic.link]p9: 724 // A type without linkage shall not be used as the type of a 725 // variable or function with external linkage unless 726 // - the entity has C language linkage, or 727 // - the entity is declared within an unnamed namespace, or 728 // - the entity is not used or is defined in the same 729 // translation unit. 730 // and [basic.link]p10: 731 // ...the types specified by all declarations referring to a 732 // given variable or function shall be identical... 733 // C does not have an equivalent rule. 734 // 735 // Ignore this if we've got an explicit attribute; the user 736 // probably knows what they're doing. 737 // 738 // Note that we don't want to make the variable non-external 739 // because of this, but unique-external linkage suits us. 740 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) && 741 !IgnoreVarTypeLinkage) { 742 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation); 743 if (!isExternallyVisible(TypeLV.getLinkage())) 744 return LinkageInfo::uniqueExternal(); 745 if (!LV.isVisibilityExplicit()) 746 LV.mergeVisibility(TypeLV); 747 } 748 749 if (Var->getStorageClass() == SC_PrivateExtern) 750 LV.mergeVisibility(HiddenVisibility, true); 751 752 // Note that Sema::MergeVarDecl already takes care of implementing 753 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 754 // to do it here. 755 756 // As per function and class template specializations (below), 757 // consider LV for the template and template arguments. We're at file 758 // scope, so we do not need to worry about nested specializations. 759 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 760 mergeTemplateLV(LV, spec, computation); 761 } 762 763 // - a function, unless it has internal linkage; or 764 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 765 // In theory, we can modify the function's LV by the LV of its 766 // type unless it has C linkage (see comment above about variables 767 // for justification). In practice, GCC doesn't do this, so it's 768 // just too painful to make work. 769 770 if (Function->getStorageClass() == SC_PrivateExtern) 771 LV.mergeVisibility(HiddenVisibility, true); 772 773 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 774 // merging storage classes and visibility attributes, so we don't have to 775 // look at previous decls in here. 776 777 // In C++, then if the type of the function uses a type with 778 // unique-external linkage, it's not legally usable from outside 779 // this translation unit. However, we should use the C linkage 780 // rules instead for extern "C" declarations. 781 if (Context.getLangOpts().CPlusPlus && !Function->isInExternCContext()) { 782 // Only look at the type-as-written. Otherwise, deducing the return type 783 // of a function could change its linkage. 784 QualType TypeAsWritten = Function->getType(); 785 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo()) 786 TypeAsWritten = TSI->getType(); 787 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 788 return LinkageInfo::uniqueExternal(); 789 } 790 791 // Consider LV from the template and the template arguments. 792 // We're at file scope, so we do not need to worry about nested 793 // specializations. 794 if (FunctionTemplateSpecializationInfo *specInfo 795 = Function->getTemplateSpecializationInfo()) { 796 mergeTemplateLV(LV, Function, specInfo, computation); 797 } 798 799 // - a named class (Clause 9), or an unnamed class defined in a 800 // typedef declaration in which the class has the typedef name 801 // for linkage purposes (7.1.3); or 802 // - a named enumeration (7.2), or an unnamed enumeration 803 // defined in a typedef declaration in which the enumeration 804 // has the typedef name for linkage purposes (7.1.3); or 805 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) { 806 // Unnamed tags have no linkage. 807 if (!Tag->hasNameForLinkage()) 808 return LinkageInfo::none(); 809 810 // If this is a class template specialization, consider the 811 // linkage of the template and template arguments. We're at file 812 // scope, so we do not need to worry about nested specializations. 813 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 814 mergeTemplateLV(LV, spec, computation); 815 } 816 817 // - an enumerator belonging to an enumeration with external linkage; 818 } else if (isa<EnumConstantDecl>(D)) { 819 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 820 computation); 821 if (!isExternalFormalLinkage(EnumLV.getLinkage())) 822 return LinkageInfo::none(); 823 LV.merge(EnumLV); 824 825 // - a template, unless it is a function template that has 826 // internal linkage (Clause 14); 827 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 828 bool considerVisibility = !hasExplicitVisibilityAlready(computation); 829 LinkageInfo tempLV = 830 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 831 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 832 833 // - a namespace (7.3), unless it is declared within an unnamed 834 // namespace. 835 // 836 // We handled names in anonymous namespaces above. 837 } else if (isa<NamespaceDecl>(D)) { 838 return LV; 839 840 // By extension, we assign external linkage to Objective-C 841 // interfaces. 842 } else if (isa<ObjCInterfaceDecl>(D)) { 843 // fallout 844 845 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 846 // A typedef declaration has linkage if it gives a type a name for 847 // linkage purposes. 848 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 849 return LinkageInfo::none(); 850 851 // Everything not covered here has no linkage. 852 } else { 853 return LinkageInfo::none(); 854 } 855 856 // If we ended up with non-externally-visible linkage, visibility should 857 // always be default. 858 if (!isExternallyVisible(LV.getLinkage())) 859 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); 860 861 return LV; 862 } 863 864 LinkageInfo 865 LinkageComputer::getLVForClassMember(const NamedDecl *D, 866 LVComputationKind computation, 867 bool IgnoreVarTypeLinkage) { 868 // Only certain class members have linkage. Note that fields don't 869 // really have linkage, but it's convenient to say they do for the 870 // purposes of calculating linkage of pointer-to-data-member 871 // template arguments. 872 // 873 // Templates also don't officially have linkage, but since we ignore 874 // the C++ standard and look at template arguments when determining 875 // linkage and visibility of a template specialization, we might hit 876 // a template template argument that way. If we do, we need to 877 // consider its linkage. 878 if (!(isa<CXXMethodDecl>(D) || 879 isa<VarDecl>(D) || 880 isa<FieldDecl>(D) || 881 isa<IndirectFieldDecl>(D) || 882 isa<TagDecl>(D) || 883 isa<TemplateDecl>(D))) 884 return LinkageInfo::none(); 885 886 LinkageInfo LV; 887 888 // If we have an explicit visibility attribute, merge that in. 889 if (!hasExplicitVisibilityAlready(computation)) { 890 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) 891 LV.mergeVisibility(*Vis, true); 892 // If we're paying attention to global visibility, apply 893 // -finline-visibility-hidden if this is an inline method. 894 // 895 // Note that we do this before merging information about 896 // the class visibility. 897 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) 898 LV.mergeVisibility(HiddenVisibility, true); 899 } 900 901 // If this class member has an explicit visibility attribute, the only 902 // thing that can change its visibility is the template arguments, so 903 // only look for them when processing the class. 904 LVComputationKind classComputation = computation; 905 if (LV.isVisibilityExplicit()) 906 classComputation = withExplicitVisibilityAlready(computation); 907 908 LinkageInfo classLV = 909 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation); 910 // The member has the same linkage as the class. If that's not externally 911 // visible, we don't need to compute anything about the linkage. 912 // FIXME: If we're only computing linkage, can we bail out here? 913 if (!isExternallyVisible(classLV.getLinkage())) 914 return classLV; 915 916 917 // Otherwise, don't merge in classLV yet, because in certain cases 918 // we need to completely ignore the visibility from it. 919 920 // Specifically, if this decl exists and has an explicit attribute. 921 const NamedDecl *explicitSpecSuppressor = nullptr; 922 923 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 924 // Only look at the type-as-written. Otherwise, deducing the return type 925 // of a function could change its linkage. 926 QualType TypeAsWritten = MD->getType(); 927 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 928 TypeAsWritten = TSI->getType(); 929 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 930 return LinkageInfo::uniqueExternal(); 931 932 // If this is a method template specialization, use the linkage for 933 // the template parameters and arguments. 934 if (FunctionTemplateSpecializationInfo *spec 935 = MD->getTemplateSpecializationInfo()) { 936 mergeTemplateLV(LV, MD, spec, computation); 937 if (spec->isExplicitSpecialization()) { 938 explicitSpecSuppressor = MD; 939 } else if (isExplicitMemberSpecialization(spec->getTemplate())) { 940 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); 941 } 942 } else if (isExplicitMemberSpecialization(MD)) { 943 explicitSpecSuppressor = MD; 944 } 945 946 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 947 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 948 mergeTemplateLV(LV, spec, computation); 949 if (spec->isExplicitSpecialization()) { 950 explicitSpecSuppressor = spec; 951 } else { 952 const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 953 if (isExplicitMemberSpecialization(temp)) { 954 explicitSpecSuppressor = temp->getTemplatedDecl(); 955 } 956 } 957 } else if (isExplicitMemberSpecialization(RD)) { 958 explicitSpecSuppressor = RD; 959 } 960 961 // Static data members. 962 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 963 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD)) 964 mergeTemplateLV(LV, spec, computation); 965 966 // Modify the variable's linkage by its type, but ignore the 967 // type's visibility unless it's a definition. 968 if (!IgnoreVarTypeLinkage) { 969 LinkageInfo typeLV = getLVForType(*VD->getType(), computation); 970 // FIXME: If the type's linkage is not externally visible, we can 971 // give this static data member UniqueExternalLinkage. 972 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()) 973 LV.mergeVisibility(typeLV); 974 LV.mergeExternalVisibility(typeLV); 975 } 976 977 if (isExplicitMemberSpecialization(VD)) { 978 explicitSpecSuppressor = VD; 979 } 980 981 // Template members. 982 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 983 bool considerVisibility = 984 (!LV.isVisibilityExplicit() && 985 !classLV.isVisibilityExplicit() && 986 !hasExplicitVisibilityAlready(computation)); 987 LinkageInfo tempLV = 988 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 989 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 990 991 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) { 992 if (isExplicitMemberSpecialization(redeclTemp)) { 993 explicitSpecSuppressor = temp->getTemplatedDecl(); 994 } 995 } 996 } 997 998 // We should never be looking for an attribute directly on a template. 999 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); 1000 1001 // If this member is an explicit member specialization, and it has 1002 // an explicit attribute, ignore visibility from the parent. 1003 bool considerClassVisibility = true; 1004 if (explicitSpecSuppressor && 1005 // optimization: hasDVA() is true only with explicit visibility. 1006 LV.isVisibilityExplicit() && 1007 classLV.getVisibility() != DefaultVisibility && 1008 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) { 1009 considerClassVisibility = false; 1010 } 1011 1012 // Finally, merge in information from the class. 1013 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility); 1014 return LV; 1015 } 1016 1017 void NamedDecl::anchor() {} 1018 1019 bool NamedDecl::isLinkageValid() const { 1020 if (!hasCachedLinkage()) 1021 return true; 1022 1023 Linkage L = LinkageComputer{} 1024 .computeLVForDecl(this, LVComputationKind::forLinkageOnly()) 1025 .getLinkage(); 1026 return L == getCachedLinkage(); 1027 } 1028 1029 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { 1030 StringRef name = getName(); 1031 if (name.empty()) return SFF_None; 1032 1033 if (name.front() == 'C') 1034 if (name == "CFStringCreateWithFormat" || 1035 name == "CFStringCreateWithFormatAndArguments" || 1036 name == "CFStringAppendFormat" || 1037 name == "CFStringAppendFormatAndArguments") 1038 return SFF_CFString; 1039 return SFF_None; 1040 } 1041 1042 Linkage NamedDecl::getLinkageInternal() const { 1043 // We don't care about visibility here, so ask for the cheapest 1044 // possible visibility analysis. 1045 return LinkageComputer{} 1046 .getLVForDecl(this, LVComputationKind::forLinkageOnly()) 1047 .getLinkage(); 1048 } 1049 1050 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 1051 return LinkageComputer{}.getDeclLinkageAndVisibility(this); 1052 } 1053 1054 static Optional<Visibility> 1055 getExplicitVisibilityAux(const NamedDecl *ND, 1056 NamedDecl::ExplicitVisibilityKind kind, 1057 bool IsMostRecent) { 1058 assert(!IsMostRecent || ND == ND->getMostRecentDecl()); 1059 1060 // Check the declaration itself first. 1061 if (Optional<Visibility> V = getVisibilityOf(ND, kind)) 1062 return V; 1063 1064 // If this is a member class of a specialization of a class template 1065 // and the corresponding decl has explicit visibility, use that. 1066 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 1067 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 1068 if (InstantiatedFrom) 1069 return getVisibilityOf(InstantiatedFrom, kind); 1070 } 1071 1072 // If there wasn't explicit visibility there, and this is a 1073 // specialization of a class template, check for visibility 1074 // on the pattern. 1075 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) 1076 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(), 1077 kind); 1078 1079 // Use the most recent declaration. 1080 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) { 1081 const NamedDecl *MostRecent = ND->getMostRecentDecl(); 1082 if (MostRecent != ND) 1083 return getExplicitVisibilityAux(MostRecent, kind, true); 1084 } 1085 1086 if (const auto *Var = dyn_cast<VarDecl>(ND)) { 1087 if (Var->isStaticDataMember()) { 1088 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 1089 if (InstantiatedFrom) 1090 return getVisibilityOf(InstantiatedFrom, kind); 1091 } 1092 1093 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var)) 1094 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), 1095 kind); 1096 1097 return None; 1098 } 1099 // Also handle function template specializations. 1100 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) { 1101 // If the function is a specialization of a template with an 1102 // explicit visibility attribute, use that. 1103 if (FunctionTemplateSpecializationInfo *templateInfo 1104 = fn->getTemplateSpecializationInfo()) 1105 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), 1106 kind); 1107 1108 // If the function is a member of a specialization of a class template 1109 // and the corresponding decl has explicit visibility, use that. 1110 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 1111 if (InstantiatedFrom) 1112 return getVisibilityOf(InstantiatedFrom, kind); 1113 1114 return None; 1115 } 1116 1117 // The visibility of a template is stored in the templated decl. 1118 if (const auto *TD = dyn_cast<TemplateDecl>(ND)) 1119 return getVisibilityOf(TD->getTemplatedDecl(), kind); 1120 1121 return None; 1122 } 1123 1124 Optional<Visibility> 1125 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { 1126 return getExplicitVisibilityAux(this, kind, false); 1127 } 1128 1129 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC, 1130 Decl *ContextDecl, 1131 LVComputationKind computation) { 1132 // This lambda has its linkage/visibility determined by its owner. 1133 const NamedDecl *Owner; 1134 if (!ContextDecl) 1135 Owner = dyn_cast<NamedDecl>(DC); 1136 else if (isa<ParmVarDecl>(ContextDecl)) 1137 Owner = 1138 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext()); 1139 else 1140 Owner = cast<NamedDecl>(ContextDecl); 1141 1142 if (!Owner) 1143 return LinkageInfo::none(); 1144 1145 // If the owner has a deduced type, we need to skip querying the linkage and 1146 // visibility of that type, because it might involve this closure type. The 1147 // only effect of this is that we might give a lambda VisibleNoLinkage rather 1148 // than NoLinkage when we don't strictly need to, which is benign. 1149 auto *VD = dyn_cast<VarDecl>(Owner); 1150 LinkageInfo OwnerLV = 1151 VD && VD->getType()->getContainedDeducedType() 1152 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true) 1153 : getLVForDecl(Owner, computation); 1154 1155 // A lambda never formally has linkage. But if the owner is externally 1156 // visible, then the lambda is too. We apply the same rules to blocks. 1157 if (!isExternallyVisible(OwnerLV.getLinkage())) 1158 return LinkageInfo::none(); 1159 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(), 1160 OwnerLV.isVisibilityExplicit()); 1161 } 1162 1163 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, 1164 LVComputationKind computation) { 1165 if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 1166 if (Function->isInAnonymousNamespace() && 1167 !Function->isInExternCContext()) 1168 return getInternalLinkageFor(Function); 1169 1170 // This is a "void f();" which got merged with a file static. 1171 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 1172 return getInternalLinkageFor(Function); 1173 1174 LinkageInfo LV; 1175 if (!hasExplicitVisibilityAlready(computation)) { 1176 if (Optional<Visibility> Vis = 1177 getExplicitVisibility(Function, computation)) 1178 LV.mergeVisibility(*Vis, true); 1179 } 1180 1181 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 1182 // merging storage classes and visibility attributes, so we don't have to 1183 // look at previous decls in here. 1184 1185 return LV; 1186 } 1187 1188 if (const auto *Var = dyn_cast<VarDecl>(D)) { 1189 if (Var->hasExternalStorage()) { 1190 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext()) 1191 return getInternalLinkageFor(Var); 1192 1193 LinkageInfo LV; 1194 if (Var->getStorageClass() == SC_PrivateExtern) 1195 LV.mergeVisibility(HiddenVisibility, true); 1196 else if (!hasExplicitVisibilityAlready(computation)) { 1197 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation)) 1198 LV.mergeVisibility(*Vis, true); 1199 } 1200 1201 if (const VarDecl *Prev = Var->getPreviousDecl()) { 1202 LinkageInfo PrevLV = getLVForDecl(Prev, computation); 1203 if (PrevLV.getLinkage()) 1204 LV.setLinkage(PrevLV.getLinkage()); 1205 LV.mergeVisibility(PrevLV); 1206 } 1207 1208 return LV; 1209 } 1210 1211 if (!Var->isStaticLocal()) 1212 return LinkageInfo::none(); 1213 } 1214 1215 ASTContext &Context = D->getASTContext(); 1216 if (!Context.getLangOpts().CPlusPlus) 1217 return LinkageInfo::none(); 1218 1219 const Decl *OuterD = getOutermostFuncOrBlockContext(D); 1220 if (!OuterD || OuterD->isInvalidDecl()) 1221 return LinkageInfo::none(); 1222 1223 LinkageInfo LV; 1224 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) { 1225 if (!BD->getBlockManglingNumber()) 1226 return LinkageInfo::none(); 1227 1228 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(), 1229 BD->getBlockManglingContextDecl(), computation); 1230 } else { 1231 const auto *FD = cast<FunctionDecl>(OuterD); 1232 if (!FD->isInlined() && 1233 !isTemplateInstantiation(FD->getTemplateSpecializationKind())) 1234 return LinkageInfo::none(); 1235 1236 LV = getLVForDecl(FD, computation); 1237 } 1238 if (!isExternallyVisible(LV.getLinkage())) 1239 return LinkageInfo::none(); 1240 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(), 1241 LV.isVisibilityExplicit()); 1242 } 1243 1244 static inline const CXXRecordDecl* 1245 getOutermostEnclosingLambda(const CXXRecordDecl *Record) { 1246 const CXXRecordDecl *Ret = Record; 1247 while (Record && Record->isLambda()) { 1248 Ret = Record; 1249 if (!Record->getParent()) break; 1250 // Get the Containing Class of this Lambda Class 1251 Record = dyn_cast_or_null<CXXRecordDecl>( 1252 Record->getParent()->getParent()); 1253 } 1254 return Ret; 1255 } 1256 1257 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, 1258 LVComputationKind computation, 1259 bool IgnoreVarTypeLinkage) { 1260 // Internal_linkage attribute overrides other considerations. 1261 if (D->hasAttr<InternalLinkageAttr>()) 1262 return getInternalLinkageFor(D); 1263 1264 // Objective-C: treat all Objective-C declarations as having external 1265 // linkage. 1266 switch (D->getKind()) { 1267 default: 1268 break; 1269 1270 // Per C++ [basic.link]p2, only the names of objects, references, 1271 // functions, types, templates, namespaces, and values ever have linkage. 1272 // 1273 // Note that the name of a typedef, namespace alias, using declaration, 1274 // and so on are not the name of the corresponding type, namespace, or 1275 // declaration, so they do *not* have linkage. 1276 case Decl::ImplicitParam: 1277 case Decl::Label: 1278 case Decl::NamespaceAlias: 1279 case Decl::ParmVar: 1280 case Decl::Using: 1281 case Decl::UsingShadow: 1282 case Decl::UsingDirective: 1283 return LinkageInfo::none(); 1284 1285 case Decl::EnumConstant: 1286 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. 1287 if (D->getASTContext().getLangOpts().CPlusPlus) 1288 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation); 1289 return LinkageInfo::visible_none(); 1290 1291 case Decl::Typedef: 1292 case Decl::TypeAlias: 1293 // A typedef declaration has linkage if it gives a type a name for 1294 // linkage purposes. 1295 if (!cast<TypedefNameDecl>(D) 1296 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 1297 return LinkageInfo::none(); 1298 break; 1299 1300 case Decl::TemplateTemplateParm: // count these as external 1301 case Decl::NonTypeTemplateParm: 1302 case Decl::ObjCAtDefsField: 1303 case Decl::ObjCCategory: 1304 case Decl::ObjCCategoryImpl: 1305 case Decl::ObjCCompatibleAlias: 1306 case Decl::ObjCImplementation: 1307 case Decl::ObjCMethod: 1308 case Decl::ObjCProperty: 1309 case Decl::ObjCPropertyImpl: 1310 case Decl::ObjCProtocol: 1311 return getExternalLinkageFor(D); 1312 1313 case Decl::CXXRecord: { 1314 const auto *Record = cast<CXXRecordDecl>(D); 1315 if (Record->isLambda()) { 1316 if (!Record->getLambdaManglingNumber()) { 1317 // This lambda has no mangling number, so it's internal. 1318 return getInternalLinkageFor(D); 1319 } 1320 1321 // This lambda has its linkage/visibility determined: 1322 // - either by the outermost lambda if that lambda has no mangling 1323 // number. 1324 // - or by the parent of the outer most lambda 1325 // This prevents infinite recursion in settings such as nested lambdas 1326 // used in NSDMI's, for e.g. 1327 // struct L { 1328 // int t{}; 1329 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); 1330 // }; 1331 const CXXRecordDecl *OuterMostLambda = 1332 getOutermostEnclosingLambda(Record); 1333 if (!OuterMostLambda->getLambdaManglingNumber()) 1334 return getInternalLinkageFor(D); 1335 1336 return getLVForClosure( 1337 OuterMostLambda->getDeclContext()->getRedeclContext(), 1338 OuterMostLambda->getLambdaContextDecl(), computation); 1339 } 1340 1341 break; 1342 } 1343 } 1344 1345 // Handle linkage for namespace-scope names. 1346 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 1347 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); 1348 1349 // C++ [basic.link]p5: 1350 // In addition, a member function, static data member, a named 1351 // class or enumeration of class scope, or an unnamed class or 1352 // enumeration defined in a class-scope typedef declaration such 1353 // that the class or enumeration has the typedef name for linkage 1354 // purposes (7.1.3), has external linkage if the name of the class 1355 // has external linkage. 1356 if (D->getDeclContext()->isRecord()) 1357 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage); 1358 1359 // C++ [basic.link]p6: 1360 // The name of a function declared in block scope and the name of 1361 // an object declared by a block scope extern declaration have 1362 // linkage. If there is a visible declaration of an entity with 1363 // linkage having the same name and type, ignoring entities 1364 // declared outside the innermost enclosing namespace scope, the 1365 // block scope declaration declares that same entity and receives 1366 // the linkage of the previous declaration. If there is more than 1367 // one such matching entity, the program is ill-formed. Otherwise, 1368 // if no matching entity is found, the block scope entity receives 1369 // external linkage. 1370 if (D->getDeclContext()->isFunctionOrMethod()) 1371 return getLVForLocalDecl(D, computation); 1372 1373 // C++ [basic.link]p6: 1374 // Names not covered by these rules have no linkage. 1375 return LinkageInfo::none(); 1376 } 1377 1378 /// getLVForDecl - Get the linkage and visibility for the given declaration. 1379 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, 1380 LVComputationKind computation) { 1381 // Internal_linkage attribute overrides other considerations. 1382 if (D->hasAttr<InternalLinkageAttr>()) 1383 return getInternalLinkageFor(D); 1384 1385 if (computation.IgnoreAllVisibility && D->hasCachedLinkage()) 1386 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); 1387 1388 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation)) 1389 return *LI; 1390 1391 LinkageInfo LV = computeLVForDecl(D, computation); 1392 if (D->hasCachedLinkage()) 1393 assert(D->getCachedLinkage() == LV.getLinkage()); 1394 1395 D->setCachedLinkage(LV.getLinkage()); 1396 cache(D, computation, LV); 1397 1398 #ifndef NDEBUG 1399 // In C (because of gnu inline) and in c++ with microsoft extensions an 1400 // static can follow an extern, so we can have two decls with different 1401 // linkages. 1402 const LangOptions &Opts = D->getASTContext().getLangOpts(); 1403 if (!Opts.CPlusPlus || Opts.MicrosoftExt) 1404 return LV; 1405 1406 // We have just computed the linkage for this decl. By induction we know 1407 // that all other computed linkages match, check that the one we just 1408 // computed also does. 1409 NamedDecl *Old = nullptr; 1410 for (auto I : D->redecls()) { 1411 auto *T = cast<NamedDecl>(I); 1412 if (T == D) 1413 continue; 1414 if (!T->isInvalidDecl() && T->hasCachedLinkage()) { 1415 Old = T; 1416 break; 1417 } 1418 } 1419 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage()); 1420 #endif 1421 1422 return LV; 1423 } 1424 1425 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) { 1426 return getLVForDecl(D, 1427 LVComputationKind(usesTypeVisibility(D) 1428 ? NamedDecl::VisibilityForType 1429 : NamedDecl::VisibilityForValue)); 1430 } 1431 1432 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const { 1433 Module *M = getOwningModule(); 1434 if (!M) 1435 return nullptr; 1436 1437 switch (M->Kind) { 1438 case Module::ModuleMapModule: 1439 // Module map modules have no special linkage semantics. 1440 return nullptr; 1441 1442 case Module::ModuleInterfaceUnit: 1443 return M; 1444 1445 case Module::GlobalModuleFragment: { 1446 // External linkage declarations in the global module have no owning module 1447 // for linkage purposes. But internal linkage declarations in the global 1448 // module fragment of a particular module are owned by that module for 1449 // linkage purposes. 1450 if (IgnoreLinkage) 1451 return nullptr; 1452 bool InternalLinkage; 1453 if (auto *ND = dyn_cast<NamedDecl>(this)) 1454 InternalLinkage = !ND->hasExternalFormalLinkage(); 1455 else { 1456 auto *NSD = dyn_cast<NamespaceDecl>(this); 1457 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) || 1458 isInAnonymousNamespace(); 1459 } 1460 return InternalLinkage ? M->Parent : nullptr; 1461 } 1462 } 1463 1464 llvm_unreachable("unknown module kind"); 1465 } 1466 1467 void NamedDecl::printName(raw_ostream &os) const { 1468 os << Name; 1469 } 1470 1471 std::string NamedDecl::getQualifiedNameAsString() const { 1472 std::string QualName; 1473 llvm::raw_string_ostream OS(QualName); 1474 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1475 return OS.str(); 1476 } 1477 1478 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1479 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1480 } 1481 1482 void NamedDecl::printQualifiedName(raw_ostream &OS, 1483 const PrintingPolicy &P) const { 1484 const DeclContext *Ctx = getDeclContext(); 1485 1486 // For ObjC methods, look through categories and use the interface as context. 1487 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) 1488 if (auto *ID = MD->getClassInterface()) 1489 Ctx = ID; 1490 1491 if (Ctx->isFunctionOrMethod()) { 1492 printName(OS); 1493 return; 1494 } 1495 1496 using ContextsTy = SmallVector<const DeclContext *, 8>; 1497 ContextsTy Contexts; 1498 1499 // Collect contexts. 1500 while (Ctx && isa<NamedDecl>(Ctx)) { 1501 Contexts.push_back(Ctx); 1502 Ctx = Ctx->getParent(); 1503 } 1504 1505 for (const DeclContext *DC : llvm::reverse(Contexts)) { 1506 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1507 OS << Spec->getName(); 1508 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1509 printTemplateArgumentList(OS, TemplateArgs.asArray(), P); 1510 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 1511 if (P.SuppressUnwrittenScope && 1512 (ND->isAnonymousNamespace() || ND->isInline())) 1513 continue; 1514 if (ND->isAnonymousNamespace()) { 1515 OS << (P.MSVCFormatting ? "`anonymous namespace\'" 1516 : "(anonymous namespace)"); 1517 } 1518 else 1519 OS << *ND; 1520 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { 1521 if (!RD->getIdentifier()) 1522 OS << "(anonymous " << RD->getKindName() << ')'; 1523 else 1524 OS << *RD; 1525 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1526 const FunctionProtoType *FT = nullptr; 1527 if (FD->hasWrittenPrototype()) 1528 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1529 1530 OS << *FD << '('; 1531 if (FT) { 1532 unsigned NumParams = FD->getNumParams(); 1533 for (unsigned i = 0; i < NumParams; ++i) { 1534 if (i) 1535 OS << ", "; 1536 OS << FD->getParamDecl(i)->getType().stream(P); 1537 } 1538 1539 if (FT->isVariadic()) { 1540 if (NumParams > 0) 1541 OS << ", "; 1542 OS << "..."; 1543 } 1544 } 1545 OS << ')'; 1546 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) { 1547 // C++ [dcl.enum]p10: Each enum-name and each unscoped 1548 // enumerator is declared in the scope that immediately contains 1549 // the enum-specifier. Each scoped enumerator is declared in the 1550 // scope of the enumeration. 1551 // For the case of unscoped enumerator, do not include in the qualified 1552 // name any information about its enum enclosing scope, as is visibility 1553 // is global. 1554 if (ED->isScoped()) 1555 OS << *ED; 1556 else 1557 continue; 1558 } else { 1559 OS << *cast<NamedDecl>(DC); 1560 } 1561 OS << "::"; 1562 } 1563 1564 if (getDeclName() || isa<DecompositionDecl>(this)) 1565 OS << *this; 1566 else 1567 OS << "(anonymous)"; 1568 } 1569 1570 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1571 const PrintingPolicy &Policy, 1572 bool Qualified) const { 1573 if (Qualified) 1574 printQualifiedName(OS, Policy); 1575 else 1576 printName(OS); 1577 } 1578 1579 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1580 return true; 1581 } 1582 static bool isRedeclarableImpl(...) { return false; } 1583 static bool isRedeclarable(Decl::Kind K) { 1584 switch (K) { 1585 #define DECL(Type, Base) \ 1586 case Decl::Type: \ 1587 return isRedeclarableImpl((Type##Decl *)nullptr); 1588 #define ABSTRACT_DECL(DECL) 1589 #include "clang/AST/DeclNodes.inc" 1590 } 1591 llvm_unreachable("unknown decl kind"); 1592 } 1593 1594 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const { 1595 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1596 1597 // Never replace one imported declaration with another; we need both results 1598 // when re-exporting. 1599 if (OldD->isFromASTFile() && isFromASTFile()) 1600 return false; 1601 1602 // A kind mismatch implies that the declaration is not replaced. 1603 if (OldD->getKind() != getKind()) 1604 return false; 1605 1606 // For method declarations, we never replace. (Why?) 1607 if (isa<ObjCMethodDecl>(this)) 1608 return false; 1609 1610 // For parameters, pick the newer one. This is either an error or (in 1611 // Objective-C) permitted as an extension. 1612 if (isa<ParmVarDecl>(this)) 1613 return true; 1614 1615 // Inline namespaces can give us two declarations with the same 1616 // name and kind in the same scope but different contexts; we should 1617 // keep both declarations in this case. 1618 if (!this->getDeclContext()->getRedeclContext()->Equals( 1619 OldD->getDeclContext()->getRedeclContext())) 1620 return false; 1621 1622 // Using declarations can be replaced if they import the same name from the 1623 // same context. 1624 if (auto *UD = dyn_cast<UsingDecl>(this)) { 1625 ASTContext &Context = getASTContext(); 1626 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1627 Context.getCanonicalNestedNameSpecifier( 1628 cast<UsingDecl>(OldD)->getQualifier()); 1629 } 1630 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1631 ASTContext &Context = getASTContext(); 1632 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1633 Context.getCanonicalNestedNameSpecifier( 1634 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1635 } 1636 1637 if (isRedeclarable(getKind())) { 1638 if (getCanonicalDecl() != OldD->getCanonicalDecl()) 1639 return false; 1640 1641 if (IsKnownNewer) 1642 return true; 1643 1644 // Check whether this is actually newer than OldD. We want to keep the 1645 // newer declaration. This loop will usually only iterate once, because 1646 // OldD is usually the previous declaration. 1647 for (auto D : redecls()) { 1648 if (D == OldD) 1649 break; 1650 1651 // If we reach the canonical declaration, then OldD is not actually older 1652 // than this one. 1653 // 1654 // FIXME: In this case, we should not add this decl to the lookup table. 1655 if (D->isCanonicalDecl()) 1656 return false; 1657 } 1658 1659 // It's a newer declaration of the same kind of declaration in the same 1660 // scope: we want this decl instead of the existing one. 1661 return true; 1662 } 1663 1664 // In all other cases, we need to keep both declarations in case they have 1665 // different visibility. Any attempt to use the name will result in an 1666 // ambiguity if more than one is visible. 1667 return false; 1668 } 1669 1670 bool NamedDecl::hasLinkage() const { 1671 return getFormalLinkage() != NoLinkage; 1672 } 1673 1674 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1675 NamedDecl *ND = this; 1676 while (auto *UD = dyn_cast<UsingShadowDecl>(ND)) 1677 ND = UD->getTargetDecl(); 1678 1679 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1680 return AD->getClassInterface(); 1681 1682 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND)) 1683 return AD->getNamespace(); 1684 1685 return ND; 1686 } 1687 1688 bool NamedDecl::isCXXInstanceMember() const { 1689 if (!isCXXClassMember()) 1690 return false; 1691 1692 const NamedDecl *D = this; 1693 if (isa<UsingShadowDecl>(D)) 1694 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1695 1696 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1697 return true; 1698 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction())) 1699 return MD->isInstance(); 1700 return false; 1701 } 1702 1703 //===----------------------------------------------------------------------===// 1704 // DeclaratorDecl Implementation 1705 //===----------------------------------------------------------------------===// 1706 1707 template <typename DeclT> 1708 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1709 if (decl->getNumTemplateParameterLists() > 0) 1710 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1711 else 1712 return decl->getInnerLocStart(); 1713 } 1714 1715 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1716 TypeSourceInfo *TSI = getTypeSourceInfo(); 1717 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1718 return SourceLocation(); 1719 } 1720 1721 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1722 if (QualifierLoc) { 1723 // Make sure the extended decl info is allocated. 1724 if (!hasExtInfo()) { 1725 // Save (non-extended) type source info pointer. 1726 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1727 // Allocate external info struct. 1728 DeclInfo = new (getASTContext()) ExtInfo; 1729 // Restore savedTInfo into (extended) decl info. 1730 getExtInfo()->TInfo = savedTInfo; 1731 } 1732 // Set qualifier info. 1733 getExtInfo()->QualifierLoc = QualifierLoc; 1734 } else { 1735 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1736 if (hasExtInfo()) { 1737 if (getExtInfo()->NumTemplParamLists == 0) { 1738 // Save type source info pointer. 1739 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 1740 // Deallocate the extended decl info. 1741 getASTContext().Deallocate(getExtInfo()); 1742 // Restore savedTInfo into (non-extended) decl info. 1743 DeclInfo = savedTInfo; 1744 } 1745 else 1746 getExtInfo()->QualifierLoc = QualifierLoc; 1747 } 1748 } 1749 } 1750 1751 void DeclaratorDecl::setTemplateParameterListsInfo( 1752 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1753 assert(!TPLists.empty()); 1754 // Make sure the extended decl info is allocated. 1755 if (!hasExtInfo()) { 1756 // Save (non-extended) type source info pointer. 1757 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1758 // Allocate external info struct. 1759 DeclInfo = new (getASTContext()) ExtInfo; 1760 // Restore savedTInfo into (extended) decl info. 1761 getExtInfo()->TInfo = savedTInfo; 1762 } 1763 // Set the template parameter lists info. 1764 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 1765 } 1766 1767 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1768 return getTemplateOrInnerLocStart(this); 1769 } 1770 1771 // Helper function: returns true if QT is or contains a type 1772 // having a postfix component. 1773 static bool typeIsPostfix(QualType QT) { 1774 while (true) { 1775 const Type* T = QT.getTypePtr(); 1776 switch (T->getTypeClass()) { 1777 default: 1778 return false; 1779 case Type::Pointer: 1780 QT = cast<PointerType>(T)->getPointeeType(); 1781 break; 1782 case Type::BlockPointer: 1783 QT = cast<BlockPointerType>(T)->getPointeeType(); 1784 break; 1785 case Type::MemberPointer: 1786 QT = cast<MemberPointerType>(T)->getPointeeType(); 1787 break; 1788 case Type::LValueReference: 1789 case Type::RValueReference: 1790 QT = cast<ReferenceType>(T)->getPointeeType(); 1791 break; 1792 case Type::PackExpansion: 1793 QT = cast<PackExpansionType>(T)->getPattern(); 1794 break; 1795 case Type::Paren: 1796 case Type::ConstantArray: 1797 case Type::DependentSizedArray: 1798 case Type::IncompleteArray: 1799 case Type::VariableArray: 1800 case Type::FunctionProto: 1801 case Type::FunctionNoProto: 1802 return true; 1803 } 1804 } 1805 } 1806 1807 SourceRange DeclaratorDecl::getSourceRange() const { 1808 SourceLocation RangeEnd = getLocation(); 1809 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1810 // If the declaration has no name or the type extends past the name take the 1811 // end location of the type. 1812 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 1813 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1814 } 1815 return SourceRange(getOuterLocStart(), RangeEnd); 1816 } 1817 1818 void QualifierInfo::setTemplateParameterListsInfo( 1819 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1820 // Free previous template parameters (if any). 1821 if (NumTemplParamLists > 0) { 1822 Context.Deallocate(TemplParamLists); 1823 TemplParamLists = nullptr; 1824 NumTemplParamLists = 0; 1825 } 1826 // Set info on matched template parameter lists (if any). 1827 if (!TPLists.empty()) { 1828 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 1829 NumTemplParamLists = TPLists.size(); 1830 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 1831 } 1832 } 1833 1834 //===----------------------------------------------------------------------===// 1835 // VarDecl Implementation 1836 //===----------------------------------------------------------------------===// 1837 1838 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1839 switch (SC) { 1840 case SC_None: break; 1841 case SC_Auto: return "auto"; 1842 case SC_Extern: return "extern"; 1843 case SC_PrivateExtern: return "__private_extern__"; 1844 case SC_Register: return "register"; 1845 case SC_Static: return "static"; 1846 } 1847 1848 llvm_unreachable("Invalid storage class"); 1849 } 1850 1851 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 1852 SourceLocation StartLoc, SourceLocation IdLoc, 1853 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1854 StorageClass SC) 1855 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 1856 redeclarable_base(C) { 1857 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 1858 "VarDeclBitfields too large!"); 1859 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 1860 "ParmVarDeclBitfields too large!"); 1861 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 1862 "NonParmVarDeclBitfields too large!"); 1863 AllBits = 0; 1864 VarDeclBits.SClass = SC; 1865 // Everything else is implicitly initialized to false. 1866 } 1867 1868 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1869 SourceLocation StartL, SourceLocation IdL, 1870 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1871 StorageClass S) { 1872 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 1873 } 1874 1875 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1876 return new (C, ID) 1877 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 1878 QualType(), nullptr, SC_None); 1879 } 1880 1881 void VarDecl::setStorageClass(StorageClass SC) { 1882 assert(isLegalForVariable(SC)); 1883 VarDeclBits.SClass = SC; 1884 } 1885 1886 VarDecl::TLSKind VarDecl::getTLSKind() const { 1887 switch (VarDeclBits.TSCSpec) { 1888 case TSCS_unspecified: 1889 if (!hasAttr<ThreadAttr>() && 1890 !(getASTContext().getLangOpts().OpenMPUseTLS && 1891 getASTContext().getTargetInfo().isTLSSupported() && 1892 hasAttr<OMPThreadPrivateDeclAttr>())) 1893 return TLS_None; 1894 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 1895 LangOptions::MSVC2015)) || 1896 hasAttr<OMPThreadPrivateDeclAttr>()) 1897 ? TLS_Dynamic 1898 : TLS_Static; 1899 case TSCS___thread: // Fall through. 1900 case TSCS__Thread_local: 1901 return TLS_Static; 1902 case TSCS_thread_local: 1903 return TLS_Dynamic; 1904 } 1905 llvm_unreachable("Unknown thread storage class specifier!"); 1906 } 1907 1908 SourceRange VarDecl::getSourceRange() const { 1909 if (const Expr *Init = getInit()) { 1910 SourceLocation InitEnd = Init->getLocEnd(); 1911 // If Init is implicit, ignore its source range and fallback on 1912 // DeclaratorDecl::getSourceRange() to handle postfix elements. 1913 if (InitEnd.isValid() && InitEnd != getLocation()) 1914 return SourceRange(getOuterLocStart(), InitEnd); 1915 } 1916 return DeclaratorDecl::getSourceRange(); 1917 } 1918 1919 template<typename T> 1920 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 1921 // C++ [dcl.link]p1: All function types, function names with external linkage, 1922 // and variable names with external linkage have a language linkage. 1923 if (!D.hasExternalFormalLinkage()) 1924 return NoLanguageLinkage; 1925 1926 // Language linkage is a C++ concept, but saying that everything else in C has 1927 // C language linkage fits the implementation nicely. 1928 ASTContext &Context = D.getASTContext(); 1929 if (!Context.getLangOpts().CPlusPlus) 1930 return CLanguageLinkage; 1931 1932 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 1933 // language linkage of the names of class members and the function type of 1934 // class member functions. 1935 const DeclContext *DC = D.getDeclContext(); 1936 if (DC->isRecord()) 1937 return CXXLanguageLinkage; 1938 1939 // If the first decl is in an extern "C" context, any other redeclaration 1940 // will have C language linkage. If the first one is not in an extern "C" 1941 // context, we would have reported an error for any other decl being in one. 1942 if (isFirstInExternCContext(&D)) 1943 return CLanguageLinkage; 1944 return CXXLanguageLinkage; 1945 } 1946 1947 template<typename T> 1948 static bool isDeclExternC(const T &D) { 1949 // Since the context is ignored for class members, they can only have C++ 1950 // language linkage or no language linkage. 1951 const DeclContext *DC = D.getDeclContext(); 1952 if (DC->isRecord()) { 1953 assert(D.getASTContext().getLangOpts().CPlusPlus); 1954 return false; 1955 } 1956 1957 return D.getLanguageLinkage() == CLanguageLinkage; 1958 } 1959 1960 LanguageLinkage VarDecl::getLanguageLinkage() const { 1961 return getDeclLanguageLinkage(*this); 1962 } 1963 1964 bool VarDecl::isExternC() const { 1965 return isDeclExternC(*this); 1966 } 1967 1968 bool VarDecl::isInExternCContext() const { 1969 return getLexicalDeclContext()->isExternCContext(); 1970 } 1971 1972 bool VarDecl::isInExternCXXContext() const { 1973 return getLexicalDeclContext()->isExternCXXContext(); 1974 } 1975 1976 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 1977 1978 VarDecl::DefinitionKind 1979 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 1980 if (isThisDeclarationADemotedDefinition()) 1981 return DeclarationOnly; 1982 1983 // C++ [basic.def]p2: 1984 // A declaration is a definition unless [...] it contains the 'extern' 1985 // specifier or a linkage-specification and neither an initializer [...], 1986 // it declares a non-inline static data member in a class declaration [...], 1987 // it declares a static data member outside a class definition and the variable 1988 // was defined within the class with the constexpr specifier [...], 1989 // C++1y [temp.expl.spec]p15: 1990 // An explicit specialization of a static data member or an explicit 1991 // specialization of a static data member template is a definition if the 1992 // declaration includes an initializer; otherwise, it is a declaration. 1993 // 1994 // FIXME: How do you declare (but not define) a partial specialization of 1995 // a static data member template outside the containing class? 1996 if (isStaticDataMember()) { 1997 if (isOutOfLine() && 1998 !(getCanonicalDecl()->isInline() && 1999 getCanonicalDecl()->isConstexpr()) && 2000 (hasInit() || 2001 // If the first declaration is out-of-line, this may be an 2002 // instantiation of an out-of-line partial specialization of a variable 2003 // template for which we have not yet instantiated the initializer. 2004 (getFirstDecl()->isOutOfLine() 2005 ? getTemplateSpecializationKind() == TSK_Undeclared 2006 : getTemplateSpecializationKind() != 2007 TSK_ExplicitSpecialization) || 2008 isa<VarTemplatePartialSpecializationDecl>(this))) 2009 return Definition; 2010 else if (!isOutOfLine() && isInline()) 2011 return Definition; 2012 else 2013 return DeclarationOnly; 2014 } 2015 // C99 6.7p5: 2016 // A definition of an identifier is a declaration for that identifier that 2017 // [...] causes storage to be reserved for that object. 2018 // Note: that applies for all non-file-scope objects. 2019 // C99 6.9.2p1: 2020 // If the declaration of an identifier for an object has file scope and an 2021 // initializer, the declaration is an external definition for the identifier 2022 if (hasInit()) 2023 return Definition; 2024 2025 if (hasDefiningAttr()) 2026 return Definition; 2027 2028 if (const auto *SAA = getAttr<SelectAnyAttr>()) 2029 if (!SAA->isInherited()) 2030 return Definition; 2031 2032 // A variable template specialization (other than a static data member 2033 // template or an explicit specialization) is a declaration until we 2034 // instantiate its initializer. 2035 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2036 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2037 !isa<VarTemplatePartialSpecializationDecl>(VTSD) && 2038 !VTSD->IsCompleteDefinition) 2039 return DeclarationOnly; 2040 } 2041 2042 if (hasExternalStorage()) 2043 return DeclarationOnly; 2044 2045 // [dcl.link] p7: 2046 // A declaration directly contained in a linkage-specification is treated 2047 // as if it contains the extern specifier for the purpose of determining 2048 // the linkage of the declared name and whether it is a definition. 2049 if (isSingleLineLanguageLinkage(*this)) 2050 return DeclarationOnly; 2051 2052 // C99 6.9.2p2: 2053 // A declaration of an object that has file scope without an initializer, 2054 // and without a storage class specifier or the scs 'static', constitutes 2055 // a tentative definition. 2056 // No such thing in C++. 2057 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 2058 return TentativeDefinition; 2059 2060 // What's left is (in C, block-scope) declarations without initializers or 2061 // external storage. These are definitions. 2062 return Definition; 2063 } 2064 2065 VarDecl *VarDecl::getActingDefinition() { 2066 DefinitionKind Kind = isThisDeclarationADefinition(); 2067 if (Kind != TentativeDefinition) 2068 return nullptr; 2069 2070 VarDecl *LastTentative = nullptr; 2071 VarDecl *First = getFirstDecl(); 2072 for (auto I : First->redecls()) { 2073 Kind = I->isThisDeclarationADefinition(); 2074 if (Kind == Definition) 2075 return nullptr; 2076 else if (Kind == TentativeDefinition) 2077 LastTentative = I; 2078 } 2079 return LastTentative; 2080 } 2081 2082 VarDecl *VarDecl::getDefinition(ASTContext &C) { 2083 VarDecl *First = getFirstDecl(); 2084 for (auto I : First->redecls()) { 2085 if (I->isThisDeclarationADefinition(C) == Definition) 2086 return I; 2087 } 2088 return nullptr; 2089 } 2090 2091 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 2092 DefinitionKind Kind = DeclarationOnly; 2093 2094 const VarDecl *First = getFirstDecl(); 2095 for (auto I : First->redecls()) { 2096 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 2097 if (Kind == Definition) 2098 break; 2099 } 2100 2101 return Kind; 2102 } 2103 2104 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2105 for (auto I : redecls()) { 2106 if (auto Expr = I->getInit()) { 2107 D = I; 2108 return Expr; 2109 } 2110 } 2111 return nullptr; 2112 } 2113 2114 bool VarDecl::hasInit() const { 2115 if (auto *P = dyn_cast<ParmVarDecl>(this)) 2116 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) 2117 return false; 2118 2119 return !Init.isNull(); 2120 } 2121 2122 Expr *VarDecl::getInit() { 2123 if (!hasInit()) 2124 return nullptr; 2125 2126 if (auto *S = Init.dyn_cast<Stmt *>()) 2127 return cast<Expr>(S); 2128 2129 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value); 2130 } 2131 2132 Stmt **VarDecl::getInitAddress() { 2133 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) 2134 return &ES->Value; 2135 2136 return Init.getAddrOfPtr1(); 2137 } 2138 2139 bool VarDecl::isOutOfLine() const { 2140 if (Decl::isOutOfLine()) 2141 return true; 2142 2143 if (!isStaticDataMember()) 2144 return false; 2145 2146 // If this static data member was instantiated from a static data member of 2147 // a class template, check whether that static data member was defined 2148 // out-of-line. 2149 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2150 return VD->isOutOfLine(); 2151 2152 return false; 2153 } 2154 2155 void VarDecl::setInit(Expr *I) { 2156 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2157 Eval->~EvaluatedStmt(); 2158 getASTContext().Deallocate(Eval); 2159 } 2160 2161 Init = I; 2162 } 2163 2164 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const { 2165 const LangOptions &Lang = C.getLangOpts(); 2166 2167 if (!Lang.CPlusPlus) 2168 return false; 2169 2170 // In C++11, any variable of reference type can be used in a constant 2171 // expression if it is initialized by a constant expression. 2172 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2173 return true; 2174 2175 // Only const objects can be used in constant expressions in C++. C++98 does 2176 // not require the variable to be non-volatile, but we consider this to be a 2177 // defect. 2178 if (!getType().isConstQualified() || getType().isVolatileQualified()) 2179 return false; 2180 2181 // In C++, const, non-volatile variables of integral or enumeration types 2182 // can be used in constant expressions. 2183 if (getType()->isIntegralOrEnumerationType()) 2184 return true; 2185 2186 // Additionally, in C++11, non-volatile constexpr variables can be used in 2187 // constant expressions. 2188 return Lang.CPlusPlus11 && isConstexpr(); 2189 } 2190 2191 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2192 /// form, which contains extra information on the evaluated value of the 2193 /// initializer. 2194 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2195 auto *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2196 if (!Eval) { 2197 // Note: EvaluatedStmt contains an APValue, which usually holds 2198 // resources not allocated from the ASTContext. We need to do some 2199 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2200 // where we can detect whether there's anything to clean up or not. 2201 Eval = new (getASTContext()) EvaluatedStmt; 2202 Eval->Value = Init.get<Stmt *>(); 2203 Init = Eval; 2204 } 2205 return Eval; 2206 } 2207 2208 APValue *VarDecl::evaluateValue() const { 2209 SmallVector<PartialDiagnosticAt, 8> Notes; 2210 return evaluateValue(Notes); 2211 } 2212 2213 APValue *VarDecl::evaluateValue( 2214 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2215 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2216 2217 // We only produce notes indicating why an initializer is non-constant the 2218 // first time it is evaluated. FIXME: The notes won't always be emitted the 2219 // first time we try evaluation, so might not be produced at all. 2220 if (Eval->WasEvaluated) 2221 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated; 2222 2223 const auto *Init = cast<Expr>(Eval->Value); 2224 assert(!Init->isValueDependent()); 2225 2226 if (Eval->IsEvaluating) { 2227 // FIXME: Produce a diagnostic for self-initialization. 2228 Eval->CheckedICE = true; 2229 Eval->IsICE = false; 2230 return nullptr; 2231 } 2232 2233 Eval->IsEvaluating = true; 2234 2235 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 2236 this, Notes); 2237 2238 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2239 // or that it's empty (so that there's nothing to clean up) if evaluation 2240 // failed. 2241 if (!Result) 2242 Eval->Evaluated = APValue(); 2243 else if (Eval->Evaluated.needsCleanup()) 2244 getASTContext().addDestruction(&Eval->Evaluated); 2245 2246 Eval->IsEvaluating = false; 2247 Eval->WasEvaluated = true; 2248 2249 // In C++11, we have determined whether the initializer was a constant 2250 // expression as a side-effect. 2251 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) { 2252 Eval->CheckedICE = true; 2253 Eval->IsICE = Result && Notes.empty(); 2254 } 2255 2256 return Result ? &Eval->Evaluated : nullptr; 2257 } 2258 2259 APValue *VarDecl::getEvaluatedValue() const { 2260 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 2261 if (Eval->WasEvaluated) 2262 return &Eval->Evaluated; 2263 2264 return nullptr; 2265 } 2266 2267 bool VarDecl::isInitKnownICE() const { 2268 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 2269 return Eval->CheckedICE; 2270 2271 return false; 2272 } 2273 2274 bool VarDecl::isInitICE() const { 2275 assert(isInitKnownICE() && 2276 "Check whether we already know that the initializer is an ICE"); 2277 return Init.get<EvaluatedStmt *>()->IsICE; 2278 } 2279 2280 bool VarDecl::checkInitIsICE() const { 2281 // Initializers of weak variables are never ICEs. 2282 if (isWeak()) 2283 return false; 2284 2285 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2286 if (Eval->CheckedICE) 2287 // We have already checked whether this subexpression is an 2288 // integral constant expression. 2289 return Eval->IsICE; 2290 2291 const auto *Init = cast<Expr>(Eval->Value); 2292 assert(!Init->isValueDependent()); 2293 2294 // In C++11, evaluate the initializer to check whether it's a constant 2295 // expression. 2296 if (getASTContext().getLangOpts().CPlusPlus11) { 2297 SmallVector<PartialDiagnosticAt, 8> Notes; 2298 evaluateValue(Notes); 2299 return Eval->IsICE; 2300 } 2301 2302 // It's an ICE whether or not the definition we found is 2303 // out-of-line. See DR 721 and the discussion in Clang PR 2304 // 6206 for details. 2305 2306 if (Eval->CheckingICE) 2307 return false; 2308 Eval->CheckingICE = true; 2309 2310 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext()); 2311 Eval->CheckingICE = false; 2312 Eval->CheckedICE = true; 2313 return Eval->IsICE; 2314 } 2315 2316 template<typename DeclT> 2317 static DeclT *getDefinitionOrSelf(DeclT *D) { 2318 assert(D); 2319 if (auto *Def = D->getDefinition()) 2320 return Def; 2321 return D; 2322 } 2323 2324 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2325 // If it's a variable template specialization, find the template or partial 2326 // specialization from which it was instantiated. 2327 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2328 auto From = VDTemplSpec->getInstantiatedFrom(); 2329 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2330 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) { 2331 if (NewVTD->isMemberSpecialization()) 2332 break; 2333 VTD = NewVTD; 2334 } 2335 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2336 } 2337 if (auto *VTPSD = 2338 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2339 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) { 2340 if (NewVTPSD->isMemberSpecialization()) 2341 break; 2342 VTPSD = NewVTPSD; 2343 } 2344 return getDefinitionOrSelf<VarDecl>(VTPSD); 2345 } 2346 } 2347 2348 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 2349 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2350 VarDecl *VD = getInstantiatedFromStaticDataMember(); 2351 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2352 VD = NewVD; 2353 return getDefinitionOrSelf(VD); 2354 } 2355 } 2356 2357 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) { 2358 while (VarTemplate->getInstantiatedFromMemberTemplate()) { 2359 if (VarTemplate->isMemberSpecialization()) 2360 break; 2361 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate(); 2362 } 2363 2364 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl()); 2365 } 2366 return nullptr; 2367 } 2368 2369 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2370 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2371 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2372 2373 return nullptr; 2374 } 2375 2376 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2377 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2378 return Spec->getSpecializationKind(); 2379 2380 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2381 return MSI->getTemplateSpecializationKind(); 2382 2383 return TSK_Undeclared; 2384 } 2385 2386 SourceLocation VarDecl::getPointOfInstantiation() const { 2387 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2388 return Spec->getPointOfInstantiation(); 2389 2390 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2391 return MSI->getPointOfInstantiation(); 2392 2393 return SourceLocation(); 2394 } 2395 2396 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2397 return getASTContext().getTemplateOrSpecializationInfo(this) 2398 .dyn_cast<VarTemplateDecl *>(); 2399 } 2400 2401 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2402 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2403 } 2404 2405 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2406 if (isStaticDataMember()) 2407 // FIXME: Remove ? 2408 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2409 return getASTContext().getTemplateOrSpecializationInfo(this) 2410 .dyn_cast<MemberSpecializationInfo *>(); 2411 return nullptr; 2412 } 2413 2414 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2415 SourceLocation PointOfInstantiation) { 2416 assert((isa<VarTemplateSpecializationDecl>(this) || 2417 getMemberSpecializationInfo()) && 2418 "not a variable or static data member template specialization"); 2419 2420 if (VarTemplateSpecializationDecl *Spec = 2421 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2422 Spec->setSpecializationKind(TSK); 2423 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2424 Spec->getPointOfInstantiation().isInvalid()) { 2425 Spec->setPointOfInstantiation(PointOfInstantiation); 2426 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2427 L->InstantiationRequested(this); 2428 } 2429 } 2430 2431 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2432 MSI->setTemplateSpecializationKind(TSK); 2433 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2434 MSI->getPointOfInstantiation().isInvalid()) { 2435 MSI->setPointOfInstantiation(PointOfInstantiation); 2436 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2437 L->InstantiationRequested(this); 2438 } 2439 } 2440 } 2441 2442 void 2443 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2444 TemplateSpecializationKind TSK) { 2445 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2446 "Previous template or instantiation?"); 2447 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2448 } 2449 2450 //===----------------------------------------------------------------------===// 2451 // ParmVarDecl Implementation 2452 //===----------------------------------------------------------------------===// 2453 2454 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2455 SourceLocation StartLoc, 2456 SourceLocation IdLoc, IdentifierInfo *Id, 2457 QualType T, TypeSourceInfo *TInfo, 2458 StorageClass S, Expr *DefArg) { 2459 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2460 S, DefArg); 2461 } 2462 2463 QualType ParmVarDecl::getOriginalType() const { 2464 TypeSourceInfo *TSI = getTypeSourceInfo(); 2465 QualType T = TSI ? TSI->getType() : getType(); 2466 if (const auto *DT = dyn_cast<DecayedType>(T)) 2467 return DT->getOriginalType(); 2468 return T; 2469 } 2470 2471 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2472 return new (C, ID) 2473 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2474 nullptr, QualType(), nullptr, SC_None, nullptr); 2475 } 2476 2477 SourceRange ParmVarDecl::getSourceRange() const { 2478 if (!hasInheritedDefaultArg()) { 2479 SourceRange ArgRange = getDefaultArgRange(); 2480 if (ArgRange.isValid()) 2481 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2482 } 2483 2484 // DeclaratorDecl considers the range of postfix types as overlapping with the 2485 // declaration name, but this is not the case with parameters in ObjC methods. 2486 if (isa<ObjCMethodDecl>(getDeclContext())) 2487 return SourceRange(DeclaratorDecl::getLocStart(), getLocation()); 2488 2489 return DeclaratorDecl::getSourceRange(); 2490 } 2491 2492 Expr *ParmVarDecl::getDefaultArg() { 2493 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2494 assert(!hasUninstantiatedDefaultArg() && 2495 "Default argument is not yet instantiated!"); 2496 2497 Expr *Arg = getInit(); 2498 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 2499 return E->getSubExpr(); 2500 2501 return Arg; 2502 } 2503 2504 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2505 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2506 Init = defarg; 2507 } 2508 2509 SourceRange ParmVarDecl::getDefaultArgRange() const { 2510 switch (ParmVarDeclBits.DefaultArgKind) { 2511 case DAK_None: 2512 case DAK_Unparsed: 2513 // Nothing we can do here. 2514 return SourceRange(); 2515 2516 case DAK_Uninstantiated: 2517 return getUninstantiatedDefaultArg()->getSourceRange(); 2518 2519 case DAK_Normal: 2520 if (const Expr *E = getInit()) 2521 return E->getSourceRange(); 2522 2523 // Missing an actual expression, may be invalid. 2524 return SourceRange(); 2525 } 2526 llvm_unreachable("Invalid default argument kind."); 2527 } 2528 2529 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 2530 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 2531 Init = arg; 2532 } 2533 2534 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 2535 assert(hasUninstantiatedDefaultArg() && 2536 "Wrong kind of initialization expression!"); 2537 return cast_or_null<Expr>(Init.get<Stmt *>()); 2538 } 2539 2540 bool ParmVarDecl::hasDefaultArg() const { 2541 // FIXME: We should just return false for DAK_None here once callers are 2542 // prepared for the case that we encountered an invalid default argument and 2543 // were unable to even build an invalid expression. 2544 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 2545 !Init.isNull(); 2546 } 2547 2548 bool ParmVarDecl::isParameterPack() const { 2549 return isa<PackExpansionType>(getType()); 2550 } 2551 2552 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 2553 getASTContext().setParameterIndex(this, parameterIndex); 2554 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 2555 } 2556 2557 unsigned ParmVarDecl::getParameterIndexLarge() const { 2558 return getASTContext().getParameterIndex(this); 2559 } 2560 2561 //===----------------------------------------------------------------------===// 2562 // FunctionDecl Implementation 2563 //===----------------------------------------------------------------------===// 2564 2565 void FunctionDecl::getNameForDiagnostic( 2566 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 2567 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 2568 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 2569 if (TemplateArgs) 2570 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 2571 } 2572 2573 bool FunctionDecl::isVariadic() const { 2574 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 2575 return FT->isVariadic(); 2576 return false; 2577 } 2578 2579 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 2580 for (auto I : redecls()) { 2581 if (I->doesThisDeclarationHaveABody()) { 2582 Definition = I; 2583 return true; 2584 } 2585 } 2586 2587 return false; 2588 } 2589 2590 bool FunctionDecl::hasTrivialBody() const 2591 { 2592 Stmt *S = getBody(); 2593 if (!S) { 2594 // Since we don't have a body for this function, we don't know if it's 2595 // trivial or not. 2596 return false; 2597 } 2598 2599 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 2600 return true; 2601 return false; 2602 } 2603 2604 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const { 2605 for (auto I : redecls()) { 2606 if (I->isThisDeclarationADefinition()) { 2607 Definition = I; 2608 return true; 2609 } 2610 } 2611 2612 return false; 2613 } 2614 2615 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 2616 if (!hasBody(Definition)) 2617 return nullptr; 2618 2619 if (Definition->Body) 2620 return Definition->Body.get(getASTContext().getExternalSource()); 2621 2622 return nullptr; 2623 } 2624 2625 void FunctionDecl::setBody(Stmt *B) { 2626 Body = B; 2627 if (B) 2628 EndRangeLoc = B->getLocEnd(); 2629 } 2630 2631 void FunctionDecl::setPure(bool P) { 2632 IsPure = P; 2633 if (P) 2634 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 2635 Parent->markedVirtualFunctionPure(); 2636 } 2637 2638 template<std::size_t Len> 2639 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 2640 IdentifierInfo *II = ND->getIdentifier(); 2641 return II && II->isStr(Str); 2642 } 2643 2644 bool FunctionDecl::isMain() const { 2645 const TranslationUnitDecl *tunit = 2646 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2647 return tunit && 2648 !tunit->getASTContext().getLangOpts().Freestanding && 2649 isNamed(this, "main"); 2650 } 2651 2652 bool FunctionDecl::isMSVCRTEntryPoint() const { 2653 const TranslationUnitDecl *TUnit = 2654 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2655 if (!TUnit) 2656 return false; 2657 2658 // Even though we aren't really targeting MSVCRT if we are freestanding, 2659 // semantic analysis for these functions remains the same. 2660 2661 // MSVCRT entry points only exist on MSVCRT targets. 2662 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 2663 return false; 2664 2665 // Nameless functions like constructors cannot be entry points. 2666 if (!getIdentifier()) 2667 return false; 2668 2669 return llvm::StringSwitch<bool>(getName()) 2670 .Cases("main", // an ANSI console app 2671 "wmain", // a Unicode console App 2672 "WinMain", // an ANSI GUI app 2673 "wWinMain", // a Unicode GUI app 2674 "DllMain", // a DLL 2675 true) 2676 .Default(false); 2677 } 2678 2679 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 2680 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 2681 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 2682 getDeclName().getCXXOverloadedOperator() == OO_Delete || 2683 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 2684 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 2685 2686 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2687 return false; 2688 2689 const auto *proto = getType()->castAs<FunctionProtoType>(); 2690 if (proto->getNumParams() != 2 || proto->isVariadic()) 2691 return false; 2692 2693 ASTContext &Context = 2694 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 2695 ->getASTContext(); 2696 2697 // The result type and first argument type are constant across all 2698 // these operators. The second argument must be exactly void*. 2699 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 2700 } 2701 2702 bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const { 2703 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 2704 return false; 2705 if (getDeclName().getCXXOverloadedOperator() != OO_New && 2706 getDeclName().getCXXOverloadedOperator() != OO_Delete && 2707 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 2708 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 2709 return false; 2710 2711 if (isa<CXXRecordDecl>(getDeclContext())) 2712 return false; 2713 2714 // This can only fail for an invalid 'operator new' declaration. 2715 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2716 return false; 2717 2718 const auto *FPT = getType()->castAs<FunctionProtoType>(); 2719 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic()) 2720 return false; 2721 2722 // If this is a single-parameter function, it must be a replaceable global 2723 // allocation or deallocation function. 2724 if (FPT->getNumParams() == 1) 2725 return true; 2726 2727 unsigned Params = 1; 2728 QualType Ty = FPT->getParamType(Params); 2729 ASTContext &Ctx = getASTContext(); 2730 2731 auto Consume = [&] { 2732 ++Params; 2733 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 2734 }; 2735 2736 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 2737 bool IsSizedDelete = false; 2738 if (Ctx.getLangOpts().SizedDeallocation && 2739 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 2740 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 2741 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 2742 IsSizedDelete = true; 2743 Consume(); 2744 } 2745 2746 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 2747 // new/delete. 2748 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 2749 if (IsAligned) 2750 *IsAligned = true; 2751 Consume(); 2752 } 2753 2754 // Finally, if this is not a sized delete, the final parameter can 2755 // be a 'const std::nothrow_t&'. 2756 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 2757 Ty = Ty->getPointeeType(); 2758 if (Ty.getCVRQualifiers() != Qualifiers::Const) 2759 return false; 2760 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 2761 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace()) 2762 Consume(); 2763 } 2764 2765 return Params == FPT->getNumParams(); 2766 } 2767 2768 bool FunctionDecl::isDestroyingOperatorDelete() const { 2769 // C++ P0722: 2770 // Within a class C, a single object deallocation function with signature 2771 // (T, std::destroying_delete_t, <more params>) 2772 // is a destroying operator delete. 2773 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 2774 getNumParams() < 2) 2775 return false; 2776 2777 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 2778 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 2779 RD->getIdentifier()->isStr("destroying_delete_t"); 2780 } 2781 2782 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 2783 return getDeclLanguageLinkage(*this); 2784 } 2785 2786 bool FunctionDecl::isExternC() const { 2787 return isDeclExternC(*this); 2788 } 2789 2790 bool FunctionDecl::isInExternCContext() const { 2791 return getLexicalDeclContext()->isExternCContext(); 2792 } 2793 2794 bool FunctionDecl::isInExternCXXContext() const { 2795 return getLexicalDeclContext()->isExternCXXContext(); 2796 } 2797 2798 bool FunctionDecl::isGlobal() const { 2799 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 2800 return Method->isStatic(); 2801 2802 if (getCanonicalDecl()->getStorageClass() == SC_Static) 2803 return false; 2804 2805 for (const DeclContext *DC = getDeclContext(); 2806 DC->isNamespace(); 2807 DC = DC->getParent()) { 2808 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 2809 if (!Namespace->getDeclName()) 2810 return false; 2811 break; 2812 } 2813 } 2814 2815 return true; 2816 } 2817 2818 bool FunctionDecl::isNoReturn() const { 2819 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 2820 hasAttr<C11NoReturnAttr>()) 2821 return true; 2822 2823 if (auto *FnTy = getType()->getAs<FunctionType>()) 2824 return FnTy->getNoReturnAttr(); 2825 2826 return false; 2827 } 2828 2829 void 2830 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 2831 redeclarable_base::setPreviousDecl(PrevDecl); 2832 2833 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 2834 FunctionTemplateDecl *PrevFunTmpl 2835 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 2836 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 2837 FunTmpl->setPreviousDecl(PrevFunTmpl); 2838 } 2839 2840 if (PrevDecl && PrevDecl->IsInline) 2841 IsInline = true; 2842 } 2843 2844 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 2845 2846 /// \brief Returns a value indicating whether this function 2847 /// corresponds to a builtin function. 2848 /// 2849 /// The function corresponds to a built-in function if it is 2850 /// declared at translation scope or within an extern "C" block and 2851 /// its name matches with the name of a builtin. The returned value 2852 /// will be 0 for functions that do not correspond to a builtin, a 2853 /// value of type \c Builtin::ID if in the target-independent range 2854 /// \c [1,Builtin::First), or a target-specific builtin value. 2855 unsigned FunctionDecl::getBuiltinID() const { 2856 if (!getIdentifier()) 2857 return 0; 2858 2859 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 2860 if (!BuiltinID) 2861 return 0; 2862 2863 ASTContext &Context = getASTContext(); 2864 if (Context.getLangOpts().CPlusPlus) { 2865 const auto *LinkageDecl = 2866 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext()); 2867 // In C++, the first declaration of a builtin is always inside an implicit 2868 // extern "C". 2869 // FIXME: A recognised library function may not be directly in an extern "C" 2870 // declaration, for instance "extern "C" { namespace std { decl } }". 2871 if (!LinkageDecl) { 2872 if (BuiltinID == Builtin::BI__GetExceptionInfo && 2873 Context.getTargetInfo().getCXXABI().isMicrosoft()) 2874 return Builtin::BI__GetExceptionInfo; 2875 return 0; 2876 } 2877 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c) 2878 return 0; 2879 } 2880 2881 // If the function is marked "overloadable", it has a different mangled name 2882 // and is not the C library function. 2883 if (hasAttr<OverloadableAttr>()) 2884 return 0; 2885 2886 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2887 return BuiltinID; 2888 2889 // This function has the name of a known C library 2890 // function. Determine whether it actually refers to the C library 2891 // function or whether it just has the same name. 2892 2893 // If this is a static function, it's not a builtin. 2894 if (getStorageClass() == SC_Static) 2895 return 0; 2896 2897 // OpenCL v1.2 s6.9.f - The library functions defined in 2898 // the C99 standard headers are not available. 2899 if (Context.getLangOpts().OpenCL && 2900 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2901 return 0; 2902 2903 return BuiltinID; 2904 } 2905 2906 /// getNumParams - Return the number of parameters this function must have 2907 /// based on its FunctionType. This is the length of the ParamInfo array 2908 /// after it has been created. 2909 unsigned FunctionDecl::getNumParams() const { 2910 const auto *FPT = getType()->getAs<FunctionProtoType>(); 2911 return FPT ? FPT->getNumParams() : 0; 2912 } 2913 2914 void FunctionDecl::setParams(ASTContext &C, 2915 ArrayRef<ParmVarDecl *> NewParamInfo) { 2916 assert(!ParamInfo && "Already has param info!"); 2917 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 2918 2919 // Zero params -> null pointer. 2920 if (!NewParamInfo.empty()) { 2921 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 2922 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 2923 } 2924 } 2925 2926 /// getMinRequiredArguments - Returns the minimum number of arguments 2927 /// needed to call this function. This may be fewer than the number of 2928 /// function parameters, if some of the parameters have default 2929 /// arguments (in C++) or are parameter packs (C++11). 2930 unsigned FunctionDecl::getMinRequiredArguments() const { 2931 if (!getASTContext().getLangOpts().CPlusPlus) 2932 return getNumParams(); 2933 2934 unsigned NumRequiredArgs = 0; 2935 for (auto *Param : parameters()) 2936 if (!Param->isParameterPack() && !Param->hasDefaultArg()) 2937 ++NumRequiredArgs; 2938 return NumRequiredArgs; 2939 } 2940 2941 /// \brief The combination of the extern and inline keywords under MSVC forces 2942 /// the function to be required. 2943 /// 2944 /// Note: This function assumes that we will only get called when isInlined() 2945 /// would return true for this FunctionDecl. 2946 bool FunctionDecl::isMSExternInline() const { 2947 assert(isInlined() && "expected to get called on an inlined function!"); 2948 2949 const ASTContext &Context = getASTContext(); 2950 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 2951 !hasAttr<DLLExportAttr>()) 2952 return false; 2953 2954 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 2955 FD = FD->getPreviousDecl()) 2956 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2957 return true; 2958 2959 return false; 2960 } 2961 2962 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 2963 if (Redecl->getStorageClass() != SC_Extern) 2964 return false; 2965 2966 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 2967 FD = FD->getPreviousDecl()) 2968 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2969 return false; 2970 2971 return true; 2972 } 2973 2974 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 2975 // Only consider file-scope declarations in this test. 2976 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 2977 return false; 2978 2979 // Only consider explicit declarations; the presence of a builtin for a 2980 // libcall shouldn't affect whether a definition is externally visible. 2981 if (Redecl->isImplicit()) 2982 return false; 2983 2984 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 2985 return true; // Not an inline definition 2986 2987 return false; 2988 } 2989 2990 /// \brief For a function declaration in C or C++, determine whether this 2991 /// declaration causes the definition to be externally visible. 2992 /// 2993 /// For instance, this determines if adding the current declaration to the set 2994 /// of redeclarations of the given functions causes 2995 /// isInlineDefinitionExternallyVisible to change from false to true. 2996 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 2997 assert(!doesThisDeclarationHaveABody() && 2998 "Must have a declaration without a body."); 2999 3000 ASTContext &Context = getASTContext(); 3001 3002 if (Context.getLangOpts().MSVCCompat) { 3003 const FunctionDecl *Definition; 3004 if (hasBody(Definition) && Definition->isInlined() && 3005 redeclForcesDefMSVC(this)) 3006 return true; 3007 } 3008 3009 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3010 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3011 // an externally visible definition. 3012 // 3013 // FIXME: What happens if gnu_inline gets added on after the first 3014 // declaration? 3015 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3016 return false; 3017 3018 const FunctionDecl *Prev = this; 3019 bool FoundBody = false; 3020 while ((Prev = Prev->getPreviousDecl())) { 3021 FoundBody |= Prev->Body.isValid(); 3022 3023 if (Prev->Body) { 3024 // If it's not the case that both 'inline' and 'extern' are 3025 // specified on the definition, then it is always externally visible. 3026 if (!Prev->isInlineSpecified() || 3027 Prev->getStorageClass() != SC_Extern) 3028 return false; 3029 } else if (Prev->isInlineSpecified() && 3030 Prev->getStorageClass() != SC_Extern) { 3031 return false; 3032 } 3033 } 3034 return FoundBody; 3035 } 3036 3037 if (Context.getLangOpts().CPlusPlus) 3038 return false; 3039 3040 // C99 6.7.4p6: 3041 // [...] If all of the file scope declarations for a function in a 3042 // translation unit include the inline function specifier without extern, 3043 // then the definition in that translation unit is an inline definition. 3044 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3045 return false; 3046 const FunctionDecl *Prev = this; 3047 bool FoundBody = false; 3048 while ((Prev = Prev->getPreviousDecl())) { 3049 FoundBody |= Prev->Body.isValid(); 3050 if (RedeclForcesDefC99(Prev)) 3051 return false; 3052 } 3053 return FoundBody; 3054 } 3055 3056 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3057 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3058 if (!TSI) 3059 return SourceRange(); 3060 FunctionTypeLoc FTL = 3061 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>(); 3062 if (!FTL) 3063 return SourceRange(); 3064 3065 // Skip self-referential return types. 3066 const SourceManager &SM = getASTContext().getSourceManager(); 3067 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3068 SourceLocation Boundary = getNameInfo().getLocStart(); 3069 if (RTRange.isInvalid() || Boundary.isInvalid() || 3070 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3071 return SourceRange(); 3072 3073 return RTRange; 3074 } 3075 3076 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3077 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3078 if (!TSI) 3079 return SourceRange(); 3080 FunctionTypeLoc FTL = 3081 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>(); 3082 if (!FTL) 3083 return SourceRange(); 3084 3085 return FTL.getExceptionSpecRange(); 3086 } 3087 3088 const Attr *FunctionDecl::getUnusedResultAttr() const { 3089 QualType RetType = getReturnType(); 3090 if (RetType->isRecordType()) { 3091 if (const auto *Ret = 3092 dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) { 3093 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) 3094 return R; 3095 } 3096 } else if (const auto *ET = RetType->getAs<EnumType>()) { 3097 if (const EnumDecl *ED = ET->getDecl()) { 3098 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>()) 3099 return R; 3100 } 3101 } 3102 return getAttr<WarnUnusedResultAttr>(); 3103 } 3104 3105 /// \brief For an inline function definition in C, or for a gnu_inline function 3106 /// in C++, determine whether the definition will be externally visible. 3107 /// 3108 /// Inline function definitions are always available for inlining optimizations. 3109 /// However, depending on the language dialect, declaration specifiers, and 3110 /// attributes, the definition of an inline function may or may not be 3111 /// "externally" visible to other translation units in the program. 3112 /// 3113 /// In C99, inline definitions are not externally visible by default. However, 3114 /// if even one of the global-scope declarations is marked "extern inline", the 3115 /// inline definition becomes externally visible (C99 6.7.4p6). 3116 /// 3117 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3118 /// definition, we use the GNU semantics for inline, which are nearly the 3119 /// opposite of C99 semantics. In particular, "inline" by itself will create 3120 /// an externally visible symbol, but "extern inline" will not create an 3121 /// externally visible symbol. 3122 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3123 assert((doesThisDeclarationHaveABody() || willHaveBody()) && 3124 "Must be a function definition"); 3125 assert(isInlined() && "Function must be inline"); 3126 ASTContext &Context = getASTContext(); 3127 3128 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3129 // Note: If you change the logic here, please change 3130 // doesDeclarationForceExternallyVisibleDefinition as well. 3131 // 3132 // If it's not the case that both 'inline' and 'extern' are 3133 // specified on the definition, then this inline definition is 3134 // externally visible. 3135 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3136 return true; 3137 3138 // If any declaration is 'inline' but not 'extern', then this definition 3139 // is externally visible. 3140 for (auto Redecl : redecls()) { 3141 if (Redecl->isInlineSpecified() && 3142 Redecl->getStorageClass() != SC_Extern) 3143 return true; 3144 } 3145 3146 return false; 3147 } 3148 3149 // The rest of this function is C-only. 3150 assert(!Context.getLangOpts().CPlusPlus && 3151 "should not use C inline rules in C++"); 3152 3153 // C99 6.7.4p6: 3154 // [...] If all of the file scope declarations for a function in a 3155 // translation unit include the inline function specifier without extern, 3156 // then the definition in that translation unit is an inline definition. 3157 for (auto Redecl : redecls()) { 3158 if (RedeclForcesDefC99(Redecl)) 3159 return true; 3160 } 3161 3162 // C99 6.7.4p6: 3163 // An inline definition does not provide an external definition for the 3164 // function, and does not forbid an external definition in another 3165 // translation unit. 3166 return false; 3167 } 3168 3169 /// getOverloadedOperator - Which C++ overloaded operator this 3170 /// function represents, if any. 3171 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3172 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3173 return getDeclName().getCXXOverloadedOperator(); 3174 else 3175 return OO_None; 3176 } 3177 3178 /// getLiteralIdentifier - The literal suffix identifier this function 3179 /// represents, if any. 3180 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3181 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3182 return getDeclName().getCXXLiteralIdentifier(); 3183 else 3184 return nullptr; 3185 } 3186 3187 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 3188 if (TemplateOrSpecialization.isNull()) 3189 return TK_NonTemplate; 3190 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 3191 return TK_FunctionTemplate; 3192 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 3193 return TK_MemberSpecialization; 3194 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 3195 return TK_FunctionTemplateSpecialization; 3196 if (TemplateOrSpecialization.is 3197 <DependentFunctionTemplateSpecializationInfo*>()) 3198 return TK_DependentFunctionTemplateSpecialization; 3199 3200 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 3201 } 3202 3203 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 3204 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 3205 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 3206 3207 return nullptr; 3208 } 3209 3210 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 3211 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>(); 3212 } 3213 3214 void 3215 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 3216 FunctionDecl *FD, 3217 TemplateSpecializationKind TSK) { 3218 assert(TemplateOrSpecialization.isNull() && 3219 "Member function is already a specialization"); 3220 MemberSpecializationInfo *Info 3221 = new (C) MemberSpecializationInfo(FD, TSK); 3222 TemplateOrSpecialization = Info; 3223 } 3224 3225 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 3226 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>(); 3227 } 3228 3229 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { 3230 TemplateOrSpecialization = Template; 3231 } 3232 3233 bool FunctionDecl::isImplicitlyInstantiable() const { 3234 // If the function is invalid, it can't be implicitly instantiated. 3235 if (isInvalidDecl()) 3236 return false; 3237 3238 switch (getTemplateSpecializationKind()) { 3239 case TSK_Undeclared: 3240 case TSK_ExplicitInstantiationDefinition: 3241 return false; 3242 3243 case TSK_ImplicitInstantiation: 3244 return true; 3245 3246 // It is possible to instantiate TSK_ExplicitSpecialization kind 3247 // if the FunctionDecl has a class scope specialization pattern. 3248 case TSK_ExplicitSpecialization: 3249 return getClassScopeSpecializationPattern() != nullptr; 3250 3251 case TSK_ExplicitInstantiationDeclaration: 3252 // Handled below. 3253 break; 3254 } 3255 3256 // Find the actual template from which we will instantiate. 3257 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 3258 bool HasPattern = false; 3259 if (PatternDecl) 3260 HasPattern = PatternDecl->hasBody(PatternDecl); 3261 3262 // C++0x [temp.explicit]p9: 3263 // Except for inline functions, other explicit instantiation declarations 3264 // have the effect of suppressing the implicit instantiation of the entity 3265 // to which they refer. 3266 if (!HasPattern || !PatternDecl) 3267 return true; 3268 3269 return PatternDecl->isInlined(); 3270 } 3271 3272 bool FunctionDecl::isTemplateInstantiation() const { 3273 switch (getTemplateSpecializationKind()) { 3274 case TSK_Undeclared: 3275 case TSK_ExplicitSpecialization: 3276 return false; 3277 case TSK_ImplicitInstantiation: 3278 case TSK_ExplicitInstantiationDeclaration: 3279 case TSK_ExplicitInstantiationDefinition: 3280 return true; 3281 } 3282 llvm_unreachable("All TSK values handled."); 3283 } 3284 3285 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 3286 // Handle class scope explicit specialization special case. 3287 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 3288 if (auto *Spec = getClassScopeSpecializationPattern()) 3289 return getDefinitionOrSelf(Spec); 3290 return nullptr; 3291 } 3292 3293 // If this is a generic lambda call operator specialization, its 3294 // instantiation pattern is always its primary template's pattern 3295 // even if its primary template was instantiated from another 3296 // member template (which happens with nested generic lambdas). 3297 // Since a lambda's call operator's body is transformed eagerly, 3298 // we don't have to go hunting for a prototype definition template 3299 // (i.e. instantiated-from-member-template) to use as an instantiation 3300 // pattern. 3301 3302 if (isGenericLambdaCallOperatorSpecialization( 3303 dyn_cast<CXXMethodDecl>(this))) { 3304 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 3305 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 3306 } 3307 3308 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 3309 while (Primary->getInstantiatedFromMemberTemplate()) { 3310 // If we have hit a point where the user provided a specialization of 3311 // this template, we're done looking. 3312 if (Primary->isMemberSpecialization()) 3313 break; 3314 Primary = Primary->getInstantiatedFromMemberTemplate(); 3315 } 3316 3317 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 3318 } 3319 3320 if (auto *MFD = getInstantiatedFromMemberFunction()) 3321 return getDefinitionOrSelf(MFD); 3322 3323 return nullptr; 3324 } 3325 3326 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 3327 if (FunctionTemplateSpecializationInfo *Info 3328 = TemplateOrSpecialization 3329 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3330 return Info->Template.getPointer(); 3331 } 3332 return nullptr; 3333 } 3334 3335 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const { 3336 return getASTContext().getClassScopeSpecializationPattern(this); 3337 } 3338 3339 FunctionTemplateSpecializationInfo * 3340 FunctionDecl::getTemplateSpecializationInfo() const { 3341 return TemplateOrSpecialization 3342 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 3343 } 3344 3345 const TemplateArgumentList * 3346 FunctionDecl::getTemplateSpecializationArgs() const { 3347 if (FunctionTemplateSpecializationInfo *Info 3348 = TemplateOrSpecialization 3349 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3350 return Info->TemplateArguments; 3351 } 3352 return nullptr; 3353 } 3354 3355 const ASTTemplateArgumentListInfo * 3356 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 3357 if (FunctionTemplateSpecializationInfo *Info 3358 = TemplateOrSpecialization 3359 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3360 return Info->TemplateArgumentsAsWritten; 3361 } 3362 return nullptr; 3363 } 3364 3365 void 3366 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 3367 FunctionTemplateDecl *Template, 3368 const TemplateArgumentList *TemplateArgs, 3369 void *InsertPos, 3370 TemplateSpecializationKind TSK, 3371 const TemplateArgumentListInfo *TemplateArgsAsWritten, 3372 SourceLocation PointOfInstantiation) { 3373 assert(TSK != TSK_Undeclared && 3374 "Must specify the type of function template specialization"); 3375 FunctionTemplateSpecializationInfo *Info 3376 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3377 if (!Info) 3378 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 3379 TemplateArgs, 3380 TemplateArgsAsWritten, 3381 PointOfInstantiation); 3382 TemplateOrSpecialization = Info; 3383 Template->addSpecialization(Info, InsertPos); 3384 } 3385 3386 void 3387 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 3388 const UnresolvedSetImpl &Templates, 3389 const TemplateArgumentListInfo &TemplateArgs) { 3390 assert(TemplateOrSpecialization.isNull()); 3391 DependentFunctionTemplateSpecializationInfo *Info = 3392 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 3393 TemplateArgs); 3394 TemplateOrSpecialization = Info; 3395 } 3396 3397 DependentFunctionTemplateSpecializationInfo * 3398 FunctionDecl::getDependentSpecializationInfo() const { 3399 return TemplateOrSpecialization 3400 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 3401 } 3402 3403 DependentFunctionTemplateSpecializationInfo * 3404 DependentFunctionTemplateSpecializationInfo::Create( 3405 ASTContext &Context, const UnresolvedSetImpl &Ts, 3406 const TemplateArgumentListInfo &TArgs) { 3407 void *Buffer = Context.Allocate( 3408 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>( 3409 TArgs.size(), Ts.size())); 3410 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs); 3411 } 3412 3413 DependentFunctionTemplateSpecializationInfo:: 3414 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 3415 const TemplateArgumentListInfo &TArgs) 3416 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 3417 NumTemplates = Ts.size(); 3418 NumArgs = TArgs.size(); 3419 3420 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>(); 3421 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 3422 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 3423 3424 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>(); 3425 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 3426 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 3427 } 3428 3429 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 3430 // For a function template specialization, query the specialization 3431 // information object. 3432 FunctionTemplateSpecializationInfo *FTSInfo 3433 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3434 if (FTSInfo) 3435 return FTSInfo->getTemplateSpecializationKind(); 3436 3437 MemberSpecializationInfo *MSInfo 3438 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 3439 if (MSInfo) 3440 return MSInfo->getTemplateSpecializationKind(); 3441 3442 return TSK_Undeclared; 3443 } 3444 3445 void 3446 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3447 SourceLocation PointOfInstantiation) { 3448 if (FunctionTemplateSpecializationInfo *FTSInfo 3449 = TemplateOrSpecialization.dyn_cast< 3450 FunctionTemplateSpecializationInfo*>()) { 3451 FTSInfo->setTemplateSpecializationKind(TSK); 3452 if (TSK != TSK_ExplicitSpecialization && 3453 PointOfInstantiation.isValid() && 3454 FTSInfo->getPointOfInstantiation().isInvalid()) { 3455 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 3456 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 3457 L->InstantiationRequested(this); 3458 } 3459 } else if (MemberSpecializationInfo *MSInfo 3460 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 3461 MSInfo->setTemplateSpecializationKind(TSK); 3462 if (TSK != TSK_ExplicitSpecialization && 3463 PointOfInstantiation.isValid() && 3464 MSInfo->getPointOfInstantiation().isInvalid()) { 3465 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3466 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 3467 L->InstantiationRequested(this); 3468 } 3469 } else 3470 llvm_unreachable("Function cannot have a template specialization kind"); 3471 } 3472 3473 SourceLocation FunctionDecl::getPointOfInstantiation() const { 3474 if (FunctionTemplateSpecializationInfo *FTSInfo 3475 = TemplateOrSpecialization.dyn_cast< 3476 FunctionTemplateSpecializationInfo*>()) 3477 return FTSInfo->getPointOfInstantiation(); 3478 else if (MemberSpecializationInfo *MSInfo 3479 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 3480 return MSInfo->getPointOfInstantiation(); 3481 3482 return SourceLocation(); 3483 } 3484 3485 bool FunctionDecl::isOutOfLine() const { 3486 if (Decl::isOutOfLine()) 3487 return true; 3488 3489 // If this function was instantiated from a member function of a 3490 // class template, check whether that member function was defined out-of-line. 3491 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 3492 const FunctionDecl *Definition; 3493 if (FD->hasBody(Definition)) 3494 return Definition->isOutOfLine(); 3495 } 3496 3497 // If this function was instantiated from a function template, 3498 // check whether that function template was defined out-of-line. 3499 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 3500 const FunctionDecl *Definition; 3501 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 3502 return Definition->isOutOfLine(); 3503 } 3504 3505 return false; 3506 } 3507 3508 SourceRange FunctionDecl::getSourceRange() const { 3509 return SourceRange(getOuterLocStart(), EndRangeLoc); 3510 } 3511 3512 unsigned FunctionDecl::getMemoryFunctionKind() const { 3513 IdentifierInfo *FnInfo = getIdentifier(); 3514 3515 if (!FnInfo) 3516 return 0; 3517 3518 // Builtin handling. 3519 switch (getBuiltinID()) { 3520 case Builtin::BI__builtin_memset: 3521 case Builtin::BI__builtin___memset_chk: 3522 case Builtin::BImemset: 3523 return Builtin::BImemset; 3524 3525 case Builtin::BI__builtin_memcpy: 3526 case Builtin::BI__builtin___memcpy_chk: 3527 case Builtin::BImemcpy: 3528 return Builtin::BImemcpy; 3529 3530 case Builtin::BI__builtin_memmove: 3531 case Builtin::BI__builtin___memmove_chk: 3532 case Builtin::BImemmove: 3533 return Builtin::BImemmove; 3534 3535 case Builtin::BIstrlcpy: 3536 case Builtin::BI__builtin___strlcpy_chk: 3537 return Builtin::BIstrlcpy; 3538 3539 case Builtin::BIstrlcat: 3540 case Builtin::BI__builtin___strlcat_chk: 3541 return Builtin::BIstrlcat; 3542 3543 case Builtin::BI__builtin_memcmp: 3544 case Builtin::BImemcmp: 3545 return Builtin::BImemcmp; 3546 3547 case Builtin::BI__builtin_strncpy: 3548 case Builtin::BI__builtin___strncpy_chk: 3549 case Builtin::BIstrncpy: 3550 return Builtin::BIstrncpy; 3551 3552 case Builtin::BI__builtin_strncmp: 3553 case Builtin::BIstrncmp: 3554 return Builtin::BIstrncmp; 3555 3556 case Builtin::BI__builtin_strncasecmp: 3557 case Builtin::BIstrncasecmp: 3558 return Builtin::BIstrncasecmp; 3559 3560 case Builtin::BI__builtin_strncat: 3561 case Builtin::BI__builtin___strncat_chk: 3562 case Builtin::BIstrncat: 3563 return Builtin::BIstrncat; 3564 3565 case Builtin::BI__builtin_strndup: 3566 case Builtin::BIstrndup: 3567 return Builtin::BIstrndup; 3568 3569 case Builtin::BI__builtin_strlen: 3570 case Builtin::BIstrlen: 3571 return Builtin::BIstrlen; 3572 3573 case Builtin::BI__builtin_bzero: 3574 case Builtin::BIbzero: 3575 return Builtin::BIbzero; 3576 3577 default: 3578 if (isExternC()) { 3579 if (FnInfo->isStr("memset")) 3580 return Builtin::BImemset; 3581 else if (FnInfo->isStr("memcpy")) 3582 return Builtin::BImemcpy; 3583 else if (FnInfo->isStr("memmove")) 3584 return Builtin::BImemmove; 3585 else if (FnInfo->isStr("memcmp")) 3586 return Builtin::BImemcmp; 3587 else if (FnInfo->isStr("strncpy")) 3588 return Builtin::BIstrncpy; 3589 else if (FnInfo->isStr("strncmp")) 3590 return Builtin::BIstrncmp; 3591 else if (FnInfo->isStr("strncasecmp")) 3592 return Builtin::BIstrncasecmp; 3593 else if (FnInfo->isStr("strncat")) 3594 return Builtin::BIstrncat; 3595 else if (FnInfo->isStr("strndup")) 3596 return Builtin::BIstrndup; 3597 else if (FnInfo->isStr("strlen")) 3598 return Builtin::BIstrlen; 3599 else if (FnInfo->isStr("bzero")) 3600 return Builtin::BIbzero; 3601 } 3602 break; 3603 } 3604 return 0; 3605 } 3606 3607 //===----------------------------------------------------------------------===// 3608 // FieldDecl Implementation 3609 //===----------------------------------------------------------------------===// 3610 3611 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 3612 SourceLocation StartLoc, SourceLocation IdLoc, 3613 IdentifierInfo *Id, QualType T, 3614 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 3615 InClassInitStyle InitStyle) { 3616 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 3617 BW, Mutable, InitStyle); 3618 } 3619 3620 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3621 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 3622 SourceLocation(), nullptr, QualType(), nullptr, 3623 nullptr, false, ICIS_NoInit); 3624 } 3625 3626 bool FieldDecl::isAnonymousStructOrUnion() const { 3627 if (!isImplicit() || getDeclName()) 3628 return false; 3629 3630 if (const auto *Record = getType()->getAs<RecordType>()) 3631 return Record->getDecl()->isAnonymousStructOrUnion(); 3632 3633 return false; 3634 } 3635 3636 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 3637 assert(isBitField() && "not a bitfield"); 3638 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 3639 } 3640 3641 unsigned FieldDecl::getFieldIndex() const { 3642 const FieldDecl *Canonical = getCanonicalDecl(); 3643 if (Canonical != this) 3644 return Canonical->getFieldIndex(); 3645 3646 if (CachedFieldIndex) return CachedFieldIndex - 1; 3647 3648 unsigned Index = 0; 3649 const RecordDecl *RD = getParent()->getDefinition(); 3650 assert(RD && "requested index for field of struct with no definition"); 3651 3652 for (auto *Field : RD->fields()) { 3653 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 3654 ++Index; 3655 } 3656 3657 assert(CachedFieldIndex && "failed to find field in parent"); 3658 return CachedFieldIndex - 1; 3659 } 3660 3661 SourceRange FieldDecl::getSourceRange() const { 3662 const Expr *FinalExpr = getInClassInitializer(); 3663 if (!FinalExpr) 3664 FinalExpr = getBitWidth(); 3665 if (FinalExpr) 3666 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd()); 3667 return DeclaratorDecl::getSourceRange(); 3668 } 3669 3670 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 3671 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 3672 "capturing type in non-lambda or captured record."); 3673 assert(InitStorage.getInt() == ISK_NoInit && 3674 InitStorage.getPointer() == nullptr && 3675 "bit width, initializer or captured type already set"); 3676 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType), 3677 ISK_CapturedVLAType); 3678 } 3679 3680 //===----------------------------------------------------------------------===// 3681 // TagDecl Implementation 3682 //===----------------------------------------------------------------------===// 3683 3684 SourceLocation TagDecl::getOuterLocStart() const { 3685 return getTemplateOrInnerLocStart(this); 3686 } 3687 3688 SourceRange TagDecl::getSourceRange() const { 3689 SourceLocation RBraceLoc = BraceRange.getEnd(); 3690 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 3691 return SourceRange(getOuterLocStart(), E); 3692 } 3693 3694 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 3695 3696 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 3697 TypedefNameDeclOrQualifier = TDD; 3698 if (const Type *T = getTypeForDecl()) { 3699 (void)T; 3700 assert(T->isLinkageValid()); 3701 } 3702 assert(isLinkageValid()); 3703 } 3704 3705 void TagDecl::startDefinition() { 3706 IsBeingDefined = true; 3707 3708 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 3709 struct CXXRecordDecl::DefinitionData *Data = 3710 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 3711 for (auto I : redecls()) 3712 cast<CXXRecordDecl>(I)->DefinitionData = Data; 3713 } 3714 } 3715 3716 void TagDecl::completeDefinition() { 3717 assert((!isa<CXXRecordDecl>(this) || 3718 cast<CXXRecordDecl>(this)->hasDefinition()) && 3719 "definition completed but not started"); 3720 3721 IsCompleteDefinition = true; 3722 IsBeingDefined = false; 3723 3724 if (ASTMutationListener *L = getASTMutationListener()) 3725 L->CompletedTagDefinition(this); 3726 } 3727 3728 TagDecl *TagDecl::getDefinition() const { 3729 if (isCompleteDefinition()) 3730 return const_cast<TagDecl *>(this); 3731 3732 // If it's possible for us to have an out-of-date definition, check now. 3733 if (MayHaveOutOfDateDef) { 3734 if (IdentifierInfo *II = getIdentifier()) { 3735 if (II->isOutOfDate()) { 3736 updateOutOfDate(*II); 3737 } 3738 } 3739 } 3740 3741 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 3742 return CXXRD->getDefinition(); 3743 3744 for (auto R : redecls()) 3745 if (R->isCompleteDefinition()) 3746 return R; 3747 3748 return nullptr; 3749 } 3750 3751 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 3752 if (QualifierLoc) { 3753 // Make sure the extended qualifier info is allocated. 3754 if (!hasExtInfo()) 3755 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3756 // Set qualifier info. 3757 getExtInfo()->QualifierLoc = QualifierLoc; 3758 } else { 3759 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 3760 if (hasExtInfo()) { 3761 if (getExtInfo()->NumTemplParamLists == 0) { 3762 getASTContext().Deallocate(getExtInfo()); 3763 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 3764 } 3765 else 3766 getExtInfo()->QualifierLoc = QualifierLoc; 3767 } 3768 } 3769 } 3770 3771 void TagDecl::setTemplateParameterListsInfo( 3772 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 3773 assert(!TPLists.empty()); 3774 // Make sure the extended decl info is allocated. 3775 if (!hasExtInfo()) 3776 // Allocate external info struct. 3777 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3778 // Set the template parameter lists info. 3779 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 3780 } 3781 3782 //===----------------------------------------------------------------------===// 3783 // EnumDecl Implementation 3784 //===----------------------------------------------------------------------===// 3785 3786 void EnumDecl::anchor() {} 3787 3788 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 3789 SourceLocation StartLoc, SourceLocation IdLoc, 3790 IdentifierInfo *Id, 3791 EnumDecl *PrevDecl, bool IsScoped, 3792 bool IsScopedUsingClassTag, bool IsFixed) { 3793 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 3794 IsScoped, IsScopedUsingClassTag, IsFixed); 3795 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3796 C.getTypeDeclType(Enum, PrevDecl); 3797 return Enum; 3798 } 3799 3800 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3801 EnumDecl *Enum = 3802 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 3803 nullptr, nullptr, false, false, false); 3804 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3805 return Enum; 3806 } 3807 3808 SourceRange EnumDecl::getIntegerTypeRange() const { 3809 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 3810 return TI->getTypeLoc().getSourceRange(); 3811 return SourceRange(); 3812 } 3813 3814 void EnumDecl::completeDefinition(QualType NewType, 3815 QualType NewPromotionType, 3816 unsigned NumPositiveBits, 3817 unsigned NumNegativeBits) { 3818 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 3819 if (!IntegerType) 3820 IntegerType = NewType.getTypePtr(); 3821 PromotionType = NewPromotionType; 3822 setNumPositiveBits(NumPositiveBits); 3823 setNumNegativeBits(NumNegativeBits); 3824 TagDecl::completeDefinition(); 3825 } 3826 3827 bool EnumDecl::isClosed() const { 3828 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 3829 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 3830 return true; 3831 } 3832 3833 bool EnumDecl::isClosedFlag() const { 3834 return isClosed() && hasAttr<FlagEnumAttr>(); 3835 } 3836 3837 bool EnumDecl::isClosedNonFlag() const { 3838 return isClosed() && !hasAttr<FlagEnumAttr>(); 3839 } 3840 3841 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 3842 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 3843 return MSI->getTemplateSpecializationKind(); 3844 3845 return TSK_Undeclared; 3846 } 3847 3848 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3849 SourceLocation PointOfInstantiation) { 3850 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 3851 assert(MSI && "Not an instantiated member enumeration?"); 3852 MSI->setTemplateSpecializationKind(TSK); 3853 if (TSK != TSK_ExplicitSpecialization && 3854 PointOfInstantiation.isValid() && 3855 MSI->getPointOfInstantiation().isInvalid()) 3856 MSI->setPointOfInstantiation(PointOfInstantiation); 3857 } 3858 3859 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 3860 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 3861 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 3862 EnumDecl *ED = getInstantiatedFromMemberEnum(); 3863 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 3864 ED = NewED; 3865 return getDefinitionOrSelf(ED); 3866 } 3867 } 3868 3869 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 3870 "couldn't find pattern for enum instantiation"); 3871 return nullptr; 3872 } 3873 3874 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 3875 if (SpecializationInfo) 3876 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 3877 3878 return nullptr; 3879 } 3880 3881 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 3882 TemplateSpecializationKind TSK) { 3883 assert(!SpecializationInfo && "Member enum is already a specialization"); 3884 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 3885 } 3886 3887 //===----------------------------------------------------------------------===// 3888 // RecordDecl Implementation 3889 //===----------------------------------------------------------------------===// 3890 3891 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 3892 DeclContext *DC, SourceLocation StartLoc, 3893 SourceLocation IdLoc, IdentifierInfo *Id, 3894 RecordDecl *PrevDecl) 3895 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc), 3896 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false), 3897 HasObjectMember(false), HasVolatileMember(false), 3898 LoadedFieldsFromExternalStorage(false) { 3899 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 3900 } 3901 3902 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 3903 SourceLocation StartLoc, SourceLocation IdLoc, 3904 IdentifierInfo *Id, RecordDecl* PrevDecl) { 3905 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 3906 StartLoc, IdLoc, Id, PrevDecl); 3907 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3908 3909 C.getTypeDeclType(R, PrevDecl); 3910 return R; 3911 } 3912 3913 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 3914 RecordDecl *R = 3915 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), 3916 SourceLocation(), nullptr, nullptr); 3917 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3918 return R; 3919 } 3920 3921 bool RecordDecl::isInjectedClassName() const { 3922 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 3923 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 3924 } 3925 3926 bool RecordDecl::isLambda() const { 3927 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 3928 return RD->isLambda(); 3929 return false; 3930 } 3931 3932 bool RecordDecl::isCapturedRecord() const { 3933 return hasAttr<CapturedRecordAttr>(); 3934 } 3935 3936 void RecordDecl::setCapturedRecord() { 3937 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 3938 } 3939 3940 RecordDecl::field_iterator RecordDecl::field_begin() const { 3941 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 3942 LoadFieldsFromExternalStorage(); 3943 3944 return field_iterator(decl_iterator(FirstDecl)); 3945 } 3946 3947 /// completeDefinition - Notes that the definition of this type is now 3948 /// complete. 3949 void RecordDecl::completeDefinition() { 3950 assert(!isCompleteDefinition() && "Cannot redefine record!"); 3951 TagDecl::completeDefinition(); 3952 } 3953 3954 /// isMsStruct - Get whether or not this record uses ms_struct layout. 3955 /// This which can be turned on with an attribute, pragma, or the 3956 /// -mms-bitfields command-line option. 3957 bool RecordDecl::isMsStruct(const ASTContext &C) const { 3958 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 3959 } 3960 3961 void RecordDecl::LoadFieldsFromExternalStorage() const { 3962 ExternalASTSource *Source = getASTContext().getExternalSource(); 3963 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 3964 3965 // Notify that we have a RecordDecl doing some initialization. 3966 ExternalASTSource::Deserializing TheFields(Source); 3967 3968 SmallVector<Decl*, 64> Decls; 3969 LoadedFieldsFromExternalStorage = true; 3970 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 3971 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 3972 }, Decls); 3973 3974 #ifndef NDEBUG 3975 // Check that all decls we got were FieldDecls. 3976 for (unsigned i=0, e=Decls.size(); i != e; ++i) 3977 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 3978 #endif 3979 3980 if (Decls.empty()) 3981 return; 3982 3983 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 3984 /*FieldsAlreadyLoaded=*/false); 3985 } 3986 3987 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 3988 ASTContext &Context = getASTContext(); 3989 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 3990 (SanitizerKind::Address | SanitizerKind::KernelAddress); 3991 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 3992 return false; 3993 const auto &Blacklist = Context.getSanitizerBlacklist(); 3994 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 3995 // We may be able to relax some of these requirements. 3996 int ReasonToReject = -1; 3997 if (!CXXRD || CXXRD->isExternCContext()) 3998 ReasonToReject = 0; // is not C++. 3999 else if (CXXRD->hasAttr<PackedAttr>()) 4000 ReasonToReject = 1; // is packed. 4001 else if (CXXRD->isUnion()) 4002 ReasonToReject = 2; // is a union. 4003 else if (CXXRD->isTriviallyCopyable()) 4004 ReasonToReject = 3; // is trivially copyable. 4005 else if (CXXRD->hasTrivialDestructor()) 4006 ReasonToReject = 4; // has trivial destructor. 4007 else if (CXXRD->isStandardLayout()) 4008 ReasonToReject = 5; // is standard layout. 4009 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(), 4010 "field-padding")) 4011 ReasonToReject = 6; // is in a blacklisted file. 4012 else if (Blacklist.isBlacklistedType(EnabledAsanMask, 4013 getQualifiedNameAsString(), 4014 "field-padding")) 4015 ReasonToReject = 7; // is blacklisted. 4016 4017 if (EmitRemark) { 4018 if (ReasonToReject >= 0) 4019 Context.getDiagnostics().Report( 4020 getLocation(), 4021 diag::remark_sanitize_address_insert_extra_padding_rejected) 4022 << getQualifiedNameAsString() << ReasonToReject; 4023 else 4024 Context.getDiagnostics().Report( 4025 getLocation(), 4026 diag::remark_sanitize_address_insert_extra_padding_accepted) 4027 << getQualifiedNameAsString(); 4028 } 4029 return ReasonToReject < 0; 4030 } 4031 4032 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 4033 for (const auto *I : fields()) { 4034 if (I->getIdentifier()) 4035 return I; 4036 4037 if (const auto *RT = I->getType()->getAs<RecordType>()) 4038 if (const FieldDecl *NamedDataMember = 4039 RT->getDecl()->findFirstNamedDataMember()) 4040 return NamedDataMember; 4041 } 4042 4043 // We didn't find a named data member. 4044 return nullptr; 4045 } 4046 4047 //===----------------------------------------------------------------------===// 4048 // BlockDecl Implementation 4049 //===----------------------------------------------------------------------===// 4050 4051 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 4052 assert(!ParamInfo && "Already has param info!"); 4053 4054 // Zero params -> null pointer. 4055 if (!NewParamInfo.empty()) { 4056 NumParams = NewParamInfo.size(); 4057 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 4058 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 4059 } 4060 } 4061 4062 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 4063 bool CapturesCXXThis) { 4064 this->CapturesCXXThis = CapturesCXXThis; 4065 this->NumCaptures = Captures.size(); 4066 4067 if (Captures.empty()) { 4068 this->Captures = nullptr; 4069 return; 4070 } 4071 4072 this->Captures = Captures.copy(Context).data(); 4073 } 4074 4075 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 4076 for (const auto &I : captures()) 4077 // Only auto vars can be captured, so no redeclaration worries. 4078 if (I.getVariable() == variable) 4079 return true; 4080 4081 return false; 4082 } 4083 4084 SourceRange BlockDecl::getSourceRange() const { 4085 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 4086 } 4087 4088 //===----------------------------------------------------------------------===// 4089 // Other Decl Allocation/Deallocation Method Implementations 4090 //===----------------------------------------------------------------------===// 4091 4092 void TranslationUnitDecl::anchor() {} 4093 4094 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 4095 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 4096 } 4097 4098 void PragmaCommentDecl::anchor() {} 4099 4100 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 4101 TranslationUnitDecl *DC, 4102 SourceLocation CommentLoc, 4103 PragmaMSCommentKind CommentKind, 4104 StringRef Arg) { 4105 PragmaCommentDecl *PCD = 4106 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 4107 PragmaCommentDecl(DC, CommentLoc, CommentKind); 4108 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 4109 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 4110 return PCD; 4111 } 4112 4113 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 4114 unsigned ID, 4115 unsigned ArgSize) { 4116 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 4117 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 4118 } 4119 4120 void PragmaDetectMismatchDecl::anchor() {} 4121 4122 PragmaDetectMismatchDecl * 4123 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 4124 SourceLocation Loc, StringRef Name, 4125 StringRef Value) { 4126 size_t ValueStart = Name.size() + 1; 4127 PragmaDetectMismatchDecl *PDMD = 4128 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 4129 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 4130 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 4131 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 4132 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 4133 Value.size()); 4134 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 4135 return PDMD; 4136 } 4137 4138 PragmaDetectMismatchDecl * 4139 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4140 unsigned NameValueSize) { 4141 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 4142 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 4143 } 4144 4145 void ExternCContextDecl::anchor() {} 4146 4147 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 4148 TranslationUnitDecl *DC) { 4149 return new (C, DC) ExternCContextDecl(DC); 4150 } 4151 4152 void LabelDecl::anchor() {} 4153 4154 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4155 SourceLocation IdentL, IdentifierInfo *II) { 4156 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 4157 } 4158 4159 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4160 SourceLocation IdentL, IdentifierInfo *II, 4161 SourceLocation GnuLabelL) { 4162 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 4163 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 4164 } 4165 4166 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4167 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 4168 SourceLocation()); 4169 } 4170 4171 void LabelDecl::setMSAsmLabel(StringRef Name) { 4172 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 4173 memcpy(Buffer, Name.data(), Name.size()); 4174 Buffer[Name.size()] = '\0'; 4175 MSAsmName = Buffer; 4176 } 4177 4178 void ValueDecl::anchor() {} 4179 4180 bool ValueDecl::isWeak() const { 4181 for (const auto *I : attrs()) 4182 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I)) 4183 return true; 4184 4185 return isWeakImported(); 4186 } 4187 4188 void ImplicitParamDecl::anchor() {} 4189 4190 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 4191 SourceLocation IdLoc, 4192 IdentifierInfo *Id, QualType Type, 4193 ImplicitParamKind ParamKind) { 4194 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 4195 } 4196 4197 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 4198 ImplicitParamKind ParamKind) { 4199 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 4200 } 4201 4202 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 4203 unsigned ID) { 4204 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 4205 } 4206 4207 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 4208 SourceLocation StartLoc, 4209 const DeclarationNameInfo &NameInfo, 4210 QualType T, TypeSourceInfo *TInfo, 4211 StorageClass SC, 4212 bool isInlineSpecified, 4213 bool hasWrittenPrototype, 4214 bool isConstexprSpecified) { 4215 FunctionDecl *New = 4216 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo, 4217 SC, isInlineSpecified, isConstexprSpecified); 4218 New->HasWrittenPrototype = hasWrittenPrototype; 4219 return New; 4220 } 4221 4222 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4223 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(), 4224 DeclarationNameInfo(), QualType(), nullptr, 4225 SC_None, false, false); 4226 } 4227 4228 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4229 return new (C, DC) BlockDecl(DC, L); 4230 } 4231 4232 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4233 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 4234 } 4235 4236 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 4237 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 4238 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 4239 4240 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 4241 unsigned NumParams) { 4242 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4243 CapturedDecl(DC, NumParams); 4244 } 4245 4246 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4247 unsigned NumParams) { 4248 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4249 CapturedDecl(nullptr, NumParams); 4250 } 4251 4252 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 4253 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 4254 4255 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 4256 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 4257 4258 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 4259 SourceLocation L, 4260 IdentifierInfo *Id, QualType T, 4261 Expr *E, const llvm::APSInt &V) { 4262 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 4263 } 4264 4265 EnumConstantDecl * 4266 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4267 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 4268 QualType(), nullptr, llvm::APSInt()); 4269 } 4270 4271 void IndirectFieldDecl::anchor() {} 4272 4273 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 4274 SourceLocation L, DeclarationName N, 4275 QualType T, 4276 MutableArrayRef<NamedDecl *> CH) 4277 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 4278 ChainingSize(CH.size()) { 4279 // In C++, indirect field declarations conflict with tag declarations in the 4280 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 4281 if (C.getLangOpts().CPlusPlus) 4282 IdentifierNamespace |= IDNS_Tag; 4283 } 4284 4285 IndirectFieldDecl * 4286 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 4287 IdentifierInfo *Id, QualType T, 4288 llvm::MutableArrayRef<NamedDecl *> CH) { 4289 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 4290 } 4291 4292 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 4293 unsigned ID) { 4294 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), 4295 DeclarationName(), QualType(), None); 4296 } 4297 4298 SourceRange EnumConstantDecl::getSourceRange() const { 4299 SourceLocation End = getLocation(); 4300 if (Init) 4301 End = Init->getLocEnd(); 4302 return SourceRange(getLocation(), End); 4303 } 4304 4305 void TypeDecl::anchor() {} 4306 4307 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 4308 SourceLocation StartLoc, SourceLocation IdLoc, 4309 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 4310 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 4311 } 4312 4313 void TypedefNameDecl::anchor() {} 4314 4315 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 4316 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 4317 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 4318 auto *ThisTypedef = this; 4319 if (AnyRedecl && OwningTypedef) { 4320 OwningTypedef = OwningTypedef->getCanonicalDecl(); 4321 ThisTypedef = ThisTypedef->getCanonicalDecl(); 4322 } 4323 if (OwningTypedef == ThisTypedef) 4324 return TT->getDecl(); 4325 } 4326 4327 return nullptr; 4328 } 4329 4330 bool TypedefNameDecl::isTransparentTagSlow() const { 4331 auto determineIsTransparent = [&]() { 4332 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 4333 if (auto *TD = TT->getDecl()) { 4334 if (TD->getName() != getName()) 4335 return false; 4336 SourceLocation TTLoc = getLocation(); 4337 SourceLocation TDLoc = TD->getLocation(); 4338 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 4339 return false; 4340 SourceManager &SM = getASTContext().getSourceManager(); 4341 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 4342 } 4343 } 4344 return false; 4345 }; 4346 4347 bool isTransparent = determineIsTransparent(); 4348 CacheIsTransparentTag = 1; 4349 if (isTransparent) 4350 CacheIsTransparentTag |= 0x2; 4351 return isTransparent; 4352 } 4353 4354 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4355 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 4356 nullptr, nullptr); 4357 } 4358 4359 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 4360 SourceLocation StartLoc, 4361 SourceLocation IdLoc, IdentifierInfo *Id, 4362 TypeSourceInfo *TInfo) { 4363 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 4364 } 4365 4366 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4367 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 4368 SourceLocation(), nullptr, nullptr); 4369 } 4370 4371 SourceRange TypedefDecl::getSourceRange() const { 4372 SourceLocation RangeEnd = getLocation(); 4373 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 4374 if (typeIsPostfix(TInfo->getType())) 4375 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 4376 } 4377 return SourceRange(getLocStart(), RangeEnd); 4378 } 4379 4380 SourceRange TypeAliasDecl::getSourceRange() const { 4381 SourceLocation RangeEnd = getLocStart(); 4382 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 4383 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 4384 return SourceRange(getLocStart(), RangeEnd); 4385 } 4386 4387 void FileScopeAsmDecl::anchor() {} 4388 4389 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 4390 StringLiteral *Str, 4391 SourceLocation AsmLoc, 4392 SourceLocation RParenLoc) { 4393 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 4394 } 4395 4396 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 4397 unsigned ID) { 4398 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 4399 SourceLocation()); 4400 } 4401 4402 void EmptyDecl::anchor() {} 4403 4404 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4405 return new (C, DC) EmptyDecl(DC, L); 4406 } 4407 4408 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4409 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 4410 } 4411 4412 //===----------------------------------------------------------------------===// 4413 // ImportDecl Implementation 4414 //===----------------------------------------------------------------------===// 4415 4416 /// \brief Retrieve the number of module identifiers needed to name the given 4417 /// module. 4418 static unsigned getNumModuleIdentifiers(Module *Mod) { 4419 unsigned Result = 1; 4420 while (Mod->Parent) { 4421 Mod = Mod->Parent; 4422 ++Result; 4423 } 4424 return Result; 4425 } 4426 4427 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4428 Module *Imported, 4429 ArrayRef<SourceLocation> IdentifierLocs) 4430 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) { 4431 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 4432 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 4433 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 4434 StoredLocs); 4435 } 4436 4437 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4438 Module *Imported, SourceLocation EndLoc) 4439 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) { 4440 *getTrailingObjects<SourceLocation>() = EndLoc; 4441 } 4442 4443 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 4444 SourceLocation StartLoc, Module *Imported, 4445 ArrayRef<SourceLocation> IdentifierLocs) { 4446 return new (C, DC, 4447 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 4448 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 4449 } 4450 4451 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 4452 SourceLocation StartLoc, 4453 Module *Imported, 4454 SourceLocation EndLoc) { 4455 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 4456 ImportDecl(DC, StartLoc, Imported, EndLoc); 4457 Import->setImplicit(); 4458 return Import; 4459 } 4460 4461 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4462 unsigned NumLocations) { 4463 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 4464 ImportDecl(EmptyShell()); 4465 } 4466 4467 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 4468 if (!ImportedAndComplete.getInt()) 4469 return None; 4470 4471 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 4472 return llvm::makeArrayRef(StoredLocs, 4473 getNumModuleIdentifiers(getImportedModule())); 4474 } 4475 4476 SourceRange ImportDecl::getSourceRange() const { 4477 if (!ImportedAndComplete.getInt()) 4478 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 4479 4480 return SourceRange(getLocation(), getIdentifierLocs().back()); 4481 } 4482 4483 //===----------------------------------------------------------------------===// 4484 // ExportDecl Implementation 4485 //===----------------------------------------------------------------------===// 4486 4487 void ExportDecl::anchor() {} 4488 4489 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 4490 SourceLocation ExportLoc) { 4491 return new (C, DC) ExportDecl(DC, ExportLoc); 4492 } 4493 4494 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4495 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 4496 } 4497