1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Decl subclasses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/Decl.h" 14 #include "Linkage.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/CanonicalType.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclOpenMP.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/DeclarationName.h" 27 #include "clang/AST/Expr.h" 28 #include "clang/AST/ExprCXX.h" 29 #include "clang/AST/ExternalASTSource.h" 30 #include "clang/AST/ODRHash.h" 31 #include "clang/AST/PrettyDeclStackTrace.h" 32 #include "clang/AST/PrettyPrinter.h" 33 #include "clang/AST/Randstruct.h" 34 #include "clang/AST/RecordLayout.h" 35 #include "clang/AST/Redeclarable.h" 36 #include "clang/AST/Stmt.h" 37 #include "clang/AST/TemplateBase.h" 38 #include "clang/AST/Type.h" 39 #include "clang/AST/TypeLoc.h" 40 #include "clang/Basic/Builtins.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/Linkage.h" 45 #include "clang/Basic/Module.h" 46 #include "clang/Basic/NoSanitizeList.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/Sanitizers.h" 49 #include "clang/Basic/SourceLocation.h" 50 #include "clang/Basic/SourceManager.h" 51 #include "clang/Basic/Specifiers.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/Visibility.h" 55 #include "llvm/ADT/APSInt.h" 56 #include "llvm/ADT/ArrayRef.h" 57 #include "llvm/ADT/STLExtras.h" 58 #include "llvm/ADT/SmallVector.h" 59 #include "llvm/ADT/StringRef.h" 60 #include "llvm/ADT/StringSwitch.h" 61 #include "llvm/Support/Casting.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/TargetParser/Triple.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <cstddef> 68 #include <cstring> 69 #include <memory> 70 #include <optional> 71 #include <string> 72 #include <tuple> 73 #include <type_traits> 74 75 using namespace clang; 76 77 Decl *clang::getPrimaryMergedDecl(Decl *D) { 78 return D->getASTContext().getPrimaryMergedDecl(D); 79 } 80 81 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 82 SourceLocation Loc = this->Loc; 83 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 84 if (Loc.isValid()) { 85 Loc.print(OS, Context.getSourceManager()); 86 OS << ": "; 87 } 88 OS << Message; 89 90 if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) { 91 OS << " '"; 92 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true); 93 OS << "'"; 94 } 95 96 OS << '\n'; 97 } 98 99 // Defined here so that it can be inlined into its direct callers. 100 bool Decl::isOutOfLine() const { 101 return !getLexicalDeclContext()->Equals(getDeclContext()); 102 } 103 104 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx) 105 : Decl(TranslationUnit, nullptr, SourceLocation()), 106 DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {} 107 108 //===----------------------------------------------------------------------===// 109 // NamedDecl Implementation 110 //===----------------------------------------------------------------------===// 111 112 // Visibility rules aren't rigorously externally specified, but here 113 // are the basic principles behind what we implement: 114 // 115 // 1. An explicit visibility attribute is generally a direct expression 116 // of the user's intent and should be honored. Only the innermost 117 // visibility attribute applies. If no visibility attribute applies, 118 // global visibility settings are considered. 119 // 120 // 2. There is one caveat to the above: on or in a template pattern, 121 // an explicit visibility attribute is just a default rule, and 122 // visibility can be decreased by the visibility of template 123 // arguments. But this, too, has an exception: an attribute on an 124 // explicit specialization or instantiation causes all the visibility 125 // restrictions of the template arguments to be ignored. 126 // 127 // 3. A variable that does not otherwise have explicit visibility can 128 // be restricted by the visibility of its type. 129 // 130 // 4. A visibility restriction is explicit if it comes from an 131 // attribute (or something like it), not a global visibility setting. 132 // When emitting a reference to an external symbol, visibility 133 // restrictions are ignored unless they are explicit. 134 // 135 // 5. When computing the visibility of a non-type, including a 136 // non-type member of a class, only non-type visibility restrictions 137 // are considered: the 'visibility' attribute, global value-visibility 138 // settings, and a few special cases like __private_extern. 139 // 140 // 6. When computing the visibility of a type, including a type member 141 // of a class, only type visibility restrictions are considered: 142 // the 'type_visibility' attribute and global type-visibility settings. 143 // However, a 'visibility' attribute counts as a 'type_visibility' 144 // attribute on any declaration that only has the former. 145 // 146 // The visibility of a "secondary" entity, like a template argument, 147 // is computed using the kind of that entity, not the kind of the 148 // primary entity for which we are computing visibility. For example, 149 // the visibility of a specialization of either of these templates: 150 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); 151 // template <class T, bool (&compare)(T, X)> class matcher; 152 // is restricted according to the type visibility of the argument 'T', 153 // the type visibility of 'bool(&)(T,X)', and the value visibility of 154 // the argument function 'compare'. That 'has_match' is a value 155 // and 'matcher' is a type only matters when looking for attributes 156 // and settings from the immediate context. 157 158 /// Does this computation kind permit us to consider additional 159 /// visibility settings from attributes and the like? 160 static bool hasExplicitVisibilityAlready(LVComputationKind computation) { 161 return computation.IgnoreExplicitVisibility; 162 } 163 164 /// Given an LVComputationKind, return one of the same type/value sort 165 /// that records that it already has explicit visibility. 166 static LVComputationKind 167 withExplicitVisibilityAlready(LVComputationKind Kind) { 168 Kind.IgnoreExplicitVisibility = true; 169 return Kind; 170 } 171 172 static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D, 173 LVComputationKind kind) { 174 assert(!kind.IgnoreExplicitVisibility && 175 "asking for explicit visibility when we shouldn't be"); 176 return D->getExplicitVisibility(kind.getExplicitVisibilityKind()); 177 } 178 179 /// Is the given declaration a "type" or a "value" for the purposes of 180 /// visibility computation? 181 static bool usesTypeVisibility(const NamedDecl *D) { 182 return isa<TypeDecl>(D) || 183 isa<ClassTemplateDecl>(D) || 184 isa<ObjCInterfaceDecl>(D); 185 } 186 187 /// Does the given declaration have member specialization information, 188 /// and if so, is it an explicit specialization? 189 template <class T> 190 static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool> 191 isExplicitMemberSpecialization(const T *D) { 192 if (const MemberSpecializationInfo *member = 193 D->getMemberSpecializationInfo()) { 194 return member->isExplicitSpecialization(); 195 } 196 return false; 197 } 198 199 /// For templates, this question is easier: a member template can't be 200 /// explicitly instantiated, so there's a single bit indicating whether 201 /// or not this is an explicit member specialization. 202 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { 203 return D->isMemberSpecialization(); 204 } 205 206 /// Given a visibility attribute, return the explicit visibility 207 /// associated with it. 208 template <class T> 209 static Visibility getVisibilityFromAttr(const T *attr) { 210 switch (attr->getVisibility()) { 211 case T::Default: 212 return DefaultVisibility; 213 case T::Hidden: 214 return HiddenVisibility; 215 case T::Protected: 216 return ProtectedVisibility; 217 } 218 llvm_unreachable("bad visibility kind"); 219 } 220 221 /// Return the explicit visibility of the given declaration. 222 static std::optional<Visibility> 223 getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) { 224 // If we're ultimately computing the visibility of a type, look for 225 // a 'type_visibility' attribute before looking for 'visibility'. 226 if (kind == NamedDecl::VisibilityForType) { 227 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) { 228 return getVisibilityFromAttr(A); 229 } 230 } 231 232 // If this declaration has an explicit visibility attribute, use it. 233 if (const auto *A = D->getAttr<VisibilityAttr>()) { 234 return getVisibilityFromAttr(A); 235 } 236 237 return std::nullopt; 238 } 239 240 LinkageInfo LinkageComputer::getLVForType(const Type &T, 241 LVComputationKind computation) { 242 if (computation.IgnoreAllVisibility) 243 return LinkageInfo(T.getLinkage(), DefaultVisibility, true); 244 return getTypeLinkageAndVisibility(&T); 245 } 246 247 /// Get the most restrictive linkage for the types in the given 248 /// template parameter list. For visibility purposes, template 249 /// parameters are part of the signature of a template. 250 LinkageInfo LinkageComputer::getLVForTemplateParameterList( 251 const TemplateParameterList *Params, LVComputationKind computation) { 252 LinkageInfo LV; 253 for (const NamedDecl *P : *Params) { 254 // Template type parameters are the most common and never 255 // contribute to visibility, pack or not. 256 if (isa<TemplateTypeParmDecl>(P)) 257 continue; 258 259 // Non-type template parameters can be restricted by the value type, e.g. 260 // template <enum X> class A { ... }; 261 // We have to be careful here, though, because we can be dealing with 262 // dependent types. 263 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 264 // Handle the non-pack case first. 265 if (!NTTP->isExpandedParameterPack()) { 266 if (!NTTP->getType()->isDependentType()) { 267 LV.merge(getLVForType(*NTTP->getType(), computation)); 268 } 269 continue; 270 } 271 272 // Look at all the types in an expanded pack. 273 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { 274 QualType type = NTTP->getExpansionType(i); 275 if (!type->isDependentType()) 276 LV.merge(getTypeLinkageAndVisibility(type)); 277 } 278 continue; 279 } 280 281 // Template template parameters can be restricted by their 282 // template parameters, recursively. 283 const auto *TTP = cast<TemplateTemplateParmDecl>(P); 284 285 // Handle the non-pack case first. 286 if (!TTP->isExpandedParameterPack()) { 287 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(), 288 computation)); 289 continue; 290 } 291 292 // Look at all expansions in an expanded pack. 293 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); 294 i != n; ++i) { 295 LV.merge(getLVForTemplateParameterList( 296 TTP->getExpansionTemplateParameters(i), computation)); 297 } 298 } 299 300 return LV; 301 } 302 303 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { 304 const Decl *Ret = nullptr; 305 const DeclContext *DC = D->getDeclContext(); 306 while (DC->getDeclKind() != Decl::TranslationUnit) { 307 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC)) 308 Ret = cast<Decl>(DC); 309 DC = DC->getParent(); 310 } 311 return Ret; 312 } 313 314 /// Get the most restrictive linkage for the types and 315 /// declarations in the given template argument list. 316 /// 317 /// Note that we don't take an LVComputationKind because we always 318 /// want to honor the visibility of template arguments in the same way. 319 LinkageInfo 320 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args, 321 LVComputationKind computation) { 322 LinkageInfo LV; 323 324 for (const TemplateArgument &Arg : Args) { 325 switch (Arg.getKind()) { 326 case TemplateArgument::Null: 327 case TemplateArgument::Integral: 328 case TemplateArgument::Expression: 329 continue; 330 331 case TemplateArgument::Type: 332 LV.merge(getLVForType(*Arg.getAsType(), computation)); 333 continue; 334 335 case TemplateArgument::Declaration: { 336 const NamedDecl *ND = Arg.getAsDecl(); 337 assert(!usesTypeVisibility(ND)); 338 LV.merge(getLVForDecl(ND, computation)); 339 continue; 340 } 341 342 case TemplateArgument::NullPtr: 343 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType())); 344 continue; 345 346 case TemplateArgument::Template: 347 case TemplateArgument::TemplateExpansion: 348 if (TemplateDecl *Template = 349 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 350 LV.merge(getLVForDecl(Template, computation)); 351 continue; 352 353 case TemplateArgument::Pack: 354 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation)); 355 continue; 356 } 357 llvm_unreachable("bad template argument kind"); 358 } 359 360 return LV; 361 } 362 363 LinkageInfo 364 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 365 LVComputationKind computation) { 366 return getLVForTemplateArgumentList(TArgs.asArray(), computation); 367 } 368 369 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, 370 const FunctionTemplateSpecializationInfo *specInfo) { 371 // Include visibility from the template parameters and arguments 372 // only if this is not an explicit instantiation or specialization 373 // with direct explicit visibility. (Implicit instantiations won't 374 // have a direct attribute.) 375 if (!specInfo->isExplicitInstantiationOrSpecialization()) 376 return true; 377 378 return !fn->hasAttr<VisibilityAttr>(); 379 } 380 381 /// Merge in template-related linkage and visibility for the given 382 /// function template specialization. 383 /// 384 /// We don't need a computation kind here because we can assume 385 /// LVForValue. 386 /// 387 /// \param[out] LV the computation to use for the parent 388 void LinkageComputer::mergeTemplateLV( 389 LinkageInfo &LV, const FunctionDecl *fn, 390 const FunctionTemplateSpecializationInfo *specInfo, 391 LVComputationKind computation) { 392 bool considerVisibility = 393 shouldConsiderTemplateVisibility(fn, specInfo); 394 395 FunctionTemplateDecl *temp = specInfo->getTemplate(); 396 // Merge information from the template declaration. 397 LinkageInfo tempLV = getLVForDecl(temp, computation); 398 // The linkage of the specialization should be consistent with the 399 // template declaration. 400 LV.setLinkage(tempLV.getLinkage()); 401 402 // Merge information from the template parameters. 403 LinkageInfo paramsLV = 404 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 405 LV.mergeMaybeWithVisibility(paramsLV, considerVisibility); 406 407 // Merge information from the template arguments. 408 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 409 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 410 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 411 } 412 413 /// Does the given declaration have a direct visibility attribute 414 /// that would match the given rules? 415 static bool hasDirectVisibilityAttribute(const NamedDecl *D, 416 LVComputationKind computation) { 417 if (computation.IgnoreAllVisibility) 418 return false; 419 420 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) || 421 D->hasAttr<VisibilityAttr>(); 422 } 423 424 /// Should we consider visibility associated with the template 425 /// arguments and parameters of the given class template specialization? 426 static bool shouldConsiderTemplateVisibility( 427 const ClassTemplateSpecializationDecl *spec, 428 LVComputationKind computation) { 429 // Include visibility from the template parameters and arguments 430 // only if this is not an explicit instantiation or specialization 431 // with direct explicit visibility (and note that implicit 432 // instantiations won't have a direct attribute). 433 // 434 // Furthermore, we want to ignore template parameters and arguments 435 // for an explicit specialization when computing the visibility of a 436 // member thereof with explicit visibility. 437 // 438 // This is a bit complex; let's unpack it. 439 // 440 // An explicit class specialization is an independent, top-level 441 // declaration. As such, if it or any of its members has an 442 // explicit visibility attribute, that must directly express the 443 // user's intent, and we should honor it. The same logic applies to 444 // an explicit instantiation of a member of such a thing. 445 446 // Fast path: if this is not an explicit instantiation or 447 // specialization, we always want to consider template-related 448 // visibility restrictions. 449 if (!spec->isExplicitInstantiationOrSpecialization()) 450 return true; 451 452 // This is the 'member thereof' check. 453 if (spec->isExplicitSpecialization() && 454 hasExplicitVisibilityAlready(computation)) 455 return false; 456 457 return !hasDirectVisibilityAttribute(spec, computation); 458 } 459 460 /// Merge in template-related linkage and visibility for the given 461 /// class template specialization. 462 void LinkageComputer::mergeTemplateLV( 463 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec, 464 LVComputationKind computation) { 465 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 466 467 // Merge information from the template parameters, but ignore 468 // visibility if we're only considering template arguments. 469 ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 470 // Merge information from the template declaration. 471 LinkageInfo tempLV = getLVForDecl(temp, computation); 472 // The linkage of the specialization should be consistent with the 473 // template declaration. 474 LV.setLinkage(tempLV.getLinkage()); 475 476 LinkageInfo paramsLV = 477 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 478 LV.mergeMaybeWithVisibility(paramsLV, 479 considerVisibility && !hasExplicitVisibilityAlready(computation)); 480 481 // Merge information from the template arguments. We ignore 482 // template-argument visibility if we've got an explicit 483 // instantiation with a visibility attribute. 484 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 485 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 486 if (considerVisibility) 487 LV.mergeVisibility(argsLV); 488 LV.mergeExternalVisibility(argsLV); 489 } 490 491 /// Should we consider visibility associated with the template 492 /// arguments and parameters of the given variable template 493 /// specialization? As usual, follow class template specialization 494 /// logic up to initialization. 495 static bool shouldConsiderTemplateVisibility( 496 const VarTemplateSpecializationDecl *spec, 497 LVComputationKind computation) { 498 // Include visibility from the template parameters and arguments 499 // only if this is not an explicit instantiation or specialization 500 // with direct explicit visibility (and note that implicit 501 // instantiations won't have a direct attribute). 502 if (!spec->isExplicitInstantiationOrSpecialization()) 503 return true; 504 505 // An explicit variable specialization is an independent, top-level 506 // declaration. As such, if it has an explicit visibility attribute, 507 // that must directly express the user's intent, and we should honor 508 // it. 509 if (spec->isExplicitSpecialization() && 510 hasExplicitVisibilityAlready(computation)) 511 return false; 512 513 return !hasDirectVisibilityAttribute(spec, computation); 514 } 515 516 /// Merge in template-related linkage and visibility for the given 517 /// variable template specialization. As usual, follow class template 518 /// specialization logic up to initialization. 519 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV, 520 const VarTemplateSpecializationDecl *spec, 521 LVComputationKind computation) { 522 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 523 524 // Merge information from the template parameters, but ignore 525 // visibility if we're only considering template arguments. 526 VarTemplateDecl *temp = spec->getSpecializedTemplate(); 527 LinkageInfo tempLV = 528 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 529 LV.mergeMaybeWithVisibility(tempLV, 530 considerVisibility && !hasExplicitVisibilityAlready(computation)); 531 532 // Merge information from the template arguments. We ignore 533 // template-argument visibility if we've got an explicit 534 // instantiation with a visibility attribute. 535 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 536 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 537 if (considerVisibility) 538 LV.mergeVisibility(argsLV); 539 LV.mergeExternalVisibility(argsLV); 540 } 541 542 static bool useInlineVisibilityHidden(const NamedDecl *D) { 543 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 544 const LangOptions &Opts = D->getASTContext().getLangOpts(); 545 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 546 return false; 547 548 const auto *FD = dyn_cast<FunctionDecl>(D); 549 if (!FD) 550 return false; 551 552 TemplateSpecializationKind TSK = TSK_Undeclared; 553 if (FunctionTemplateSpecializationInfo *spec 554 = FD->getTemplateSpecializationInfo()) { 555 TSK = spec->getTemplateSpecializationKind(); 556 } else if (MemberSpecializationInfo *MSI = 557 FD->getMemberSpecializationInfo()) { 558 TSK = MSI->getTemplateSpecializationKind(); 559 } 560 561 const FunctionDecl *Def = nullptr; 562 // InlineVisibilityHidden only applies to definitions, and 563 // isInlined() only gives meaningful answers on definitions 564 // anyway. 565 return TSK != TSK_ExplicitInstantiationDeclaration && 566 TSK != TSK_ExplicitInstantiationDefinition && 567 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 568 } 569 570 template <typename T> static bool isFirstInExternCContext(T *D) { 571 const T *First = D->getFirstDecl(); 572 return First->isInExternCContext(); 573 } 574 575 static bool isSingleLineLanguageLinkage(const Decl &D) { 576 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext())) 577 if (!SD->hasBraces()) 578 return true; 579 return false; 580 } 581 582 static bool isDeclaredInModuleInterfaceOrPartition(const NamedDecl *D) { 583 if (auto *M = D->getOwningModule()) 584 return M->isInterfaceOrPartition(); 585 return false; 586 } 587 588 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) { 589 return LinkageInfo::external(); 590 } 591 592 static StorageClass getStorageClass(const Decl *D) { 593 if (auto *TD = dyn_cast<TemplateDecl>(D)) 594 D = TD->getTemplatedDecl(); 595 if (D) { 596 if (auto *VD = dyn_cast<VarDecl>(D)) 597 return VD->getStorageClass(); 598 if (auto *FD = dyn_cast<FunctionDecl>(D)) 599 return FD->getStorageClass(); 600 } 601 return SC_None; 602 } 603 604 LinkageInfo 605 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, 606 LVComputationKind computation, 607 bool IgnoreVarTypeLinkage) { 608 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 609 "Not a name having namespace scope"); 610 ASTContext &Context = D->getASTContext(); 611 612 // C++ [basic.link]p3: 613 // A name having namespace scope (3.3.6) has internal linkage if it 614 // is the name of 615 616 if (getStorageClass(D->getCanonicalDecl()) == SC_Static) { 617 // - a variable, variable template, function, or function template 618 // that is explicitly declared static; or 619 // (This bullet corresponds to C99 6.2.2p3.) 620 return LinkageInfo::internal(); 621 } 622 623 if (const auto *Var = dyn_cast<VarDecl>(D)) { 624 // - a non-template variable of non-volatile const-qualified type, unless 625 // - it is explicitly declared extern, or 626 // - it is declared in the purview of a module interface unit 627 // (outside the private-module-fragment, if any) or module partition, or 628 // - it is inline, or 629 // - it was previously declared and the prior declaration did not have 630 // internal linkage 631 // (There is no equivalent in C99.) 632 if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() && 633 !Var->getType().isVolatileQualified() && !Var->isInline() && 634 !isDeclaredInModuleInterfaceOrPartition(Var) && 635 !isa<VarTemplateSpecializationDecl>(Var) && 636 !Var->getDescribedVarTemplate()) { 637 const VarDecl *PrevVar = Var->getPreviousDecl(); 638 if (PrevVar) 639 return getLVForDecl(PrevVar, computation); 640 641 if (Var->getStorageClass() != SC_Extern && 642 Var->getStorageClass() != SC_PrivateExtern && 643 !isSingleLineLanguageLinkage(*Var)) 644 return LinkageInfo::internal(); 645 } 646 647 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; 648 PrevVar = PrevVar->getPreviousDecl()) { 649 if (PrevVar->getStorageClass() == SC_PrivateExtern && 650 Var->getStorageClass() == SC_None) 651 return getDeclLinkageAndVisibility(PrevVar); 652 // Explicitly declared static. 653 if (PrevVar->getStorageClass() == SC_Static) 654 return LinkageInfo::internal(); 655 } 656 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) { 657 // - a data member of an anonymous union. 658 const VarDecl *VD = IFD->getVarDecl(); 659 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); 660 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage); 661 } 662 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"); 663 664 // FIXME: This gives internal linkage to names that should have no linkage 665 // (those not covered by [basic.link]p6). 666 if (D->isInAnonymousNamespace()) { 667 const auto *Var = dyn_cast<VarDecl>(D); 668 const auto *Func = dyn_cast<FunctionDecl>(D); 669 // FIXME: The check for extern "C" here is not justified by the standard 670 // wording, but we retain it from the pre-DR1113 model to avoid breaking 671 // code. 672 // 673 // C++11 [basic.link]p4: 674 // An unnamed namespace or a namespace declared directly or indirectly 675 // within an unnamed namespace has internal linkage. 676 if ((!Var || !isFirstInExternCContext(Var)) && 677 (!Func || !isFirstInExternCContext(Func))) 678 return LinkageInfo::internal(); 679 } 680 681 // Set up the defaults. 682 683 // C99 6.2.2p5: 684 // If the declaration of an identifier for an object has file 685 // scope and no storage-class specifier, its linkage is 686 // external. 687 LinkageInfo LV = getExternalLinkageFor(D); 688 689 if (!hasExplicitVisibilityAlready(computation)) { 690 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) { 691 LV.mergeVisibility(*Vis, true); 692 } else { 693 // If we're declared in a namespace with a visibility attribute, 694 // use that namespace's visibility, and it still counts as explicit. 695 for (const DeclContext *DC = D->getDeclContext(); 696 !isa<TranslationUnitDecl>(DC); 697 DC = DC->getParent()) { 698 const auto *ND = dyn_cast<NamespaceDecl>(DC); 699 if (!ND) continue; 700 if (std::optional<Visibility> Vis = 701 getExplicitVisibility(ND, computation)) { 702 LV.mergeVisibility(*Vis, true); 703 break; 704 } 705 } 706 } 707 708 // Add in global settings if the above didn't give us direct visibility. 709 if (!LV.isVisibilityExplicit()) { 710 // Use global type/value visibility as appropriate. 711 Visibility globalVisibility = 712 computation.isValueVisibility() 713 ? Context.getLangOpts().getValueVisibilityMode() 714 : Context.getLangOpts().getTypeVisibilityMode(); 715 LV.mergeVisibility(globalVisibility, /*explicit*/ false); 716 717 // If we're paying attention to global visibility, apply 718 // -finline-visibility-hidden if this is an inline method. 719 if (useInlineVisibilityHidden(D)) 720 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false); 721 } 722 } 723 724 // C++ [basic.link]p4: 725 726 // A name having namespace scope that has not been given internal linkage 727 // above and that is the name of 728 // [...bullets...] 729 // has its linkage determined as follows: 730 // - if the enclosing namespace has internal linkage, the name has 731 // internal linkage; [handled above] 732 // - otherwise, if the declaration of the name is attached to a named 733 // module and is not exported, the name has module linkage; 734 // - otherwise, the name has external linkage. 735 // LV is currently set up to handle the last two bullets. 736 // 737 // The bullets are: 738 739 // - a variable; or 740 if (const auto *Var = dyn_cast<VarDecl>(D)) { 741 // GCC applies the following optimization to variables and static 742 // data members, but not to functions: 743 // 744 // Modify the variable's LV by the LV of its type unless this is 745 // C or extern "C". This follows from [basic.link]p9: 746 // A type without linkage shall not be used as the type of a 747 // variable or function with external linkage unless 748 // - the entity has C language linkage, or 749 // - the entity is declared within an unnamed namespace, or 750 // - the entity is not used or is defined in the same 751 // translation unit. 752 // and [basic.link]p10: 753 // ...the types specified by all declarations referring to a 754 // given variable or function shall be identical... 755 // C does not have an equivalent rule. 756 // 757 // Ignore this if we've got an explicit attribute; the user 758 // probably knows what they're doing. 759 // 760 // Note that we don't want to make the variable non-external 761 // because of this, but unique-external linkage suits us. 762 763 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) && 764 !IgnoreVarTypeLinkage) { 765 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation); 766 if (!isExternallyVisible(TypeLV.getLinkage())) 767 return LinkageInfo::uniqueExternal(); 768 if (!LV.isVisibilityExplicit()) 769 LV.mergeVisibility(TypeLV); 770 } 771 772 if (Var->getStorageClass() == SC_PrivateExtern) 773 LV.mergeVisibility(HiddenVisibility, true); 774 775 // Note that Sema::MergeVarDecl already takes care of implementing 776 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 777 // to do it here. 778 779 // As per function and class template specializations (below), 780 // consider LV for the template and template arguments. We're at file 781 // scope, so we do not need to worry about nested specializations. 782 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 783 mergeTemplateLV(LV, spec, computation); 784 } 785 786 // - a function; or 787 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 788 // In theory, we can modify the function's LV by the LV of its 789 // type unless it has C linkage (see comment above about variables 790 // for justification). In practice, GCC doesn't do this, so it's 791 // just too painful to make work. 792 793 if (Function->getStorageClass() == SC_PrivateExtern) 794 LV.mergeVisibility(HiddenVisibility, true); 795 796 // OpenMP target declare device functions are not callable from the host so 797 // they should not be exported from the device image. This applies to all 798 // functions as the host-callable kernel functions are emitted at codegen. 799 if (Context.getLangOpts().OpenMP && 800 Context.getLangOpts().OpenMPIsTargetDevice && 801 ((Context.getTargetInfo().getTriple().isAMDGPU() || 802 Context.getTargetInfo().getTriple().isNVPTX()) || 803 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function))) 804 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false); 805 806 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 807 // merging storage classes and visibility attributes, so we don't have to 808 // look at previous decls in here. 809 810 // In C++, then if the type of the function uses a type with 811 // unique-external linkage, it's not legally usable from outside 812 // this translation unit. However, we should use the C linkage 813 // rules instead for extern "C" declarations. 814 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) { 815 // Only look at the type-as-written. Otherwise, deducing the return type 816 // of a function could change its linkage. 817 QualType TypeAsWritten = Function->getType(); 818 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo()) 819 TypeAsWritten = TSI->getType(); 820 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 821 return LinkageInfo::uniqueExternal(); 822 } 823 824 // Consider LV from the template and the template arguments. 825 // We're at file scope, so we do not need to worry about nested 826 // specializations. 827 if (FunctionTemplateSpecializationInfo *specInfo 828 = Function->getTemplateSpecializationInfo()) { 829 mergeTemplateLV(LV, Function, specInfo, computation); 830 } 831 832 // - a named class (Clause 9), or an unnamed class defined in a 833 // typedef declaration in which the class has the typedef name 834 // for linkage purposes (7.1.3); or 835 // - a named enumeration (7.2), or an unnamed enumeration 836 // defined in a typedef declaration in which the enumeration 837 // has the typedef name for linkage purposes (7.1.3); or 838 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) { 839 // Unnamed tags have no linkage. 840 if (!Tag->hasNameForLinkage()) 841 return LinkageInfo::none(); 842 843 // If this is a class template specialization, consider the 844 // linkage of the template and template arguments. We're at file 845 // scope, so we do not need to worry about nested specializations. 846 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 847 mergeTemplateLV(LV, spec, computation); 848 } 849 850 // FIXME: This is not part of the C++ standard any more. 851 // - an enumerator belonging to an enumeration with external linkage; or 852 } else if (isa<EnumConstantDecl>(D)) { 853 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 854 computation); 855 if (!isExternalFormalLinkage(EnumLV.getLinkage())) 856 return LinkageInfo::none(); 857 LV.merge(EnumLV); 858 859 // - a template 860 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 861 bool considerVisibility = !hasExplicitVisibilityAlready(computation); 862 LinkageInfo tempLV = 863 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 864 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 865 866 // An unnamed namespace or a namespace declared directly or indirectly 867 // within an unnamed namespace has internal linkage. All other namespaces 868 // have external linkage. 869 // 870 // We handled names in anonymous namespaces above. 871 } else if (isa<NamespaceDecl>(D)) { 872 return LV; 873 874 // By extension, we assign external linkage to Objective-C 875 // interfaces. 876 } else if (isa<ObjCInterfaceDecl>(D)) { 877 // fallout 878 879 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 880 // A typedef declaration has linkage if it gives a type a name for 881 // linkage purposes. 882 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 883 return LinkageInfo::none(); 884 885 } else if (isa<MSGuidDecl>(D)) { 886 // A GUID behaves like an inline variable with external linkage. Fall 887 // through. 888 889 // Everything not covered here has no linkage. 890 } else { 891 return LinkageInfo::none(); 892 } 893 894 // If we ended up with non-externally-visible linkage, visibility should 895 // always be default. 896 if (!isExternallyVisible(LV.getLinkage())) 897 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); 898 899 return LV; 900 } 901 902 LinkageInfo 903 LinkageComputer::getLVForClassMember(const NamedDecl *D, 904 LVComputationKind computation, 905 bool IgnoreVarTypeLinkage) { 906 // Only certain class members have linkage. Note that fields don't 907 // really have linkage, but it's convenient to say they do for the 908 // purposes of calculating linkage of pointer-to-data-member 909 // template arguments. 910 // 911 // Templates also don't officially have linkage, but since we ignore 912 // the C++ standard and look at template arguments when determining 913 // linkage and visibility of a template specialization, we might hit 914 // a template template argument that way. If we do, we need to 915 // consider its linkage. 916 if (!(isa<CXXMethodDecl>(D) || 917 isa<VarDecl>(D) || 918 isa<FieldDecl>(D) || 919 isa<IndirectFieldDecl>(D) || 920 isa<TagDecl>(D) || 921 isa<TemplateDecl>(D))) 922 return LinkageInfo::none(); 923 924 LinkageInfo LV; 925 926 // If we have an explicit visibility attribute, merge that in. 927 if (!hasExplicitVisibilityAlready(computation)) { 928 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) 929 LV.mergeVisibility(*Vis, true); 930 // If we're paying attention to global visibility, apply 931 // -finline-visibility-hidden if this is an inline method. 932 // 933 // Note that we do this before merging information about 934 // the class visibility. 935 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) 936 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false); 937 } 938 939 // If this class member has an explicit visibility attribute, the only 940 // thing that can change its visibility is the template arguments, so 941 // only look for them when processing the class. 942 LVComputationKind classComputation = computation; 943 if (LV.isVisibilityExplicit()) 944 classComputation = withExplicitVisibilityAlready(computation); 945 946 LinkageInfo classLV = 947 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation); 948 // The member has the same linkage as the class. If that's not externally 949 // visible, we don't need to compute anything about the linkage. 950 // FIXME: If we're only computing linkage, can we bail out here? 951 if (!isExternallyVisible(classLV.getLinkage())) 952 return classLV; 953 954 955 // Otherwise, don't merge in classLV yet, because in certain cases 956 // we need to completely ignore the visibility from it. 957 958 // Specifically, if this decl exists and has an explicit attribute. 959 const NamedDecl *explicitSpecSuppressor = nullptr; 960 961 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 962 // Only look at the type-as-written. Otherwise, deducing the return type 963 // of a function could change its linkage. 964 QualType TypeAsWritten = MD->getType(); 965 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 966 TypeAsWritten = TSI->getType(); 967 if (!isExternallyVisible(TypeAsWritten->getLinkage())) 968 return LinkageInfo::uniqueExternal(); 969 970 // If this is a method template specialization, use the linkage for 971 // the template parameters and arguments. 972 if (FunctionTemplateSpecializationInfo *spec 973 = MD->getTemplateSpecializationInfo()) { 974 mergeTemplateLV(LV, MD, spec, computation); 975 if (spec->isExplicitSpecialization()) { 976 explicitSpecSuppressor = MD; 977 } else if (isExplicitMemberSpecialization(spec->getTemplate())) { 978 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); 979 } 980 } else if (isExplicitMemberSpecialization(MD)) { 981 explicitSpecSuppressor = MD; 982 } 983 984 // OpenMP target declare device functions are not callable from the host so 985 // they should not be exported from the device image. This applies to all 986 // functions as the host-callable kernel functions are emitted at codegen. 987 ASTContext &Context = D->getASTContext(); 988 if (Context.getLangOpts().OpenMP && 989 Context.getLangOpts().OpenMPIsTargetDevice && 990 ((Context.getTargetInfo().getTriple().isAMDGPU() || 991 Context.getTargetInfo().getTriple().isNVPTX()) || 992 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD))) 993 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false); 994 995 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { 996 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 997 mergeTemplateLV(LV, spec, computation); 998 if (spec->isExplicitSpecialization()) { 999 explicitSpecSuppressor = spec; 1000 } else { 1001 const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 1002 if (isExplicitMemberSpecialization(temp)) { 1003 explicitSpecSuppressor = temp->getTemplatedDecl(); 1004 } 1005 } 1006 } else if (isExplicitMemberSpecialization(RD)) { 1007 explicitSpecSuppressor = RD; 1008 } 1009 1010 // Static data members. 1011 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 1012 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD)) 1013 mergeTemplateLV(LV, spec, computation); 1014 1015 // Modify the variable's linkage by its type, but ignore the 1016 // type's visibility unless it's a definition. 1017 if (!IgnoreVarTypeLinkage) { 1018 LinkageInfo typeLV = getLVForType(*VD->getType(), computation); 1019 // FIXME: If the type's linkage is not externally visible, we can 1020 // give this static data member UniqueExternalLinkage. 1021 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()) 1022 LV.mergeVisibility(typeLV); 1023 LV.mergeExternalVisibility(typeLV); 1024 } 1025 1026 if (isExplicitMemberSpecialization(VD)) { 1027 explicitSpecSuppressor = VD; 1028 } 1029 1030 // Template members. 1031 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) { 1032 bool considerVisibility = 1033 (!LV.isVisibilityExplicit() && 1034 !classLV.isVisibilityExplicit() && 1035 !hasExplicitVisibilityAlready(computation)); 1036 LinkageInfo tempLV = 1037 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 1038 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 1039 1040 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) { 1041 if (isExplicitMemberSpecialization(redeclTemp)) { 1042 explicitSpecSuppressor = temp->getTemplatedDecl(); 1043 } 1044 } 1045 } 1046 1047 // We should never be looking for an attribute directly on a template. 1048 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); 1049 1050 // If this member is an explicit member specialization, and it has 1051 // an explicit attribute, ignore visibility from the parent. 1052 bool considerClassVisibility = true; 1053 if (explicitSpecSuppressor && 1054 // optimization: hasDVA() is true only with explicit visibility. 1055 LV.isVisibilityExplicit() && 1056 classLV.getVisibility() != DefaultVisibility && 1057 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) { 1058 considerClassVisibility = false; 1059 } 1060 1061 // Finally, merge in information from the class. 1062 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility); 1063 return LV; 1064 } 1065 1066 void NamedDecl::anchor() {} 1067 1068 bool NamedDecl::isLinkageValid() const { 1069 if (!hasCachedLinkage()) 1070 return true; 1071 1072 Linkage L = LinkageComputer{} 1073 .computeLVForDecl(this, LVComputationKind::forLinkageOnly()) 1074 .getLinkage(); 1075 return L == getCachedLinkage(); 1076 } 1077 1078 bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const { 1079 // [C++2c] [basic.scope.scope]/p5 1080 // A declaration is name-independent if its name is _ and it declares 1081 // - a variable with automatic storage duration, 1082 // - a structured binding not inhabiting a namespace scope, 1083 // - the variable introduced by an init-capture 1084 // - or a non-static data member. 1085 1086 if (!LangOpts.CPlusPlus || !getIdentifier() || 1087 !getIdentifier()->isPlaceholder()) 1088 return false; 1089 if (isa<FieldDecl>(this)) 1090 return true; 1091 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) { 1092 if (!getDeclContext()->isFunctionOrMethod() && 1093 !getDeclContext()->isRecord()) 1094 return false; 1095 const VarDecl *VD = IFD->getVarDecl(); 1096 return !VD || VD->getStorageDuration() == SD_Automatic; 1097 } 1098 // and it declares a variable with automatic storage duration 1099 if (const auto *VD = dyn_cast<VarDecl>(this)) { 1100 if (isa<ParmVarDecl>(VD)) 1101 return false; 1102 if (VD->isInitCapture()) 1103 return true; 1104 return VD->getStorageDuration() == StorageDuration::SD_Automatic; 1105 } 1106 if (const auto *BD = dyn_cast<BindingDecl>(this); 1107 BD && getDeclContext()->isFunctionOrMethod()) { 1108 const VarDecl *VD = BD->getHoldingVar(); 1109 return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic; 1110 } 1111 return false; 1112 } 1113 1114 ReservedIdentifierStatus 1115 NamedDecl::isReserved(const LangOptions &LangOpts) const { 1116 const IdentifierInfo *II = getIdentifier(); 1117 1118 // This triggers at least for CXXLiteralIdentifiers, which we already checked 1119 // at lexing time. 1120 if (!II) 1121 return ReservedIdentifierStatus::NotReserved; 1122 1123 ReservedIdentifierStatus Status = II->isReserved(LangOpts); 1124 if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) { 1125 // This name is only reserved at global scope. Check if this declaration 1126 // conflicts with a global scope declaration. 1127 if (isa<ParmVarDecl>(this) || isTemplateParameter()) 1128 return ReservedIdentifierStatus::NotReserved; 1129 1130 // C++ [dcl.link]/7: 1131 // Two declarations [conflict] if [...] one declares a function or 1132 // variable with C language linkage, and the other declares [...] a 1133 // variable that belongs to the global scope. 1134 // 1135 // Therefore names that are reserved at global scope are also reserved as 1136 // names of variables and functions with C language linkage. 1137 const DeclContext *DC = getDeclContext()->getRedeclContext(); 1138 if (DC->isTranslationUnit()) 1139 return Status; 1140 if (auto *VD = dyn_cast<VarDecl>(this)) 1141 if (VD->isExternC()) 1142 return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; 1143 if (auto *FD = dyn_cast<FunctionDecl>(this)) 1144 if (FD->isExternC()) 1145 return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC; 1146 return ReservedIdentifierStatus::NotReserved; 1147 } 1148 1149 return Status; 1150 } 1151 1152 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { 1153 StringRef name = getName(); 1154 if (name.empty()) return SFF_None; 1155 1156 if (name.front() == 'C') 1157 if (name == "CFStringCreateWithFormat" || 1158 name == "CFStringCreateWithFormatAndArguments" || 1159 name == "CFStringAppendFormat" || 1160 name == "CFStringAppendFormatAndArguments") 1161 return SFF_CFString; 1162 return SFF_None; 1163 } 1164 1165 Linkage NamedDecl::getLinkageInternal() const { 1166 // We don't care about visibility here, so ask for the cheapest 1167 // possible visibility analysis. 1168 return LinkageComputer{} 1169 .getLVForDecl(this, LVComputationKind::forLinkageOnly()) 1170 .getLinkage(); 1171 } 1172 1173 /// Determine whether D is attached to a named module. 1174 static bool isInNamedModule(const NamedDecl *D) { 1175 if (auto *M = D->getOwningModule()) 1176 return M->isNamedModule(); 1177 return false; 1178 } 1179 1180 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) { 1181 // FIXME: Handle isModulePrivate. 1182 switch (D->getModuleOwnershipKind()) { 1183 case Decl::ModuleOwnershipKind::Unowned: 1184 case Decl::ModuleOwnershipKind::ReachableWhenImported: 1185 case Decl::ModuleOwnershipKind::ModulePrivate: 1186 return false; 1187 case Decl::ModuleOwnershipKind::Visible: 1188 case Decl::ModuleOwnershipKind::VisibleWhenImported: 1189 return isInNamedModule(D); 1190 } 1191 llvm_unreachable("unexpected module ownership kind"); 1192 } 1193 1194 /// Get the linkage from a semantic point of view. Entities in 1195 /// anonymous namespaces are external (in c++98). 1196 Linkage NamedDecl::getFormalLinkage() const { 1197 Linkage InternalLinkage = getLinkageInternal(); 1198 1199 // C++ [basic.link]p4.8: 1200 // - if the declaration of the name is attached to a named module and is not 1201 // exported 1202 // the name has module linkage; 1203 // 1204 // [basic.namespace.general]/p2 1205 // A namespace is never attached to a named module and never has a name with 1206 // module linkage. 1207 if (isInNamedModule(this) && InternalLinkage == Linkage::External && 1208 !isExportedFromModuleInterfaceUnit( 1209 cast<NamedDecl>(this->getCanonicalDecl())) && 1210 !isa<NamespaceDecl>(this)) 1211 InternalLinkage = Linkage::Module; 1212 1213 return clang::getFormalLinkage(InternalLinkage); 1214 } 1215 1216 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 1217 return LinkageComputer{}.getDeclLinkageAndVisibility(this); 1218 } 1219 1220 static std::optional<Visibility> 1221 getExplicitVisibilityAux(const NamedDecl *ND, 1222 NamedDecl::ExplicitVisibilityKind kind, 1223 bool IsMostRecent) { 1224 assert(!IsMostRecent || ND == ND->getMostRecentDecl()); 1225 1226 // Check the declaration itself first. 1227 if (std::optional<Visibility> V = getVisibilityOf(ND, kind)) 1228 return V; 1229 1230 // If this is a member class of a specialization of a class template 1231 // and the corresponding decl has explicit visibility, use that. 1232 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 1233 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 1234 if (InstantiatedFrom) 1235 return getVisibilityOf(InstantiatedFrom, kind); 1236 } 1237 1238 // If there wasn't explicit visibility there, and this is a 1239 // specialization of a class template, check for visibility 1240 // on the pattern. 1241 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 1242 // Walk all the template decl till this point to see if there are 1243 // explicit visibility attributes. 1244 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl(); 1245 while (TD != nullptr) { 1246 auto Vis = getVisibilityOf(TD, kind); 1247 if (Vis != std::nullopt) 1248 return Vis; 1249 TD = TD->getPreviousDecl(); 1250 } 1251 return std::nullopt; 1252 } 1253 1254 // Use the most recent declaration. 1255 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) { 1256 const NamedDecl *MostRecent = ND->getMostRecentDecl(); 1257 if (MostRecent != ND) 1258 return getExplicitVisibilityAux(MostRecent, kind, true); 1259 } 1260 1261 if (const auto *Var = dyn_cast<VarDecl>(ND)) { 1262 if (Var->isStaticDataMember()) { 1263 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 1264 if (InstantiatedFrom) 1265 return getVisibilityOf(InstantiatedFrom, kind); 1266 } 1267 1268 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var)) 1269 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), 1270 kind); 1271 1272 return std::nullopt; 1273 } 1274 // Also handle function template specializations. 1275 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) { 1276 // If the function is a specialization of a template with an 1277 // explicit visibility attribute, use that. 1278 if (FunctionTemplateSpecializationInfo *templateInfo 1279 = fn->getTemplateSpecializationInfo()) 1280 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), 1281 kind); 1282 1283 // If the function is a member of a specialization of a class template 1284 // and the corresponding decl has explicit visibility, use that. 1285 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 1286 if (InstantiatedFrom) 1287 return getVisibilityOf(InstantiatedFrom, kind); 1288 1289 return std::nullopt; 1290 } 1291 1292 // The visibility of a template is stored in the templated decl. 1293 if (const auto *TD = dyn_cast<TemplateDecl>(ND)) 1294 return getVisibilityOf(TD->getTemplatedDecl(), kind); 1295 1296 return std::nullopt; 1297 } 1298 1299 std::optional<Visibility> 1300 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { 1301 return getExplicitVisibilityAux(this, kind, false); 1302 } 1303 1304 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC, 1305 Decl *ContextDecl, 1306 LVComputationKind computation) { 1307 // This lambda has its linkage/visibility determined by its owner. 1308 const NamedDecl *Owner; 1309 if (!ContextDecl) 1310 Owner = dyn_cast<NamedDecl>(DC); 1311 else if (isa<ParmVarDecl>(ContextDecl)) 1312 Owner = 1313 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext()); 1314 else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) { 1315 // Replace with the concept's owning decl, which is either a namespace or a 1316 // TU, so this needs a dyn_cast. 1317 Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext()); 1318 } else { 1319 Owner = cast<NamedDecl>(ContextDecl); 1320 } 1321 1322 if (!Owner) 1323 return LinkageInfo::none(); 1324 1325 // If the owner has a deduced type, we need to skip querying the linkage and 1326 // visibility of that type, because it might involve this closure type. The 1327 // only effect of this is that we might give a lambda VisibleNoLinkage rather 1328 // than NoLinkage when we don't strictly need to, which is benign. 1329 auto *VD = dyn_cast<VarDecl>(Owner); 1330 LinkageInfo OwnerLV = 1331 VD && VD->getType()->getContainedDeducedType() 1332 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true) 1333 : getLVForDecl(Owner, computation); 1334 1335 // A lambda never formally has linkage. But if the owner is externally 1336 // visible, then the lambda is too. We apply the same rules to blocks. 1337 if (!isExternallyVisible(OwnerLV.getLinkage())) 1338 return LinkageInfo::none(); 1339 return LinkageInfo(Linkage::VisibleNone, OwnerLV.getVisibility(), 1340 OwnerLV.isVisibilityExplicit()); 1341 } 1342 1343 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, 1344 LVComputationKind computation) { 1345 if (const auto *Function = dyn_cast<FunctionDecl>(D)) { 1346 if (Function->isInAnonymousNamespace() && 1347 !isFirstInExternCContext(Function)) 1348 return LinkageInfo::internal(); 1349 1350 // This is a "void f();" which got merged with a file static. 1351 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 1352 return LinkageInfo::internal(); 1353 1354 LinkageInfo LV; 1355 if (!hasExplicitVisibilityAlready(computation)) { 1356 if (std::optional<Visibility> Vis = 1357 getExplicitVisibility(Function, computation)) 1358 LV.mergeVisibility(*Vis, true); 1359 } 1360 1361 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 1362 // merging storage classes and visibility attributes, so we don't have to 1363 // look at previous decls in here. 1364 1365 return LV; 1366 } 1367 1368 if (const auto *Var = dyn_cast<VarDecl>(D)) { 1369 if (Var->hasExternalStorage()) { 1370 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var)) 1371 return LinkageInfo::internal(); 1372 1373 LinkageInfo LV; 1374 if (Var->getStorageClass() == SC_PrivateExtern) 1375 LV.mergeVisibility(HiddenVisibility, true); 1376 else if (!hasExplicitVisibilityAlready(computation)) { 1377 if (std::optional<Visibility> Vis = 1378 getExplicitVisibility(Var, computation)) 1379 LV.mergeVisibility(*Vis, true); 1380 } 1381 1382 if (const VarDecl *Prev = Var->getPreviousDecl()) { 1383 LinkageInfo PrevLV = getLVForDecl(Prev, computation); 1384 if (PrevLV.getLinkage() != Linkage::Invalid) 1385 LV.setLinkage(PrevLV.getLinkage()); 1386 LV.mergeVisibility(PrevLV); 1387 } 1388 1389 return LV; 1390 } 1391 1392 if (!Var->isStaticLocal()) 1393 return LinkageInfo::none(); 1394 } 1395 1396 ASTContext &Context = D->getASTContext(); 1397 if (!Context.getLangOpts().CPlusPlus) 1398 return LinkageInfo::none(); 1399 1400 const Decl *OuterD = getOutermostFuncOrBlockContext(D); 1401 if (!OuterD || OuterD->isInvalidDecl()) 1402 return LinkageInfo::none(); 1403 1404 LinkageInfo LV; 1405 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) { 1406 if (!BD->getBlockManglingNumber()) 1407 return LinkageInfo::none(); 1408 1409 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(), 1410 BD->getBlockManglingContextDecl(), computation); 1411 } else { 1412 const auto *FD = cast<FunctionDecl>(OuterD); 1413 if (!FD->isInlined() && 1414 !isTemplateInstantiation(FD->getTemplateSpecializationKind())) 1415 return LinkageInfo::none(); 1416 1417 // If a function is hidden by -fvisibility-inlines-hidden option and 1418 // is not explicitly attributed as a hidden function, 1419 // we should not make static local variables in the function hidden. 1420 LV = getLVForDecl(FD, computation); 1421 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) && 1422 !LV.isVisibilityExplicit() && 1423 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) { 1424 assert(cast<VarDecl>(D)->isStaticLocal()); 1425 // If this was an implicitly hidden inline method, check again for 1426 // explicit visibility on the parent class, and use that for static locals 1427 // if present. 1428 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1429 LV = getLVForDecl(MD->getParent(), computation); 1430 if (!LV.isVisibilityExplicit()) { 1431 Visibility globalVisibility = 1432 computation.isValueVisibility() 1433 ? Context.getLangOpts().getValueVisibilityMode() 1434 : Context.getLangOpts().getTypeVisibilityMode(); 1435 return LinkageInfo(Linkage::VisibleNone, globalVisibility, 1436 /*visibilityExplicit=*/false); 1437 } 1438 } 1439 } 1440 if (!isExternallyVisible(LV.getLinkage())) 1441 return LinkageInfo::none(); 1442 return LinkageInfo(Linkage::VisibleNone, LV.getVisibility(), 1443 LV.isVisibilityExplicit()); 1444 } 1445 1446 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, 1447 LVComputationKind computation, 1448 bool IgnoreVarTypeLinkage) { 1449 // Internal_linkage attribute overrides other considerations. 1450 if (D->hasAttr<InternalLinkageAttr>()) 1451 return LinkageInfo::internal(); 1452 1453 // Objective-C: treat all Objective-C declarations as having external 1454 // linkage. 1455 switch (D->getKind()) { 1456 default: 1457 break; 1458 1459 // Per C++ [basic.link]p2, only the names of objects, references, 1460 // functions, types, templates, namespaces, and values ever have linkage. 1461 // 1462 // Note that the name of a typedef, namespace alias, using declaration, 1463 // and so on are not the name of the corresponding type, namespace, or 1464 // declaration, so they do *not* have linkage. 1465 case Decl::ImplicitParam: 1466 case Decl::Label: 1467 case Decl::NamespaceAlias: 1468 case Decl::ParmVar: 1469 case Decl::Using: 1470 case Decl::UsingEnum: 1471 case Decl::UsingShadow: 1472 case Decl::UsingDirective: 1473 return LinkageInfo::none(); 1474 1475 case Decl::EnumConstant: 1476 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. 1477 if (D->getASTContext().getLangOpts().CPlusPlus) 1478 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation); 1479 return LinkageInfo::visible_none(); 1480 1481 case Decl::Typedef: 1482 case Decl::TypeAlias: 1483 // A typedef declaration has linkage if it gives a type a name for 1484 // linkage purposes. 1485 if (!cast<TypedefNameDecl>(D) 1486 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) 1487 return LinkageInfo::none(); 1488 break; 1489 1490 case Decl::TemplateTemplateParm: // count these as external 1491 case Decl::NonTypeTemplateParm: 1492 case Decl::ObjCAtDefsField: 1493 case Decl::ObjCCategory: 1494 case Decl::ObjCCategoryImpl: 1495 case Decl::ObjCCompatibleAlias: 1496 case Decl::ObjCImplementation: 1497 case Decl::ObjCMethod: 1498 case Decl::ObjCProperty: 1499 case Decl::ObjCPropertyImpl: 1500 case Decl::ObjCProtocol: 1501 return getExternalLinkageFor(D); 1502 1503 case Decl::CXXRecord: { 1504 const auto *Record = cast<CXXRecordDecl>(D); 1505 if (Record->isLambda()) { 1506 if (Record->hasKnownLambdaInternalLinkage() || 1507 !Record->getLambdaManglingNumber()) { 1508 // This lambda has no mangling number, so it's internal. 1509 return LinkageInfo::internal(); 1510 } 1511 1512 return getLVForClosure( 1513 Record->getDeclContext()->getRedeclContext(), 1514 Record->getLambdaContextDecl(), computation); 1515 } 1516 1517 break; 1518 } 1519 1520 case Decl::TemplateParamObject: { 1521 // The template parameter object can be referenced from anywhere its type 1522 // and value can be referenced. 1523 auto *TPO = cast<TemplateParamObjectDecl>(D); 1524 LinkageInfo LV = getLVForType(*TPO->getType(), computation); 1525 LV.merge(getLVForValue(TPO->getValue(), computation)); 1526 return LV; 1527 } 1528 } 1529 1530 // Handle linkage for namespace-scope names. 1531 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 1532 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); 1533 1534 // C++ [basic.link]p5: 1535 // In addition, a member function, static data member, a named 1536 // class or enumeration of class scope, or an unnamed class or 1537 // enumeration defined in a class-scope typedef declaration such 1538 // that the class or enumeration has the typedef name for linkage 1539 // purposes (7.1.3), has external linkage if the name of the class 1540 // has external linkage. 1541 if (D->getDeclContext()->isRecord()) 1542 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage); 1543 1544 // C++ [basic.link]p6: 1545 // The name of a function declared in block scope and the name of 1546 // an object declared by a block scope extern declaration have 1547 // linkage. If there is a visible declaration of an entity with 1548 // linkage having the same name and type, ignoring entities 1549 // declared outside the innermost enclosing namespace scope, the 1550 // block scope declaration declares that same entity and receives 1551 // the linkage of the previous declaration. If there is more than 1552 // one such matching entity, the program is ill-formed. Otherwise, 1553 // if no matching entity is found, the block scope entity receives 1554 // external linkage. 1555 if (D->getDeclContext()->isFunctionOrMethod()) 1556 return getLVForLocalDecl(D, computation); 1557 1558 // C++ [basic.link]p6: 1559 // Names not covered by these rules have no linkage. 1560 return LinkageInfo::none(); 1561 } 1562 1563 /// getLVForDecl - Get the linkage and visibility for the given declaration. 1564 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, 1565 LVComputationKind computation) { 1566 // Internal_linkage attribute overrides other considerations. 1567 if (D->hasAttr<InternalLinkageAttr>()) 1568 return LinkageInfo::internal(); 1569 1570 if (computation.IgnoreAllVisibility && D->hasCachedLinkage()) 1571 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); 1572 1573 if (std::optional<LinkageInfo> LI = lookup(D, computation)) 1574 return *LI; 1575 1576 LinkageInfo LV = computeLVForDecl(D, computation); 1577 if (D->hasCachedLinkage()) 1578 assert(D->getCachedLinkage() == LV.getLinkage()); 1579 1580 D->setCachedLinkage(LV.getLinkage()); 1581 cache(D, computation, LV); 1582 1583 #ifndef NDEBUG 1584 // In C (because of gnu inline) and in c++ with microsoft extensions an 1585 // static can follow an extern, so we can have two decls with different 1586 // linkages. 1587 const LangOptions &Opts = D->getASTContext().getLangOpts(); 1588 if (!Opts.CPlusPlus || Opts.MicrosoftExt) 1589 return LV; 1590 1591 // We have just computed the linkage for this decl. By induction we know 1592 // that all other computed linkages match, check that the one we just 1593 // computed also does. 1594 NamedDecl *Old = nullptr; 1595 for (auto *I : D->redecls()) { 1596 auto *T = cast<NamedDecl>(I); 1597 if (T == D) 1598 continue; 1599 if (!T->isInvalidDecl() && T->hasCachedLinkage()) { 1600 Old = T; 1601 break; 1602 } 1603 } 1604 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage()); 1605 #endif 1606 1607 return LV; 1608 } 1609 1610 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) { 1611 NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D) 1612 ? NamedDecl::VisibilityForType 1613 : NamedDecl::VisibilityForValue; 1614 LVComputationKind CK(EK); 1615 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility 1616 ? CK.forLinkageOnly() 1617 : CK); 1618 } 1619 1620 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const { 1621 if (isa<NamespaceDecl>(this)) 1622 // Namespaces never have module linkage. It is the entities within them 1623 // that [may] do. 1624 return nullptr; 1625 1626 Module *M = getOwningModule(); 1627 if (!M) 1628 return nullptr; 1629 1630 switch (M->Kind) { 1631 case Module::ModuleMapModule: 1632 // Module map modules have no special linkage semantics. 1633 return nullptr; 1634 1635 case Module::ModuleInterfaceUnit: 1636 case Module::ModuleImplementationUnit: 1637 case Module::ModulePartitionInterface: 1638 case Module::ModulePartitionImplementation: 1639 return M; 1640 1641 case Module::ModuleHeaderUnit: 1642 case Module::ExplicitGlobalModuleFragment: 1643 case Module::ImplicitGlobalModuleFragment: { 1644 // External linkage declarations in the global module have no owning module 1645 // for linkage purposes. But internal linkage declarations in the global 1646 // module fragment of a particular module are owned by that module for 1647 // linkage purposes. 1648 // FIXME: p1815 removes the need for this distinction -- there are no 1649 // internal linkage declarations that need to be referred to from outside 1650 // this TU. 1651 if (IgnoreLinkage) 1652 return nullptr; 1653 bool InternalLinkage; 1654 if (auto *ND = dyn_cast<NamedDecl>(this)) 1655 InternalLinkage = !ND->hasExternalFormalLinkage(); 1656 else 1657 InternalLinkage = isInAnonymousNamespace(); 1658 return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : M->Parent 1659 : nullptr; 1660 } 1661 1662 case Module::PrivateModuleFragment: 1663 // The private module fragment is part of its containing module for linkage 1664 // purposes. 1665 return M->Parent; 1666 } 1667 1668 llvm_unreachable("unknown module kind"); 1669 } 1670 1671 void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 1672 Name.print(OS, Policy); 1673 } 1674 1675 void NamedDecl::printName(raw_ostream &OS) const { 1676 printName(OS, getASTContext().getPrintingPolicy()); 1677 } 1678 1679 std::string NamedDecl::getQualifiedNameAsString() const { 1680 std::string QualName; 1681 llvm::raw_string_ostream OS(QualName); 1682 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1683 return QualName; 1684 } 1685 1686 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1687 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1688 } 1689 1690 void NamedDecl::printQualifiedName(raw_ostream &OS, 1691 const PrintingPolicy &P) const { 1692 if (getDeclContext()->isFunctionOrMethod()) { 1693 // We do not print '(anonymous)' for function parameters without name. 1694 printName(OS, P); 1695 return; 1696 } 1697 printNestedNameSpecifier(OS, P); 1698 if (getDeclName()) 1699 OS << *this; 1700 else { 1701 // Give the printName override a chance to pick a different name before we 1702 // fall back to "(anonymous)". 1703 SmallString<64> NameBuffer; 1704 llvm::raw_svector_ostream NameOS(NameBuffer); 1705 printName(NameOS, P); 1706 if (NameBuffer.empty()) 1707 OS << "(anonymous)"; 1708 else 1709 OS << NameBuffer; 1710 } 1711 } 1712 1713 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const { 1714 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy()); 1715 } 1716 1717 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS, 1718 const PrintingPolicy &P) const { 1719 const DeclContext *Ctx = getDeclContext(); 1720 1721 // For ObjC methods and properties, look through categories and use the 1722 // interface as context. 1723 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) { 1724 if (auto *ID = MD->getClassInterface()) 1725 Ctx = ID; 1726 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) { 1727 if (auto *MD = PD->getGetterMethodDecl()) 1728 if (auto *ID = MD->getClassInterface()) 1729 Ctx = ID; 1730 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) { 1731 if (auto *CI = ID->getContainingInterface()) 1732 Ctx = CI; 1733 } 1734 1735 if (Ctx->isFunctionOrMethod()) 1736 return; 1737 1738 using ContextsTy = SmallVector<const DeclContext *, 8>; 1739 ContextsTy Contexts; 1740 1741 // Collect named contexts. 1742 DeclarationName NameInScope = getDeclName(); 1743 for (; Ctx; Ctx = Ctx->getParent()) { 1744 // Suppress anonymous namespace if requested. 1745 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) && 1746 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace()) 1747 continue; 1748 1749 // Suppress inline namespace if it doesn't make the result ambiguous. 1750 if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope && 1751 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope)) 1752 continue; 1753 1754 // Skip non-named contexts such as linkage specifications and ExportDecls. 1755 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx); 1756 if (!ND) 1757 continue; 1758 1759 Contexts.push_back(Ctx); 1760 NameInScope = ND->getDeclName(); 1761 } 1762 1763 for (const DeclContext *DC : llvm::reverse(Contexts)) { 1764 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1765 OS << Spec->getName(); 1766 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1767 printTemplateArgumentList( 1768 OS, TemplateArgs.asArray(), P, 1769 Spec->getSpecializedTemplate()->getTemplateParameters()); 1770 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 1771 if (ND->isAnonymousNamespace()) { 1772 OS << (P.MSVCFormatting ? "`anonymous namespace\'" 1773 : "(anonymous namespace)"); 1774 } 1775 else 1776 OS << *ND; 1777 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { 1778 if (!RD->getIdentifier()) 1779 OS << "(anonymous " << RD->getKindName() << ')'; 1780 else 1781 OS << *RD; 1782 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1783 const FunctionProtoType *FT = nullptr; 1784 if (FD->hasWrittenPrototype()) 1785 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1786 1787 OS << *FD << '('; 1788 if (FT) { 1789 unsigned NumParams = FD->getNumParams(); 1790 for (unsigned i = 0; i < NumParams; ++i) { 1791 if (i) 1792 OS << ", "; 1793 OS << FD->getParamDecl(i)->getType().stream(P); 1794 } 1795 1796 if (FT->isVariadic()) { 1797 if (NumParams > 0) 1798 OS << ", "; 1799 OS << "..."; 1800 } 1801 } 1802 OS << ')'; 1803 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) { 1804 // C++ [dcl.enum]p10: Each enum-name and each unscoped 1805 // enumerator is declared in the scope that immediately contains 1806 // the enum-specifier. Each scoped enumerator is declared in the 1807 // scope of the enumeration. 1808 // For the case of unscoped enumerator, do not include in the qualified 1809 // name any information about its enum enclosing scope, as its visibility 1810 // is global. 1811 if (ED->isScoped()) 1812 OS << *ED; 1813 else 1814 continue; 1815 } else { 1816 OS << *cast<NamedDecl>(DC); 1817 } 1818 OS << "::"; 1819 } 1820 } 1821 1822 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1823 const PrintingPolicy &Policy, 1824 bool Qualified) const { 1825 if (Qualified) 1826 printQualifiedName(OS, Policy); 1827 else 1828 printName(OS, Policy); 1829 } 1830 1831 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1832 return true; 1833 } 1834 static bool isRedeclarableImpl(...) { return false; } 1835 static bool isRedeclarable(Decl::Kind K) { 1836 switch (K) { 1837 #define DECL(Type, Base) \ 1838 case Decl::Type: \ 1839 return isRedeclarableImpl((Type##Decl *)nullptr); 1840 #define ABSTRACT_DECL(DECL) 1841 #include "clang/AST/DeclNodes.inc" 1842 } 1843 llvm_unreachable("unknown decl kind"); 1844 } 1845 1846 bool NamedDecl::declarationReplaces(const NamedDecl *OldD, 1847 bool IsKnownNewer) const { 1848 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1849 1850 // Never replace one imported declaration with another; we need both results 1851 // when re-exporting. 1852 if (OldD->isFromASTFile() && isFromASTFile()) 1853 return false; 1854 1855 // A kind mismatch implies that the declaration is not replaced. 1856 if (OldD->getKind() != getKind()) 1857 return false; 1858 1859 // For method declarations, we never replace. (Why?) 1860 if (isa<ObjCMethodDecl>(this)) 1861 return false; 1862 1863 // For parameters, pick the newer one. This is either an error or (in 1864 // Objective-C) permitted as an extension. 1865 if (isa<ParmVarDecl>(this)) 1866 return true; 1867 1868 // Inline namespaces can give us two declarations with the same 1869 // name and kind in the same scope but different contexts; we should 1870 // keep both declarations in this case. 1871 if (!this->getDeclContext()->getRedeclContext()->Equals( 1872 OldD->getDeclContext()->getRedeclContext())) 1873 return false; 1874 1875 // Using declarations can be replaced if they import the same name from the 1876 // same context. 1877 if (const auto *UD = dyn_cast<UsingDecl>(this)) { 1878 ASTContext &Context = getASTContext(); 1879 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1880 Context.getCanonicalNestedNameSpecifier( 1881 cast<UsingDecl>(OldD)->getQualifier()); 1882 } 1883 if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1884 ASTContext &Context = getASTContext(); 1885 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1886 Context.getCanonicalNestedNameSpecifier( 1887 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1888 } 1889 1890 if (isRedeclarable(getKind())) { 1891 if (getCanonicalDecl() != OldD->getCanonicalDecl()) 1892 return false; 1893 1894 if (IsKnownNewer) 1895 return true; 1896 1897 // Check whether this is actually newer than OldD. We want to keep the 1898 // newer declaration. This loop will usually only iterate once, because 1899 // OldD is usually the previous declaration. 1900 for (const auto *D : redecls()) { 1901 if (D == OldD) 1902 break; 1903 1904 // If we reach the canonical declaration, then OldD is not actually older 1905 // than this one. 1906 // 1907 // FIXME: In this case, we should not add this decl to the lookup table. 1908 if (D->isCanonicalDecl()) 1909 return false; 1910 } 1911 1912 // It's a newer declaration of the same kind of declaration in the same 1913 // scope: we want this decl instead of the existing one. 1914 return true; 1915 } 1916 1917 // In all other cases, we need to keep both declarations in case they have 1918 // different visibility. Any attempt to use the name will result in an 1919 // ambiguity if more than one is visible. 1920 return false; 1921 } 1922 1923 bool NamedDecl::hasLinkage() const { 1924 switch (getFormalLinkage()) { 1925 case Linkage::Invalid: 1926 llvm_unreachable("Linkage hasn't been computed!"); 1927 case Linkage::None: 1928 return false; 1929 case Linkage::Internal: 1930 return true; 1931 case Linkage::UniqueExternal: 1932 case Linkage::VisibleNone: 1933 llvm_unreachable("Non-formal linkage is not allowed here!"); 1934 case Linkage::Module: 1935 case Linkage::External: 1936 return true; 1937 } 1938 llvm_unreachable("Unhandled Linkage enum"); 1939 } 1940 1941 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1942 NamedDecl *ND = this; 1943 if (auto *UD = dyn_cast<UsingShadowDecl>(ND)) 1944 ND = UD->getTargetDecl(); 1945 1946 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1947 return AD->getClassInterface(); 1948 1949 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND)) 1950 return AD->getNamespace(); 1951 1952 return ND; 1953 } 1954 1955 bool NamedDecl::isCXXInstanceMember() const { 1956 if (!isCXXClassMember()) 1957 return false; 1958 1959 const NamedDecl *D = this; 1960 if (isa<UsingShadowDecl>(D)) 1961 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1962 1963 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1964 return true; 1965 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction())) 1966 return MD->isInstance(); 1967 return false; 1968 } 1969 1970 //===----------------------------------------------------------------------===// 1971 // DeclaratorDecl Implementation 1972 //===----------------------------------------------------------------------===// 1973 1974 template <typename DeclT> 1975 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1976 if (decl->getNumTemplateParameterLists() > 0) 1977 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1978 return decl->getInnerLocStart(); 1979 } 1980 1981 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1982 TypeSourceInfo *TSI = getTypeSourceInfo(); 1983 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1984 return SourceLocation(); 1985 } 1986 1987 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const { 1988 TypeSourceInfo *TSI = getTypeSourceInfo(); 1989 if (TSI) return TSI->getTypeLoc().getEndLoc(); 1990 return SourceLocation(); 1991 } 1992 1993 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1994 if (QualifierLoc) { 1995 // Make sure the extended decl info is allocated. 1996 if (!hasExtInfo()) { 1997 // Save (non-extended) type source info pointer. 1998 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1999 // Allocate external info struct. 2000 DeclInfo = new (getASTContext()) ExtInfo; 2001 // Restore savedTInfo into (extended) decl info. 2002 getExtInfo()->TInfo = savedTInfo; 2003 } 2004 // Set qualifier info. 2005 getExtInfo()->QualifierLoc = QualifierLoc; 2006 } else if (hasExtInfo()) { 2007 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2008 getExtInfo()->QualifierLoc = QualifierLoc; 2009 } 2010 } 2011 2012 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) { 2013 assert(TrailingRequiresClause); 2014 // Make sure the extended decl info is allocated. 2015 if (!hasExtInfo()) { 2016 // Save (non-extended) type source info pointer. 2017 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 2018 // Allocate external info struct. 2019 DeclInfo = new (getASTContext()) ExtInfo; 2020 // Restore savedTInfo into (extended) decl info. 2021 getExtInfo()->TInfo = savedTInfo; 2022 } 2023 // Set requires clause info. 2024 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause; 2025 } 2026 2027 void DeclaratorDecl::setTemplateParameterListsInfo( 2028 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 2029 assert(!TPLists.empty()); 2030 // Make sure the extended decl info is allocated. 2031 if (!hasExtInfo()) { 2032 // Save (non-extended) type source info pointer. 2033 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 2034 // Allocate external info struct. 2035 DeclInfo = new (getASTContext()) ExtInfo; 2036 // Restore savedTInfo into (extended) decl info. 2037 getExtInfo()->TInfo = savedTInfo; 2038 } 2039 // Set the template parameter lists info. 2040 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 2041 } 2042 2043 SourceLocation DeclaratorDecl::getOuterLocStart() const { 2044 return getTemplateOrInnerLocStart(this); 2045 } 2046 2047 // Helper function: returns true if QT is or contains a type 2048 // having a postfix component. 2049 static bool typeIsPostfix(QualType QT) { 2050 while (true) { 2051 const Type* T = QT.getTypePtr(); 2052 switch (T->getTypeClass()) { 2053 default: 2054 return false; 2055 case Type::Pointer: 2056 QT = cast<PointerType>(T)->getPointeeType(); 2057 break; 2058 case Type::BlockPointer: 2059 QT = cast<BlockPointerType>(T)->getPointeeType(); 2060 break; 2061 case Type::MemberPointer: 2062 QT = cast<MemberPointerType>(T)->getPointeeType(); 2063 break; 2064 case Type::LValueReference: 2065 case Type::RValueReference: 2066 QT = cast<ReferenceType>(T)->getPointeeType(); 2067 break; 2068 case Type::PackExpansion: 2069 QT = cast<PackExpansionType>(T)->getPattern(); 2070 break; 2071 case Type::Paren: 2072 case Type::ConstantArray: 2073 case Type::DependentSizedArray: 2074 case Type::IncompleteArray: 2075 case Type::VariableArray: 2076 case Type::FunctionProto: 2077 case Type::FunctionNoProto: 2078 return true; 2079 } 2080 } 2081 } 2082 2083 SourceRange DeclaratorDecl::getSourceRange() const { 2084 SourceLocation RangeEnd = getLocation(); 2085 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 2086 // If the declaration has no name or the type extends past the name take the 2087 // end location of the type. 2088 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 2089 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 2090 } 2091 return SourceRange(getOuterLocStart(), RangeEnd); 2092 } 2093 2094 void QualifierInfo::setTemplateParameterListsInfo( 2095 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 2096 // Free previous template parameters (if any). 2097 if (NumTemplParamLists > 0) { 2098 Context.Deallocate(TemplParamLists); 2099 TemplParamLists = nullptr; 2100 NumTemplParamLists = 0; 2101 } 2102 // Set info on matched template parameter lists (if any). 2103 if (!TPLists.empty()) { 2104 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 2105 NumTemplParamLists = TPLists.size(); 2106 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 2107 } 2108 } 2109 2110 //===----------------------------------------------------------------------===// 2111 // VarDecl Implementation 2112 //===----------------------------------------------------------------------===// 2113 2114 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 2115 switch (SC) { 2116 case SC_None: break; 2117 case SC_Auto: return "auto"; 2118 case SC_Extern: return "extern"; 2119 case SC_PrivateExtern: return "__private_extern__"; 2120 case SC_Register: return "register"; 2121 case SC_Static: return "static"; 2122 } 2123 2124 llvm_unreachable("Invalid storage class"); 2125 } 2126 2127 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 2128 SourceLocation StartLoc, SourceLocation IdLoc, 2129 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 2130 StorageClass SC) 2131 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 2132 redeclarable_base(C) { 2133 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 2134 "VarDeclBitfields too large!"); 2135 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 2136 "ParmVarDeclBitfields too large!"); 2137 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 2138 "NonParmVarDeclBitfields too large!"); 2139 AllBits = 0; 2140 VarDeclBits.SClass = SC; 2141 // Everything else is implicitly initialized to false. 2142 } 2143 2144 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL, 2145 SourceLocation IdL, const IdentifierInfo *Id, 2146 QualType T, TypeSourceInfo *TInfo, StorageClass S) { 2147 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 2148 } 2149 2150 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2151 return new (C, ID) 2152 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 2153 QualType(), nullptr, SC_None); 2154 } 2155 2156 void VarDecl::setStorageClass(StorageClass SC) { 2157 assert(isLegalForVariable(SC)); 2158 VarDeclBits.SClass = SC; 2159 } 2160 2161 VarDecl::TLSKind VarDecl::getTLSKind() const { 2162 switch (VarDeclBits.TSCSpec) { 2163 case TSCS_unspecified: 2164 if (!hasAttr<ThreadAttr>() && 2165 !(getASTContext().getLangOpts().OpenMPUseTLS && 2166 getASTContext().getTargetInfo().isTLSSupported() && 2167 hasAttr<OMPThreadPrivateDeclAttr>())) 2168 return TLS_None; 2169 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 2170 LangOptions::MSVC2015)) || 2171 hasAttr<OMPThreadPrivateDeclAttr>()) 2172 ? TLS_Dynamic 2173 : TLS_Static; 2174 case TSCS___thread: // Fall through. 2175 case TSCS__Thread_local: 2176 return TLS_Static; 2177 case TSCS_thread_local: 2178 return TLS_Dynamic; 2179 } 2180 llvm_unreachable("Unknown thread storage class specifier!"); 2181 } 2182 2183 SourceRange VarDecl::getSourceRange() const { 2184 if (const Expr *Init = getInit()) { 2185 SourceLocation InitEnd = Init->getEndLoc(); 2186 // If Init is implicit, ignore its source range and fallback on 2187 // DeclaratorDecl::getSourceRange() to handle postfix elements. 2188 if (InitEnd.isValid() && InitEnd != getLocation()) 2189 return SourceRange(getOuterLocStart(), InitEnd); 2190 } 2191 return DeclaratorDecl::getSourceRange(); 2192 } 2193 2194 template<typename T> 2195 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 2196 // C++ [dcl.link]p1: All function types, function names with external linkage, 2197 // and variable names with external linkage have a language linkage. 2198 if (!D.hasExternalFormalLinkage()) 2199 return NoLanguageLinkage; 2200 2201 // Language linkage is a C++ concept, but saying that everything else in C has 2202 // C language linkage fits the implementation nicely. 2203 if (!D.getASTContext().getLangOpts().CPlusPlus) 2204 return CLanguageLinkage; 2205 2206 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 2207 // language linkage of the names of class members and the function type of 2208 // class member functions. 2209 const DeclContext *DC = D.getDeclContext(); 2210 if (DC->isRecord()) 2211 return CXXLanguageLinkage; 2212 2213 // If the first decl is in an extern "C" context, any other redeclaration 2214 // will have C language linkage. If the first one is not in an extern "C" 2215 // context, we would have reported an error for any other decl being in one. 2216 if (isFirstInExternCContext(&D)) 2217 return CLanguageLinkage; 2218 return CXXLanguageLinkage; 2219 } 2220 2221 template<typename T> 2222 static bool isDeclExternC(const T &D) { 2223 // Since the context is ignored for class members, they can only have C++ 2224 // language linkage or no language linkage. 2225 const DeclContext *DC = D.getDeclContext(); 2226 if (DC->isRecord()) { 2227 assert(D.getASTContext().getLangOpts().CPlusPlus); 2228 return false; 2229 } 2230 2231 return D.getLanguageLinkage() == CLanguageLinkage; 2232 } 2233 2234 LanguageLinkage VarDecl::getLanguageLinkage() const { 2235 return getDeclLanguageLinkage(*this); 2236 } 2237 2238 bool VarDecl::isExternC() const { 2239 return isDeclExternC(*this); 2240 } 2241 2242 bool VarDecl::isInExternCContext() const { 2243 return getLexicalDeclContext()->isExternCContext(); 2244 } 2245 2246 bool VarDecl::isInExternCXXContext() const { 2247 return getLexicalDeclContext()->isExternCXXContext(); 2248 } 2249 2250 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 2251 2252 VarDecl::DefinitionKind 2253 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 2254 if (isThisDeclarationADemotedDefinition()) 2255 return DeclarationOnly; 2256 2257 // C++ [basic.def]p2: 2258 // A declaration is a definition unless [...] it contains the 'extern' 2259 // specifier or a linkage-specification and neither an initializer [...], 2260 // it declares a non-inline static data member in a class declaration [...], 2261 // it declares a static data member outside a class definition and the variable 2262 // was defined within the class with the constexpr specifier [...], 2263 // C++1y [temp.expl.spec]p15: 2264 // An explicit specialization of a static data member or an explicit 2265 // specialization of a static data member template is a definition if the 2266 // declaration includes an initializer; otherwise, it is a declaration. 2267 // 2268 // FIXME: How do you declare (but not define) a partial specialization of 2269 // a static data member template outside the containing class? 2270 if (isStaticDataMember()) { 2271 if (isOutOfLine() && 2272 !(getCanonicalDecl()->isInline() && 2273 getCanonicalDecl()->isConstexpr()) && 2274 (hasInit() || 2275 // If the first declaration is out-of-line, this may be an 2276 // instantiation of an out-of-line partial specialization of a variable 2277 // template for which we have not yet instantiated the initializer. 2278 (getFirstDecl()->isOutOfLine() 2279 ? getTemplateSpecializationKind() == TSK_Undeclared 2280 : getTemplateSpecializationKind() != 2281 TSK_ExplicitSpecialization) || 2282 isa<VarTemplatePartialSpecializationDecl>(this))) 2283 return Definition; 2284 if (!isOutOfLine() && isInline()) 2285 return Definition; 2286 return DeclarationOnly; 2287 } 2288 // C99 6.7p5: 2289 // A definition of an identifier is a declaration for that identifier that 2290 // [...] causes storage to be reserved for that object. 2291 // Note: that applies for all non-file-scope objects. 2292 // C99 6.9.2p1: 2293 // If the declaration of an identifier for an object has file scope and an 2294 // initializer, the declaration is an external definition for the identifier 2295 if (hasInit()) 2296 return Definition; 2297 2298 if (hasDefiningAttr()) 2299 return Definition; 2300 2301 if (const auto *SAA = getAttr<SelectAnyAttr>()) 2302 if (!SAA->isInherited()) 2303 return Definition; 2304 2305 // A variable template specialization (other than a static data member 2306 // template or an explicit specialization) is a declaration until we 2307 // instantiate its initializer. 2308 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2309 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2310 !isa<VarTemplatePartialSpecializationDecl>(VTSD) && 2311 !VTSD->IsCompleteDefinition) 2312 return DeclarationOnly; 2313 } 2314 2315 if (hasExternalStorage()) 2316 return DeclarationOnly; 2317 2318 // [dcl.link] p7: 2319 // A declaration directly contained in a linkage-specification is treated 2320 // as if it contains the extern specifier for the purpose of determining 2321 // the linkage of the declared name and whether it is a definition. 2322 if (isSingleLineLanguageLinkage(*this)) 2323 return DeclarationOnly; 2324 2325 // C99 6.9.2p2: 2326 // A declaration of an object that has file scope without an initializer, 2327 // and without a storage class specifier or the scs 'static', constitutes 2328 // a tentative definition. 2329 // No such thing in C++. 2330 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 2331 return TentativeDefinition; 2332 2333 // What's left is (in C, block-scope) declarations without initializers or 2334 // external storage. These are definitions. 2335 return Definition; 2336 } 2337 2338 VarDecl *VarDecl::getActingDefinition() { 2339 DefinitionKind Kind = isThisDeclarationADefinition(); 2340 if (Kind != TentativeDefinition) 2341 return nullptr; 2342 2343 VarDecl *LastTentative = nullptr; 2344 2345 // Loop through the declaration chain, starting with the most recent. 2346 for (VarDecl *Decl = getMostRecentDecl(); Decl; 2347 Decl = Decl->getPreviousDecl()) { 2348 Kind = Decl->isThisDeclarationADefinition(); 2349 if (Kind == Definition) 2350 return nullptr; 2351 // Record the first (most recent) TentativeDefinition that is encountered. 2352 if (Kind == TentativeDefinition && !LastTentative) 2353 LastTentative = Decl; 2354 } 2355 2356 return LastTentative; 2357 } 2358 2359 VarDecl *VarDecl::getDefinition(ASTContext &C) { 2360 VarDecl *First = getFirstDecl(); 2361 for (auto *I : First->redecls()) { 2362 if (I->isThisDeclarationADefinition(C) == Definition) 2363 return I; 2364 } 2365 return nullptr; 2366 } 2367 2368 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 2369 DefinitionKind Kind = DeclarationOnly; 2370 2371 const VarDecl *First = getFirstDecl(); 2372 for (auto *I : First->redecls()) { 2373 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 2374 if (Kind == Definition) 2375 break; 2376 } 2377 2378 return Kind; 2379 } 2380 2381 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2382 for (auto *I : redecls()) { 2383 if (auto Expr = I->getInit()) { 2384 D = I; 2385 return Expr; 2386 } 2387 } 2388 return nullptr; 2389 } 2390 2391 bool VarDecl::hasInit() const { 2392 if (auto *P = dyn_cast<ParmVarDecl>(this)) 2393 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) 2394 return false; 2395 2396 return !Init.isNull(); 2397 } 2398 2399 Expr *VarDecl::getInit() { 2400 if (!hasInit()) 2401 return nullptr; 2402 2403 if (auto *S = Init.dyn_cast<Stmt *>()) 2404 return cast<Expr>(S); 2405 2406 auto *Eval = getEvaluatedStmt(); 2407 return cast<Expr>(Eval->Value.isOffset() 2408 ? Eval->Value.get(getASTContext().getExternalSource()) 2409 : Eval->Value.get(nullptr)); 2410 } 2411 2412 Stmt **VarDecl::getInitAddress() { 2413 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) 2414 return ES->Value.getAddressOfPointer(getASTContext().getExternalSource()); 2415 2416 return Init.getAddrOfPtr1(); 2417 } 2418 2419 VarDecl *VarDecl::getInitializingDeclaration() { 2420 VarDecl *Def = nullptr; 2421 for (auto *I : redecls()) { 2422 if (I->hasInit()) 2423 return I; 2424 2425 if (I->isThisDeclarationADefinition()) { 2426 if (isStaticDataMember()) 2427 return I; 2428 Def = I; 2429 } 2430 } 2431 return Def; 2432 } 2433 2434 bool VarDecl::isOutOfLine() const { 2435 if (Decl::isOutOfLine()) 2436 return true; 2437 2438 if (!isStaticDataMember()) 2439 return false; 2440 2441 // If this static data member was instantiated from a static data member of 2442 // a class template, check whether that static data member was defined 2443 // out-of-line. 2444 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2445 return VD->isOutOfLine(); 2446 2447 return false; 2448 } 2449 2450 void VarDecl::setInit(Expr *I) { 2451 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2452 Eval->~EvaluatedStmt(); 2453 getASTContext().Deallocate(Eval); 2454 } 2455 2456 Init = I; 2457 } 2458 2459 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const { 2460 const LangOptions &Lang = C.getLangOpts(); 2461 2462 // OpenCL permits const integral variables to be used in constant 2463 // expressions, like in C++98. 2464 if (!Lang.CPlusPlus && !Lang.OpenCL) 2465 return false; 2466 2467 // Function parameters are never usable in constant expressions. 2468 if (isa<ParmVarDecl>(this)) 2469 return false; 2470 2471 // The values of weak variables are never usable in constant expressions. 2472 if (isWeak()) 2473 return false; 2474 2475 // In C++11, any variable of reference type can be used in a constant 2476 // expression if it is initialized by a constant expression. 2477 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2478 return true; 2479 2480 // Only const objects can be used in constant expressions in C++. C++98 does 2481 // not require the variable to be non-volatile, but we consider this to be a 2482 // defect. 2483 if (!getType().isConstant(C) || getType().isVolatileQualified()) 2484 return false; 2485 2486 // In C++, const, non-volatile variables of integral or enumeration types 2487 // can be used in constant expressions. 2488 if (getType()->isIntegralOrEnumerationType()) 2489 return true; 2490 2491 // Additionally, in C++11, non-volatile constexpr variables can be used in 2492 // constant expressions. 2493 return Lang.CPlusPlus11 && isConstexpr(); 2494 } 2495 2496 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const { 2497 // C++2a [expr.const]p3: 2498 // A variable is usable in constant expressions after its initializing 2499 // declaration is encountered... 2500 const VarDecl *DefVD = nullptr; 2501 const Expr *Init = getAnyInitializer(DefVD); 2502 if (!Init || Init->isValueDependent() || getType()->isDependentType()) 2503 return false; 2504 // ... if it is a constexpr variable, or it is of reference type or of 2505 // const-qualified integral or enumeration type, ... 2506 if (!DefVD->mightBeUsableInConstantExpressions(Context)) 2507 return false; 2508 // ... and its initializer is a constant initializer. 2509 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization()) 2510 return false; 2511 // C++98 [expr.const]p1: 2512 // An integral constant-expression can involve only [...] const variables 2513 // or static data members of integral or enumeration types initialized with 2514 // [integer] constant expressions (dcl.init) 2515 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) && 2516 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context)) 2517 return false; 2518 return true; 2519 } 2520 2521 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2522 /// form, which contains extra information on the evaluated value of the 2523 /// initializer. 2524 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2525 auto *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2526 if (!Eval) { 2527 // Note: EvaluatedStmt contains an APValue, which usually holds 2528 // resources not allocated from the ASTContext. We need to do some 2529 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2530 // where we can detect whether there's anything to clean up or not. 2531 Eval = new (getASTContext()) EvaluatedStmt; 2532 Eval->Value = Init.get<Stmt *>(); 2533 Init = Eval; 2534 } 2535 return Eval; 2536 } 2537 2538 EvaluatedStmt *VarDecl::getEvaluatedStmt() const { 2539 return Init.dyn_cast<EvaluatedStmt *>(); 2540 } 2541 2542 APValue *VarDecl::evaluateValue() const { 2543 SmallVector<PartialDiagnosticAt, 8> Notes; 2544 return evaluateValueImpl(Notes, hasConstantInitialization()); 2545 } 2546 2547 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, 2548 bool IsConstantInitialization) const { 2549 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2550 2551 const auto *Init = getInit(); 2552 assert(!Init->isValueDependent()); 2553 2554 // We only produce notes indicating why an initializer is non-constant the 2555 // first time it is evaluated. FIXME: The notes won't always be emitted the 2556 // first time we try evaluation, so might not be produced at all. 2557 if (Eval->WasEvaluated) 2558 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated; 2559 2560 if (Eval->IsEvaluating) { 2561 // FIXME: Produce a diagnostic for self-initialization. 2562 return nullptr; 2563 } 2564 2565 Eval->IsEvaluating = true; 2566 2567 ASTContext &Ctx = getASTContext(); 2568 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes, 2569 IsConstantInitialization); 2570 2571 // In C++, this isn't a constant initializer if we produced notes. In that 2572 // case, we can't keep the result, because it may only be correct under the 2573 // assumption that the initializer is a constant context. 2574 if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus && 2575 !Notes.empty()) 2576 Result = false; 2577 2578 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2579 // or that it's empty (so that there's nothing to clean up) if evaluation 2580 // failed. 2581 if (!Result) 2582 Eval->Evaluated = APValue(); 2583 else if (Eval->Evaluated.needsCleanup()) 2584 Ctx.addDestruction(&Eval->Evaluated); 2585 2586 Eval->IsEvaluating = false; 2587 Eval->WasEvaluated = true; 2588 2589 return Result ? &Eval->Evaluated : nullptr; 2590 } 2591 2592 APValue *VarDecl::getEvaluatedValue() const { 2593 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2594 if (Eval->WasEvaluated) 2595 return &Eval->Evaluated; 2596 2597 return nullptr; 2598 } 2599 2600 bool VarDecl::hasICEInitializer(const ASTContext &Context) const { 2601 const Expr *Init = getInit(); 2602 assert(Init && "no initializer"); 2603 2604 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2605 if (!Eval->CheckedForICEInit) { 2606 Eval->CheckedForICEInit = true; 2607 Eval->HasICEInit = Init->isIntegerConstantExpr(Context); 2608 } 2609 return Eval->HasICEInit; 2610 } 2611 2612 bool VarDecl::hasConstantInitialization() const { 2613 // In C, all globals (and only globals) have constant initialization. 2614 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus) 2615 return true; 2616 2617 // In C++, it depends on whether the evaluation at the point of definition 2618 // was evaluatable as a constant initializer. 2619 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2620 return Eval->HasConstantInitialization; 2621 2622 return false; 2623 } 2624 2625 bool VarDecl::checkForConstantInitialization( 2626 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2627 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2628 // If we ask for the value before we know whether we have a constant 2629 // initializer, we can compute the wrong value (for example, due to 2630 // std::is_constant_evaluated()). 2631 assert(!Eval->WasEvaluated && 2632 "already evaluated var value before checking for constant init"); 2633 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++"); 2634 2635 assert(!getInit()->isValueDependent()); 2636 2637 // Evaluate the initializer to check whether it's a constant expression. 2638 Eval->HasConstantInitialization = 2639 evaluateValueImpl(Notes, true) && Notes.empty(); 2640 2641 // If evaluation as a constant initializer failed, allow re-evaluation as a 2642 // non-constant initializer if we later find we want the value. 2643 if (!Eval->HasConstantInitialization) 2644 Eval->WasEvaluated = false; 2645 2646 return Eval->HasConstantInitialization; 2647 } 2648 2649 bool VarDecl::isParameterPack() const { 2650 return isa<PackExpansionType>(getType()); 2651 } 2652 2653 template<typename DeclT> 2654 static DeclT *getDefinitionOrSelf(DeclT *D) { 2655 assert(D); 2656 if (auto *Def = D->getDefinition()) 2657 return Def; 2658 return D; 2659 } 2660 2661 bool VarDecl::isEscapingByref() const { 2662 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref; 2663 } 2664 2665 bool VarDecl::isNonEscapingByref() const { 2666 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref; 2667 } 2668 2669 bool VarDecl::hasDependentAlignment() const { 2670 QualType T = getType(); 2671 return T->isDependentType() || T->isUndeducedType() || 2672 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) { 2673 return AA->isAlignmentDependent(); 2674 }); 2675 } 2676 2677 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2678 const VarDecl *VD = this; 2679 2680 // If this is an instantiated member, walk back to the template from which 2681 // it was instantiated. 2682 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) { 2683 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2684 VD = VD->getInstantiatedFromStaticDataMember(); 2685 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2686 VD = NewVD; 2687 } 2688 } 2689 2690 // If it's an instantiated variable template specialization, find the 2691 // template or partial specialization from which it was instantiated. 2692 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 2693 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) { 2694 auto From = VDTemplSpec->getInstantiatedFrom(); 2695 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2696 while (!VTD->isMemberSpecialization()) { 2697 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate(); 2698 if (!NewVTD) 2699 break; 2700 VTD = NewVTD; 2701 } 2702 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2703 } 2704 if (auto *VTPSD = 2705 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2706 while (!VTPSD->isMemberSpecialization()) { 2707 auto *NewVTPSD = VTPSD->getInstantiatedFromMember(); 2708 if (!NewVTPSD) 2709 break; 2710 VTPSD = NewVTPSD; 2711 } 2712 return getDefinitionOrSelf<VarDecl>(VTPSD); 2713 } 2714 } 2715 } 2716 2717 // If this is the pattern of a variable template, find where it was 2718 // instantiated from. FIXME: Is this necessary? 2719 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) { 2720 while (!VarTemplate->isMemberSpecialization()) { 2721 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate(); 2722 if (!NewVT) 2723 break; 2724 VarTemplate = NewVT; 2725 } 2726 2727 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl()); 2728 } 2729 2730 if (VD == this) 2731 return nullptr; 2732 return getDefinitionOrSelf(const_cast<VarDecl*>(VD)); 2733 } 2734 2735 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2736 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2737 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2738 2739 return nullptr; 2740 } 2741 2742 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2743 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2744 return Spec->getSpecializationKind(); 2745 2746 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2747 return MSI->getTemplateSpecializationKind(); 2748 2749 return TSK_Undeclared; 2750 } 2751 2752 TemplateSpecializationKind 2753 VarDecl::getTemplateSpecializationKindForInstantiation() const { 2754 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2755 return MSI->getTemplateSpecializationKind(); 2756 2757 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2758 return Spec->getSpecializationKind(); 2759 2760 return TSK_Undeclared; 2761 } 2762 2763 SourceLocation VarDecl::getPointOfInstantiation() const { 2764 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2765 return Spec->getPointOfInstantiation(); 2766 2767 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2768 return MSI->getPointOfInstantiation(); 2769 2770 return SourceLocation(); 2771 } 2772 2773 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2774 return getASTContext().getTemplateOrSpecializationInfo(this) 2775 .dyn_cast<VarTemplateDecl *>(); 2776 } 2777 2778 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2779 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2780 } 2781 2782 bool VarDecl::isKnownToBeDefined() const { 2783 const auto &LangOpts = getASTContext().getLangOpts(); 2784 // In CUDA mode without relocatable device code, variables of form 'extern 2785 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared 2786 // memory pool. These are never undefined variables, even if they appear 2787 // inside of an anon namespace or static function. 2788 // 2789 // With CUDA relocatable device code enabled, these variables don't get 2790 // special handling; they're treated like regular extern variables. 2791 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode && 2792 hasExternalStorage() && hasAttr<CUDASharedAttr>() && 2793 isa<IncompleteArrayType>(getType())) 2794 return true; 2795 2796 return hasDefinition(); 2797 } 2798 2799 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { 2800 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() || 2801 (!Ctx.getLangOpts().RegisterStaticDestructors && 2802 !hasAttr<AlwaysDestroyAttr>())); 2803 } 2804 2805 QualType::DestructionKind 2806 VarDecl::needsDestruction(const ASTContext &Ctx) const { 2807 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2808 if (Eval->HasConstantDestruction) 2809 return QualType::DK_none; 2810 2811 if (isNoDestroy(Ctx)) 2812 return QualType::DK_none; 2813 2814 return getType().isDestructedType(); 2815 } 2816 2817 bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const { 2818 assert(hasInit() && "Expect initializer to check for flexible array init"); 2819 auto *Ty = getType()->getAs<RecordType>(); 2820 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) 2821 return false; 2822 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2823 if (!List) 2824 return false; 2825 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2826 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2827 if (!InitTy) 2828 return false; 2829 return InitTy->getSize() != 0; 2830 } 2831 2832 CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const { 2833 assert(hasInit() && "Expect initializer to check for flexible array init"); 2834 auto *Ty = getType()->getAs<RecordType>(); 2835 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) 2836 return CharUnits::Zero(); 2837 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2838 if (!List || List->getNumInits() == 0) 2839 return CharUnits::Zero(); 2840 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2841 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2842 if (!InitTy) 2843 return CharUnits::Zero(); 2844 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy); 2845 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl()); 2846 CharUnits FlexibleArrayOffset = 2847 Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1)); 2848 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize()) 2849 return CharUnits::Zero(); 2850 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize(); 2851 } 2852 2853 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2854 if (isStaticDataMember()) 2855 // FIXME: Remove ? 2856 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2857 return getASTContext().getTemplateOrSpecializationInfo(this) 2858 .dyn_cast<MemberSpecializationInfo *>(); 2859 return nullptr; 2860 } 2861 2862 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2863 SourceLocation PointOfInstantiation) { 2864 assert((isa<VarTemplateSpecializationDecl>(this) || 2865 getMemberSpecializationInfo()) && 2866 "not a variable or static data member template specialization"); 2867 2868 if (VarTemplateSpecializationDecl *Spec = 2869 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2870 Spec->setSpecializationKind(TSK); 2871 if (TSK != TSK_ExplicitSpecialization && 2872 PointOfInstantiation.isValid() && 2873 Spec->getPointOfInstantiation().isInvalid()) { 2874 Spec->setPointOfInstantiation(PointOfInstantiation); 2875 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2876 L->InstantiationRequested(this); 2877 } 2878 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2879 MSI->setTemplateSpecializationKind(TSK); 2880 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2881 MSI->getPointOfInstantiation().isInvalid()) { 2882 MSI->setPointOfInstantiation(PointOfInstantiation); 2883 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2884 L->InstantiationRequested(this); 2885 } 2886 } 2887 } 2888 2889 void 2890 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2891 TemplateSpecializationKind TSK) { 2892 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2893 "Previous template or instantiation?"); 2894 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2895 } 2896 2897 //===----------------------------------------------------------------------===// 2898 // ParmVarDecl Implementation 2899 //===----------------------------------------------------------------------===// 2900 2901 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2902 SourceLocation StartLoc, 2903 SourceLocation IdLoc, IdentifierInfo *Id, 2904 QualType T, TypeSourceInfo *TInfo, 2905 StorageClass S, Expr *DefArg) { 2906 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2907 S, DefArg); 2908 } 2909 2910 QualType ParmVarDecl::getOriginalType() const { 2911 TypeSourceInfo *TSI = getTypeSourceInfo(); 2912 QualType T = TSI ? TSI->getType() : getType(); 2913 if (const auto *DT = dyn_cast<DecayedType>(T)) 2914 return DT->getOriginalType(); 2915 return T; 2916 } 2917 2918 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2919 return new (C, ID) 2920 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2921 nullptr, QualType(), nullptr, SC_None, nullptr); 2922 } 2923 2924 SourceRange ParmVarDecl::getSourceRange() const { 2925 if (!hasInheritedDefaultArg()) { 2926 SourceRange ArgRange = getDefaultArgRange(); 2927 if (ArgRange.isValid()) 2928 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2929 } 2930 2931 // DeclaratorDecl considers the range of postfix types as overlapping with the 2932 // declaration name, but this is not the case with parameters in ObjC methods. 2933 if (isa<ObjCMethodDecl>(getDeclContext())) 2934 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation()); 2935 2936 return DeclaratorDecl::getSourceRange(); 2937 } 2938 2939 bool ParmVarDecl::isDestroyedInCallee() const { 2940 // ns_consumed only affects code generation in ARC 2941 if (hasAttr<NSConsumedAttr>()) 2942 return getASTContext().getLangOpts().ObjCAutoRefCount; 2943 2944 // FIXME: isParamDestroyedInCallee() should probably imply 2945 // isDestructedType() 2946 const auto *RT = getType()->getAs<RecordType>(); 2947 if (RT && RT->getDecl()->isParamDestroyedInCallee() && 2948 getType().isDestructedType()) 2949 return true; 2950 2951 return false; 2952 } 2953 2954 Expr *ParmVarDecl::getDefaultArg() { 2955 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2956 assert(!hasUninstantiatedDefaultArg() && 2957 "Default argument is not yet instantiated!"); 2958 2959 Expr *Arg = getInit(); 2960 if (auto *E = dyn_cast_if_present<FullExpr>(Arg)) 2961 return E->getSubExpr(); 2962 2963 return Arg; 2964 } 2965 2966 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2967 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2968 Init = defarg; 2969 } 2970 2971 SourceRange ParmVarDecl::getDefaultArgRange() const { 2972 switch (ParmVarDeclBits.DefaultArgKind) { 2973 case DAK_None: 2974 case DAK_Unparsed: 2975 // Nothing we can do here. 2976 return SourceRange(); 2977 2978 case DAK_Uninstantiated: 2979 return getUninstantiatedDefaultArg()->getSourceRange(); 2980 2981 case DAK_Normal: 2982 if (const Expr *E = getInit()) 2983 return E->getSourceRange(); 2984 2985 // Missing an actual expression, may be invalid. 2986 return SourceRange(); 2987 } 2988 llvm_unreachable("Invalid default argument kind."); 2989 } 2990 2991 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 2992 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 2993 Init = arg; 2994 } 2995 2996 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 2997 assert(hasUninstantiatedDefaultArg() && 2998 "Wrong kind of initialization expression!"); 2999 return cast_if_present<Expr>(Init.get<Stmt *>()); 3000 } 3001 3002 bool ParmVarDecl::hasDefaultArg() const { 3003 // FIXME: We should just return false for DAK_None here once callers are 3004 // prepared for the case that we encountered an invalid default argument and 3005 // were unable to even build an invalid expression. 3006 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 3007 !Init.isNull(); 3008 } 3009 3010 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 3011 getASTContext().setParameterIndex(this, parameterIndex); 3012 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 3013 } 3014 3015 unsigned ParmVarDecl::getParameterIndexLarge() const { 3016 return getASTContext().getParameterIndex(this); 3017 } 3018 3019 //===----------------------------------------------------------------------===// 3020 // FunctionDecl Implementation 3021 //===----------------------------------------------------------------------===// 3022 3023 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, 3024 SourceLocation StartLoc, 3025 const DeclarationNameInfo &NameInfo, QualType T, 3026 TypeSourceInfo *TInfo, StorageClass S, 3027 bool UsesFPIntrin, bool isInlineSpecified, 3028 ConstexprSpecKind ConstexprKind, 3029 Expr *TrailingRequiresClause) 3030 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 3031 StartLoc), 3032 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0), 3033 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) { 3034 assert(T.isNull() || T->isFunctionType()); 3035 FunctionDeclBits.SClass = S; 3036 FunctionDeclBits.IsInline = isInlineSpecified; 3037 FunctionDeclBits.IsInlineSpecified = isInlineSpecified; 3038 FunctionDeclBits.IsVirtualAsWritten = false; 3039 FunctionDeclBits.IsPure = false; 3040 FunctionDeclBits.HasInheritedPrototype = false; 3041 FunctionDeclBits.HasWrittenPrototype = true; 3042 FunctionDeclBits.IsDeleted = false; 3043 FunctionDeclBits.IsTrivial = false; 3044 FunctionDeclBits.IsTrivialForCall = false; 3045 FunctionDeclBits.IsDefaulted = false; 3046 FunctionDeclBits.IsExplicitlyDefaulted = false; 3047 FunctionDeclBits.HasDefaultedFunctionInfo = false; 3048 FunctionDeclBits.IsIneligibleOrNotSelected = false; 3049 FunctionDeclBits.HasImplicitReturnZero = false; 3050 FunctionDeclBits.IsLateTemplateParsed = false; 3051 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind); 3052 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false; 3053 FunctionDeclBits.InstantiationIsPending = false; 3054 FunctionDeclBits.UsesSEHTry = false; 3055 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin; 3056 FunctionDeclBits.HasSkippedBody = false; 3057 FunctionDeclBits.WillHaveBody = false; 3058 FunctionDeclBits.IsMultiVersion = false; 3059 FunctionDeclBits.DeductionCandidateKind = 3060 static_cast<unsigned char>(DeductionCandidate::Normal); 3061 FunctionDeclBits.HasODRHash = false; 3062 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false; 3063 if (TrailingRequiresClause) 3064 setTrailingRequiresClause(TrailingRequiresClause); 3065 } 3066 3067 void FunctionDecl::getNameForDiagnostic( 3068 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 3069 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 3070 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 3071 if (TemplateArgs) 3072 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 3073 } 3074 3075 bool FunctionDecl::isVariadic() const { 3076 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 3077 return FT->isVariadic(); 3078 return false; 3079 } 3080 3081 FunctionDecl::DefaultedFunctionInfo * 3082 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context, 3083 ArrayRef<DeclAccessPair> Lookups) { 3084 DefaultedFunctionInfo *Info = new (Context.Allocate( 3085 totalSizeToAlloc<DeclAccessPair>(Lookups.size()), 3086 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair)))) 3087 DefaultedFunctionInfo; 3088 Info->NumLookups = Lookups.size(); 3089 std::uninitialized_copy(Lookups.begin(), Lookups.end(), 3090 Info->getTrailingObjects<DeclAccessPair>()); 3091 return Info; 3092 } 3093 3094 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) { 3095 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this"); 3096 assert(!Body && "can't replace function body with defaulted function info"); 3097 3098 FunctionDeclBits.HasDefaultedFunctionInfo = true; 3099 DefaultedInfo = Info; 3100 } 3101 3102 FunctionDecl::DefaultedFunctionInfo * 3103 FunctionDecl::getDefaultedFunctionInfo() const { 3104 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr; 3105 } 3106 3107 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 3108 for (const auto *I : redecls()) { 3109 if (I->doesThisDeclarationHaveABody()) { 3110 Definition = I; 3111 return true; 3112 } 3113 } 3114 3115 return false; 3116 } 3117 3118 bool FunctionDecl::hasTrivialBody() const { 3119 const Stmt *S = getBody(); 3120 if (!S) { 3121 // Since we don't have a body for this function, we don't know if it's 3122 // trivial or not. 3123 return false; 3124 } 3125 3126 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 3127 return true; 3128 return false; 3129 } 3130 3131 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const { 3132 if (!getFriendObjectKind()) 3133 return false; 3134 3135 // Check for a friend function instantiated from a friend function 3136 // definition in a templated class. 3137 if (const FunctionDecl *InstantiatedFrom = 3138 getInstantiatedFromMemberFunction()) 3139 return InstantiatedFrom->getFriendObjectKind() && 3140 InstantiatedFrom->isThisDeclarationADefinition(); 3141 3142 // Check for a friend function template instantiated from a friend 3143 // function template definition in a templated class. 3144 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { 3145 if (const FunctionTemplateDecl *InstantiatedFrom = 3146 Template->getInstantiatedFromMemberTemplate()) 3147 return InstantiatedFrom->getFriendObjectKind() && 3148 InstantiatedFrom->isThisDeclarationADefinition(); 3149 } 3150 3151 return false; 3152 } 3153 3154 bool FunctionDecl::isDefined(const FunctionDecl *&Definition, 3155 bool CheckForPendingFriendDefinition) const { 3156 for (const FunctionDecl *FD : redecls()) { 3157 if (FD->isThisDeclarationADefinition()) { 3158 Definition = FD; 3159 return true; 3160 } 3161 3162 // If this is a friend function defined in a class template, it does not 3163 // have a body until it is used, nevertheless it is a definition, see 3164 // [temp.inst]p2: 3165 // 3166 // ... for the purpose of determining whether an instantiated redeclaration 3167 // is valid according to [basic.def.odr] and [class.mem], a declaration that 3168 // corresponds to a definition in the template is considered to be a 3169 // definition. 3170 // 3171 // The following code must produce redefinition error: 3172 // 3173 // template<typename T> struct C20 { friend void func_20() {} }; 3174 // C20<int> c20i; 3175 // void func_20() {} 3176 // 3177 if (CheckForPendingFriendDefinition && 3178 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 3179 Definition = FD; 3180 return true; 3181 } 3182 } 3183 3184 return false; 3185 } 3186 3187 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 3188 if (!hasBody(Definition)) 3189 return nullptr; 3190 3191 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo && 3192 "definition should not have a body"); 3193 if (Definition->Body) 3194 return Definition->Body.get(getASTContext().getExternalSource()); 3195 3196 return nullptr; 3197 } 3198 3199 void FunctionDecl::setBody(Stmt *B) { 3200 FunctionDeclBits.HasDefaultedFunctionInfo = false; 3201 Body = LazyDeclStmtPtr(B); 3202 if (B) 3203 EndRangeLoc = B->getEndLoc(); 3204 } 3205 3206 void FunctionDecl::setPure(bool P) { 3207 FunctionDeclBits.IsPure = P; 3208 if (P) 3209 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 3210 Parent->markedVirtualFunctionPure(); 3211 } 3212 3213 template<std::size_t Len> 3214 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 3215 const IdentifierInfo *II = ND->getIdentifier(); 3216 return II && II->isStr(Str); 3217 } 3218 3219 bool FunctionDecl::isImmediateEscalating() const { 3220 // C++23 [expr.const]/p17 3221 // An immediate-escalating function is 3222 // - the call operator of a lambda that is not declared with the consteval 3223 // specifier, 3224 if (isLambdaCallOperator(this) && !isConsteval()) 3225 return true; 3226 // - a defaulted special member function that is not declared with the 3227 // consteval specifier, 3228 if (isDefaulted() && !isConsteval()) 3229 return true; 3230 // - a function that results from the instantiation of a templated entity 3231 // defined with the constexpr specifier. 3232 TemplatedKind TK = getTemplatedKind(); 3233 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate && 3234 isConstexprSpecified()) 3235 return true; 3236 return false; 3237 } 3238 3239 bool FunctionDecl::isImmediateFunction() const { 3240 // C++23 [expr.const]/p18 3241 // An immediate function is a function or constructor that is 3242 // - declared with the consteval specifier 3243 if (isConsteval()) 3244 return true; 3245 // - an immediate-escalating function F whose function body contains an 3246 // immediate-escalating expression 3247 if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions()) 3248 return true; 3249 3250 if (const auto *MD = dyn_cast<CXXMethodDecl>(this); 3251 MD && MD->isLambdaStaticInvoker()) 3252 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction(); 3253 3254 return false; 3255 } 3256 3257 bool FunctionDecl::isMain() const { 3258 const TranslationUnitDecl *tunit = 3259 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3260 return tunit && 3261 !tunit->getASTContext().getLangOpts().Freestanding && 3262 isNamed(this, "main"); 3263 } 3264 3265 bool FunctionDecl::isMSVCRTEntryPoint() const { 3266 const TranslationUnitDecl *TUnit = 3267 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3268 if (!TUnit) 3269 return false; 3270 3271 // Even though we aren't really targeting MSVCRT if we are freestanding, 3272 // semantic analysis for these functions remains the same. 3273 3274 // MSVCRT entry points only exist on MSVCRT targets. 3275 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 3276 return false; 3277 3278 // Nameless functions like constructors cannot be entry points. 3279 if (!getIdentifier()) 3280 return false; 3281 3282 return llvm::StringSwitch<bool>(getName()) 3283 .Cases("main", // an ANSI console app 3284 "wmain", // a Unicode console App 3285 "WinMain", // an ANSI GUI app 3286 "wWinMain", // a Unicode GUI app 3287 "DllMain", // a DLL 3288 true) 3289 .Default(false); 3290 } 3291 3292 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 3293 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3294 return false; 3295 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3296 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3297 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3298 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3299 return false; 3300 3301 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3302 return false; 3303 3304 const auto *proto = getType()->castAs<FunctionProtoType>(); 3305 if (proto->getNumParams() != 2 || proto->isVariadic()) 3306 return false; 3307 3308 const ASTContext &Context = 3309 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 3310 ->getASTContext(); 3311 3312 // The result type and first argument type are constant across all 3313 // these operators. The second argument must be exactly void*. 3314 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 3315 } 3316 3317 bool FunctionDecl::isReplaceableGlobalAllocationFunction( 3318 std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const { 3319 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3320 return false; 3321 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3322 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3323 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3324 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3325 return false; 3326 3327 if (isa<CXXRecordDecl>(getDeclContext())) 3328 return false; 3329 3330 // This can only fail for an invalid 'operator new' declaration. 3331 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3332 return false; 3333 3334 const auto *FPT = getType()->castAs<FunctionProtoType>(); 3335 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic()) 3336 return false; 3337 3338 // If this is a single-parameter function, it must be a replaceable global 3339 // allocation or deallocation function. 3340 if (FPT->getNumParams() == 1) 3341 return true; 3342 3343 unsigned Params = 1; 3344 QualType Ty = FPT->getParamType(Params); 3345 const ASTContext &Ctx = getASTContext(); 3346 3347 auto Consume = [&] { 3348 ++Params; 3349 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 3350 }; 3351 3352 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 3353 bool IsSizedDelete = false; 3354 if (Ctx.getLangOpts().SizedDeallocation && 3355 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 3356 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 3357 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 3358 IsSizedDelete = true; 3359 Consume(); 3360 } 3361 3362 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 3363 // new/delete. 3364 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 3365 Consume(); 3366 if (AlignmentParam) 3367 *AlignmentParam = Params; 3368 } 3369 3370 // If this is not a sized delete, the next parameter can be a 3371 // 'const std::nothrow_t&'. 3372 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 3373 Ty = Ty->getPointeeType(); 3374 if (Ty.getCVRQualifiers() != Qualifiers::Const) 3375 return false; 3376 if (Ty->isNothrowT()) { 3377 if (IsNothrow) 3378 *IsNothrow = true; 3379 Consume(); 3380 } 3381 } 3382 3383 // Finally, recognize the not yet standard versions of new that take a 3384 // hot/cold allocation hint (__hot_cold_t). These are currently supported by 3385 // tcmalloc (see 3386 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53). 3387 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) { 3388 QualType T = Ty; 3389 while (const auto *TD = T->getAs<TypedefType>()) 3390 T = TD->getDecl()->getUnderlyingType(); 3391 const IdentifierInfo *II = 3392 T->castAs<EnumType>()->getDecl()->getIdentifier(); 3393 if (II && II->isStr("__hot_cold_t")) 3394 Consume(); 3395 } 3396 3397 return Params == FPT->getNumParams(); 3398 } 3399 3400 bool FunctionDecl::isInlineBuiltinDeclaration() const { 3401 if (!getBuiltinID()) 3402 return false; 3403 3404 const FunctionDecl *Definition; 3405 if (!hasBody(Definition)) 3406 return false; 3407 3408 if (!Definition->isInlineSpecified() || 3409 !Definition->hasAttr<AlwaysInlineAttr>()) 3410 return false; 3411 3412 ASTContext &Context = getASTContext(); 3413 switch (Context.GetGVALinkageForFunction(Definition)) { 3414 case GVA_Internal: 3415 case GVA_DiscardableODR: 3416 case GVA_StrongODR: 3417 return false; 3418 case GVA_AvailableExternally: 3419 case GVA_StrongExternal: 3420 return true; 3421 } 3422 llvm_unreachable("Unknown GVALinkage"); 3423 } 3424 3425 bool FunctionDecl::isDestroyingOperatorDelete() const { 3426 // C++ P0722: 3427 // Within a class C, a single object deallocation function with signature 3428 // (T, std::destroying_delete_t, <more params>) 3429 // is a destroying operator delete. 3430 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 3431 getNumParams() < 2) 3432 return false; 3433 3434 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 3435 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 3436 RD->getIdentifier()->isStr("destroying_delete_t"); 3437 } 3438 3439 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 3440 return getDeclLanguageLinkage(*this); 3441 } 3442 3443 bool FunctionDecl::isExternC() const { 3444 return isDeclExternC(*this); 3445 } 3446 3447 bool FunctionDecl::isInExternCContext() const { 3448 if (hasAttr<OpenCLKernelAttr>()) 3449 return true; 3450 return getLexicalDeclContext()->isExternCContext(); 3451 } 3452 3453 bool FunctionDecl::isInExternCXXContext() const { 3454 return getLexicalDeclContext()->isExternCXXContext(); 3455 } 3456 3457 bool FunctionDecl::isGlobal() const { 3458 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 3459 return Method->isStatic(); 3460 3461 if (getCanonicalDecl()->getStorageClass() == SC_Static) 3462 return false; 3463 3464 for (const DeclContext *DC = getDeclContext(); 3465 DC->isNamespace(); 3466 DC = DC->getParent()) { 3467 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 3468 if (!Namespace->getDeclName()) 3469 return false; 3470 } 3471 } 3472 3473 return true; 3474 } 3475 3476 bool FunctionDecl::isNoReturn() const { 3477 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 3478 hasAttr<C11NoReturnAttr>()) 3479 return true; 3480 3481 if (auto *FnTy = getType()->getAs<FunctionType>()) 3482 return FnTy->getNoReturnAttr(); 3483 3484 return false; 3485 } 3486 3487 bool FunctionDecl::isMemberLikeConstrainedFriend() const { 3488 // C++20 [temp.friend]p9: 3489 // A non-template friend declaration with a requires-clause [or] 3490 // a friend function template with a constraint that depends on a template 3491 // parameter from an enclosing template [...] does not declare the same 3492 // function or function template as a declaration in any other scope. 3493 3494 // If this isn't a friend then it's not a member-like constrained friend. 3495 if (!getFriendObjectKind()) { 3496 return false; 3497 } 3498 3499 if (!getDescribedFunctionTemplate()) { 3500 // If these friends don't have constraints, they aren't constrained, and 3501 // thus don't fall under temp.friend p9. Else the simple presence of a 3502 // constraint makes them unique. 3503 return getTrailingRequiresClause(); 3504 } 3505 3506 return FriendConstraintRefersToEnclosingTemplate(); 3507 } 3508 3509 MultiVersionKind FunctionDecl::getMultiVersionKind() const { 3510 if (hasAttr<TargetAttr>()) 3511 return MultiVersionKind::Target; 3512 if (hasAttr<TargetVersionAttr>()) 3513 return MultiVersionKind::TargetVersion; 3514 if (hasAttr<CPUDispatchAttr>()) 3515 return MultiVersionKind::CPUDispatch; 3516 if (hasAttr<CPUSpecificAttr>()) 3517 return MultiVersionKind::CPUSpecific; 3518 if (hasAttr<TargetClonesAttr>()) 3519 return MultiVersionKind::TargetClones; 3520 return MultiVersionKind::None; 3521 } 3522 3523 bool FunctionDecl::isCPUDispatchMultiVersion() const { 3524 return isMultiVersion() && hasAttr<CPUDispatchAttr>(); 3525 } 3526 3527 bool FunctionDecl::isCPUSpecificMultiVersion() const { 3528 return isMultiVersion() && hasAttr<CPUSpecificAttr>(); 3529 } 3530 3531 bool FunctionDecl::isTargetMultiVersion() const { 3532 return isMultiVersion() && 3533 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>()); 3534 } 3535 3536 bool FunctionDecl::isTargetClonesMultiVersion() const { 3537 return isMultiVersion() && hasAttr<TargetClonesAttr>(); 3538 } 3539 3540 void 3541 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 3542 redeclarable_base::setPreviousDecl(PrevDecl); 3543 3544 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 3545 FunctionTemplateDecl *PrevFunTmpl 3546 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 3547 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 3548 FunTmpl->setPreviousDecl(PrevFunTmpl); 3549 } 3550 3551 if (PrevDecl && PrevDecl->isInlined()) 3552 setImplicitlyInline(true); 3553 } 3554 3555 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 3556 3557 /// Returns a value indicating whether this function corresponds to a builtin 3558 /// function. 3559 /// 3560 /// The function corresponds to a built-in function if it is declared at 3561 /// translation scope or within an extern "C" block and its name matches with 3562 /// the name of a builtin. The returned value will be 0 for functions that do 3563 /// not correspond to a builtin, a value of type \c Builtin::ID if in the 3564 /// target-independent range \c [1,Builtin::First), or a target-specific builtin 3565 /// value. 3566 /// 3567 /// \param ConsiderWrapperFunctions If true, we should consider wrapper 3568 /// functions as their wrapped builtins. This shouldn't be done in general, but 3569 /// it's useful in Sema to diagnose calls to wrappers based on their semantics. 3570 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { 3571 unsigned BuiltinID = 0; 3572 3573 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) { 3574 BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); 3575 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) { 3576 BuiltinID = BAA->getBuiltinName()->getBuiltinID(); 3577 } else if (const auto *A = getAttr<BuiltinAttr>()) { 3578 BuiltinID = A->getID(); 3579 } 3580 3581 if (!BuiltinID) 3582 return 0; 3583 3584 // If the function is marked "overloadable", it has a different mangled name 3585 // and is not the C library function. 3586 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() && 3587 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>())) 3588 return 0; 3589 3590 const ASTContext &Context = getASTContext(); 3591 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3592 return BuiltinID; 3593 3594 // This function has the name of a known C library 3595 // function. Determine whether it actually refers to the C library 3596 // function or whether it just has the same name. 3597 3598 // If this is a static function, it's not a builtin. 3599 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static) 3600 return 0; 3601 3602 // OpenCL v1.2 s6.9.f - The library functions defined in 3603 // the C99 standard headers are not available. 3604 if (Context.getLangOpts().OpenCL && 3605 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3606 return 0; 3607 3608 // CUDA does not have device-side standard library. printf and malloc are the 3609 // only special cases that are supported by device-side runtime. 3610 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && 3611 !hasAttr<CUDAHostAttr>() && 3612 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3613 return 0; 3614 3615 // As AMDGCN implementation of OpenMP does not have a device-side standard 3616 // library, none of the predefined library functions except printf and malloc 3617 // should be treated as a builtin i.e. 0 should be returned for them. 3618 if (Context.getTargetInfo().getTriple().isAMDGCN() && 3619 Context.getLangOpts().OpenMPIsTargetDevice && 3620 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 3621 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3622 return 0; 3623 3624 return BuiltinID; 3625 } 3626 3627 /// getNumParams - Return the number of parameters this function must have 3628 /// based on its FunctionType. This is the length of the ParamInfo array 3629 /// after it has been created. 3630 unsigned FunctionDecl::getNumParams() const { 3631 const auto *FPT = getType()->getAs<FunctionProtoType>(); 3632 return FPT ? FPT->getNumParams() : 0; 3633 } 3634 3635 void FunctionDecl::setParams(ASTContext &C, 3636 ArrayRef<ParmVarDecl *> NewParamInfo) { 3637 assert(!ParamInfo && "Already has param info!"); 3638 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 3639 3640 // Zero params -> null pointer. 3641 if (!NewParamInfo.empty()) { 3642 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 3643 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3644 } 3645 } 3646 3647 /// getMinRequiredArguments - Returns the minimum number of arguments 3648 /// needed to call this function. This may be fewer than the number of 3649 /// function parameters, if some of the parameters have default 3650 /// arguments (in C++) or are parameter packs (C++11). 3651 unsigned FunctionDecl::getMinRequiredArguments() const { 3652 if (!getASTContext().getLangOpts().CPlusPlus) 3653 return getNumParams(); 3654 3655 // Note that it is possible for a parameter with no default argument to 3656 // follow a parameter with a default argument. 3657 unsigned NumRequiredArgs = 0; 3658 unsigned MinParamsSoFar = 0; 3659 for (auto *Param : parameters()) { 3660 if (!Param->isParameterPack()) { 3661 ++MinParamsSoFar; 3662 if (!Param->hasDefaultArg()) 3663 NumRequiredArgs = MinParamsSoFar; 3664 } 3665 } 3666 return NumRequiredArgs; 3667 } 3668 3669 bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const { 3670 return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter(); 3671 } 3672 3673 unsigned FunctionDecl::getNumNonObjectParams() const { 3674 return getNumParams() - 3675 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); 3676 } 3677 3678 unsigned FunctionDecl::getMinRequiredExplicitArguments() const { 3679 return getMinRequiredArguments() - 3680 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter()); 3681 } 3682 3683 bool FunctionDecl::hasOneParamOrDefaultArgs() const { 3684 return getNumParams() == 1 || 3685 (getNumParams() > 1 && 3686 llvm::all_of(llvm::drop_begin(parameters()), 3687 [](ParmVarDecl *P) { return P->hasDefaultArg(); })); 3688 } 3689 3690 /// The combination of the extern and inline keywords under MSVC forces 3691 /// the function to be required. 3692 /// 3693 /// Note: This function assumes that we will only get called when isInlined() 3694 /// would return true for this FunctionDecl. 3695 bool FunctionDecl::isMSExternInline() const { 3696 assert(isInlined() && "expected to get called on an inlined function!"); 3697 3698 const ASTContext &Context = getASTContext(); 3699 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 3700 !hasAttr<DLLExportAttr>()) 3701 return false; 3702 3703 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 3704 FD = FD->getPreviousDecl()) 3705 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3706 return true; 3707 3708 return false; 3709 } 3710 3711 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 3712 if (Redecl->getStorageClass() != SC_Extern) 3713 return false; 3714 3715 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 3716 FD = FD->getPreviousDecl()) 3717 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3718 return false; 3719 3720 return true; 3721 } 3722 3723 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 3724 // Only consider file-scope declarations in this test. 3725 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 3726 return false; 3727 3728 // Only consider explicit declarations; the presence of a builtin for a 3729 // libcall shouldn't affect whether a definition is externally visible. 3730 if (Redecl->isImplicit()) 3731 return false; 3732 3733 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 3734 return true; // Not an inline definition 3735 3736 return false; 3737 } 3738 3739 /// For a function declaration in C or C++, determine whether this 3740 /// declaration causes the definition to be externally visible. 3741 /// 3742 /// For instance, this determines if adding the current declaration to the set 3743 /// of redeclarations of the given functions causes 3744 /// isInlineDefinitionExternallyVisible to change from false to true. 3745 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 3746 assert(!doesThisDeclarationHaveABody() && 3747 "Must have a declaration without a body."); 3748 3749 const ASTContext &Context = getASTContext(); 3750 3751 if (Context.getLangOpts().MSVCCompat) { 3752 const FunctionDecl *Definition; 3753 if (hasBody(Definition) && Definition->isInlined() && 3754 redeclForcesDefMSVC(this)) 3755 return true; 3756 } 3757 3758 if (Context.getLangOpts().CPlusPlus) 3759 return false; 3760 3761 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3762 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3763 // an externally visible definition. 3764 // 3765 // FIXME: What happens if gnu_inline gets added on after the first 3766 // declaration? 3767 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3768 return false; 3769 3770 const FunctionDecl *Prev = this; 3771 bool FoundBody = false; 3772 while ((Prev = Prev->getPreviousDecl())) { 3773 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3774 3775 if (Prev->doesThisDeclarationHaveABody()) { 3776 // If it's not the case that both 'inline' and 'extern' are 3777 // specified on the definition, then it is always externally visible. 3778 if (!Prev->isInlineSpecified() || 3779 Prev->getStorageClass() != SC_Extern) 3780 return false; 3781 } else if (Prev->isInlineSpecified() && 3782 Prev->getStorageClass() != SC_Extern) { 3783 return false; 3784 } 3785 } 3786 return FoundBody; 3787 } 3788 3789 // C99 6.7.4p6: 3790 // [...] If all of the file scope declarations for a function in a 3791 // translation unit include the inline function specifier without extern, 3792 // then the definition in that translation unit is an inline definition. 3793 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3794 return false; 3795 const FunctionDecl *Prev = this; 3796 bool FoundBody = false; 3797 while ((Prev = Prev->getPreviousDecl())) { 3798 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3799 if (RedeclForcesDefC99(Prev)) 3800 return false; 3801 } 3802 return FoundBody; 3803 } 3804 3805 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { 3806 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3807 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>() 3808 : FunctionTypeLoc(); 3809 } 3810 3811 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3812 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3813 if (!FTL) 3814 return SourceRange(); 3815 3816 // Skip self-referential return types. 3817 const SourceManager &SM = getASTContext().getSourceManager(); 3818 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3819 SourceLocation Boundary = getNameInfo().getBeginLoc(); 3820 if (RTRange.isInvalid() || Boundary.isInvalid() || 3821 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3822 return SourceRange(); 3823 3824 return RTRange; 3825 } 3826 3827 SourceRange FunctionDecl::getParametersSourceRange() const { 3828 unsigned NP = getNumParams(); 3829 SourceLocation EllipsisLoc = getEllipsisLoc(); 3830 3831 if (NP == 0 && EllipsisLoc.isInvalid()) 3832 return SourceRange(); 3833 3834 SourceLocation Begin = 3835 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc; 3836 SourceLocation End = EllipsisLoc.isValid() 3837 ? EllipsisLoc 3838 : ParamInfo[NP - 1]->getSourceRange().getEnd(); 3839 3840 return SourceRange(Begin, End); 3841 } 3842 3843 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3844 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3845 return FTL ? FTL.getExceptionSpecRange() : SourceRange(); 3846 } 3847 3848 /// For an inline function definition in C, or for a gnu_inline function 3849 /// in C++, determine whether the definition will be externally visible. 3850 /// 3851 /// Inline function definitions are always available for inlining optimizations. 3852 /// However, depending on the language dialect, declaration specifiers, and 3853 /// attributes, the definition of an inline function may or may not be 3854 /// "externally" visible to other translation units in the program. 3855 /// 3856 /// In C99, inline definitions are not externally visible by default. However, 3857 /// if even one of the global-scope declarations is marked "extern inline", the 3858 /// inline definition becomes externally visible (C99 6.7.4p6). 3859 /// 3860 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3861 /// definition, we use the GNU semantics for inline, which are nearly the 3862 /// opposite of C99 semantics. In particular, "inline" by itself will create 3863 /// an externally visible symbol, but "extern inline" will not create an 3864 /// externally visible symbol. 3865 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3866 assert((doesThisDeclarationHaveABody() || willHaveBody() || 3867 hasAttr<AliasAttr>()) && 3868 "Must be a function definition"); 3869 assert(isInlined() && "Function must be inline"); 3870 ASTContext &Context = getASTContext(); 3871 3872 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3873 // Note: If you change the logic here, please change 3874 // doesDeclarationForceExternallyVisibleDefinition as well. 3875 // 3876 // If it's not the case that both 'inline' and 'extern' are 3877 // specified on the definition, then this inline definition is 3878 // externally visible. 3879 if (Context.getLangOpts().CPlusPlus) 3880 return false; 3881 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3882 return true; 3883 3884 // If any declaration is 'inline' but not 'extern', then this definition 3885 // is externally visible. 3886 for (auto *Redecl : redecls()) { 3887 if (Redecl->isInlineSpecified() && 3888 Redecl->getStorageClass() != SC_Extern) 3889 return true; 3890 } 3891 3892 return false; 3893 } 3894 3895 // The rest of this function is C-only. 3896 assert(!Context.getLangOpts().CPlusPlus && 3897 "should not use C inline rules in C++"); 3898 3899 // C99 6.7.4p6: 3900 // [...] If all of the file scope declarations for a function in a 3901 // translation unit include the inline function specifier without extern, 3902 // then the definition in that translation unit is an inline definition. 3903 for (auto *Redecl : redecls()) { 3904 if (RedeclForcesDefC99(Redecl)) 3905 return true; 3906 } 3907 3908 // C99 6.7.4p6: 3909 // An inline definition does not provide an external definition for the 3910 // function, and does not forbid an external definition in another 3911 // translation unit. 3912 return false; 3913 } 3914 3915 /// getOverloadedOperator - Which C++ overloaded operator this 3916 /// function represents, if any. 3917 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3918 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3919 return getDeclName().getCXXOverloadedOperator(); 3920 return OO_None; 3921 } 3922 3923 /// getLiteralIdentifier - The literal suffix identifier this function 3924 /// represents, if any. 3925 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3926 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3927 return getDeclName().getCXXLiteralIdentifier(); 3928 return nullptr; 3929 } 3930 3931 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 3932 if (TemplateOrSpecialization.isNull()) 3933 return TK_NonTemplate; 3934 if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) { 3935 if (isa<FunctionDecl>(ND)) 3936 return TK_DependentNonTemplate; 3937 assert(isa<FunctionTemplateDecl>(ND) && 3938 "No other valid types in NamedDecl"); 3939 return TK_FunctionTemplate; 3940 } 3941 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 3942 return TK_MemberSpecialization; 3943 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 3944 return TK_FunctionTemplateSpecialization; 3945 if (TemplateOrSpecialization.is 3946 <DependentFunctionTemplateSpecializationInfo*>()) 3947 return TK_DependentFunctionTemplateSpecialization; 3948 3949 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 3950 } 3951 3952 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 3953 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 3954 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 3955 3956 return nullptr; 3957 } 3958 3959 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 3960 if (auto *MSI = 3961 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3962 return MSI; 3963 if (auto *FTSI = TemplateOrSpecialization 3964 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 3965 return FTSI->getMemberSpecializationInfo(); 3966 return nullptr; 3967 } 3968 3969 void 3970 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 3971 FunctionDecl *FD, 3972 TemplateSpecializationKind TSK) { 3973 assert(TemplateOrSpecialization.isNull() && 3974 "Member function is already a specialization"); 3975 MemberSpecializationInfo *Info 3976 = new (C) MemberSpecializationInfo(FD, TSK); 3977 TemplateOrSpecialization = Info; 3978 } 3979 3980 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 3981 return dyn_cast_if_present<FunctionTemplateDecl>( 3982 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 3983 } 3984 3985 void FunctionDecl::setDescribedFunctionTemplate( 3986 FunctionTemplateDecl *Template) { 3987 assert(TemplateOrSpecialization.isNull() && 3988 "Member function is already a specialization"); 3989 TemplateOrSpecialization = Template; 3990 } 3991 3992 bool FunctionDecl::isFunctionTemplateSpecialization() const { 3993 return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() || 3994 TemplateOrSpecialization 3995 .is<DependentFunctionTemplateSpecializationInfo *>(); 3996 } 3997 3998 void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) { 3999 assert(TemplateOrSpecialization.isNull() && 4000 "Function is already a specialization"); 4001 TemplateOrSpecialization = FD; 4002 } 4003 4004 FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const { 4005 return dyn_cast_if_present<FunctionDecl>( 4006 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 4007 } 4008 4009 bool FunctionDecl::isImplicitlyInstantiable() const { 4010 // If the function is invalid, it can't be implicitly instantiated. 4011 if (isInvalidDecl()) 4012 return false; 4013 4014 switch (getTemplateSpecializationKindForInstantiation()) { 4015 case TSK_Undeclared: 4016 case TSK_ExplicitInstantiationDefinition: 4017 case TSK_ExplicitSpecialization: 4018 return false; 4019 4020 case TSK_ImplicitInstantiation: 4021 return true; 4022 4023 case TSK_ExplicitInstantiationDeclaration: 4024 // Handled below. 4025 break; 4026 } 4027 4028 // Find the actual template from which we will instantiate. 4029 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 4030 bool HasPattern = false; 4031 if (PatternDecl) 4032 HasPattern = PatternDecl->hasBody(PatternDecl); 4033 4034 // C++0x [temp.explicit]p9: 4035 // Except for inline functions, other explicit instantiation declarations 4036 // have the effect of suppressing the implicit instantiation of the entity 4037 // to which they refer. 4038 if (!HasPattern || !PatternDecl) 4039 return true; 4040 4041 return PatternDecl->isInlined(); 4042 } 4043 4044 bool FunctionDecl::isTemplateInstantiation() const { 4045 // FIXME: Remove this, it's not clear what it means. (Which template 4046 // specialization kind?) 4047 return clang::isTemplateInstantiation(getTemplateSpecializationKind()); 4048 } 4049 4050 FunctionDecl * 4051 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const { 4052 // If this is a generic lambda call operator specialization, its 4053 // instantiation pattern is always its primary template's pattern 4054 // even if its primary template was instantiated from another 4055 // member template (which happens with nested generic lambdas). 4056 // Since a lambda's call operator's body is transformed eagerly, 4057 // we don't have to go hunting for a prototype definition template 4058 // (i.e. instantiated-from-member-template) to use as an instantiation 4059 // pattern. 4060 4061 if (isGenericLambdaCallOperatorSpecialization( 4062 dyn_cast<CXXMethodDecl>(this))) { 4063 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 4064 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 4065 } 4066 4067 // Check for a declaration of this function that was instantiated from a 4068 // friend definition. 4069 const FunctionDecl *FD = nullptr; 4070 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true)) 4071 FD = this; 4072 4073 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) { 4074 if (ForDefinition && 4075 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind())) 4076 return nullptr; 4077 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom())); 4078 } 4079 4080 if (ForDefinition && 4081 !clang::isTemplateInstantiation(getTemplateSpecializationKind())) 4082 return nullptr; 4083 4084 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 4085 // If we hit a point where the user provided a specialization of this 4086 // template, we're done looking. 4087 while (!ForDefinition || !Primary->isMemberSpecialization()) { 4088 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate(); 4089 if (!NewPrimary) 4090 break; 4091 Primary = NewPrimary; 4092 } 4093 4094 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 4095 } 4096 4097 return nullptr; 4098 } 4099 4100 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 4101 if (FunctionTemplateSpecializationInfo *Info 4102 = TemplateOrSpecialization 4103 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4104 return Info->getTemplate(); 4105 } 4106 return nullptr; 4107 } 4108 4109 FunctionTemplateSpecializationInfo * 4110 FunctionDecl::getTemplateSpecializationInfo() const { 4111 return TemplateOrSpecialization 4112 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 4113 } 4114 4115 const TemplateArgumentList * 4116 FunctionDecl::getTemplateSpecializationArgs() const { 4117 if (FunctionTemplateSpecializationInfo *Info 4118 = TemplateOrSpecialization 4119 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4120 return Info->TemplateArguments; 4121 } 4122 return nullptr; 4123 } 4124 4125 const ASTTemplateArgumentListInfo * 4126 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 4127 if (FunctionTemplateSpecializationInfo *Info 4128 = TemplateOrSpecialization 4129 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 4130 return Info->TemplateArgumentsAsWritten; 4131 } 4132 if (DependentFunctionTemplateSpecializationInfo *Info = 4133 TemplateOrSpecialization 4134 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) { 4135 return Info->TemplateArgumentsAsWritten; 4136 } 4137 return nullptr; 4138 } 4139 4140 void 4141 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 4142 FunctionTemplateDecl *Template, 4143 const TemplateArgumentList *TemplateArgs, 4144 void *InsertPos, 4145 TemplateSpecializationKind TSK, 4146 const TemplateArgumentListInfo *TemplateArgsAsWritten, 4147 SourceLocation PointOfInstantiation) { 4148 assert((TemplateOrSpecialization.isNull() || 4149 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && 4150 "Member function is already a specialization"); 4151 assert(TSK != TSK_Undeclared && 4152 "Must specify the type of function template specialization"); 4153 assert((TemplateOrSpecialization.isNull() || 4154 getFriendObjectKind() != FOK_None || 4155 TSK == TSK_ExplicitSpecialization) && 4156 "Member specialization must be an explicit specialization"); 4157 FunctionTemplateSpecializationInfo *Info = 4158 FunctionTemplateSpecializationInfo::Create( 4159 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten, 4160 PointOfInstantiation, 4161 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()); 4162 TemplateOrSpecialization = Info; 4163 Template->addSpecialization(Info, InsertPos); 4164 } 4165 4166 void FunctionDecl::setDependentTemplateSpecialization( 4167 ASTContext &Context, const UnresolvedSetImpl &Templates, 4168 const TemplateArgumentListInfo *TemplateArgs) { 4169 assert(TemplateOrSpecialization.isNull()); 4170 DependentFunctionTemplateSpecializationInfo *Info = 4171 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 4172 TemplateArgs); 4173 TemplateOrSpecialization = Info; 4174 } 4175 4176 DependentFunctionTemplateSpecializationInfo * 4177 FunctionDecl::getDependentSpecializationInfo() const { 4178 return TemplateOrSpecialization 4179 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 4180 } 4181 4182 DependentFunctionTemplateSpecializationInfo * 4183 DependentFunctionTemplateSpecializationInfo::Create( 4184 ASTContext &Context, const UnresolvedSetImpl &Candidates, 4185 const TemplateArgumentListInfo *TArgs) { 4186 const auto *TArgsWritten = 4187 TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr; 4188 return new (Context.Allocate( 4189 totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size()))) 4190 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten); 4191 } 4192 4193 DependentFunctionTemplateSpecializationInfo:: 4194 DependentFunctionTemplateSpecializationInfo( 4195 const UnresolvedSetImpl &Candidates, 4196 const ASTTemplateArgumentListInfo *TemplateArgsWritten) 4197 : NumCandidates(Candidates.size()), 4198 TemplateArgumentsAsWritten(TemplateArgsWritten) { 4199 std::transform(Candidates.begin(), Candidates.end(), 4200 getTrailingObjects<FunctionTemplateDecl *>(), 4201 [](NamedDecl *ND) { 4202 return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl()); 4203 }); 4204 } 4205 4206 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 4207 // For a function template specialization, query the specialization 4208 // information object. 4209 if (FunctionTemplateSpecializationInfo *FTSInfo = 4210 TemplateOrSpecialization 4211 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 4212 return FTSInfo->getTemplateSpecializationKind(); 4213 4214 if (MemberSpecializationInfo *MSInfo = 4215 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4216 return MSInfo->getTemplateSpecializationKind(); 4217 4218 // A dependent function template specialization is an explicit specialization, 4219 // except when it's a friend declaration. 4220 if (TemplateOrSpecialization 4221 .is<DependentFunctionTemplateSpecializationInfo *>() && 4222 getFriendObjectKind() == FOK_None) 4223 return TSK_ExplicitSpecialization; 4224 4225 return TSK_Undeclared; 4226 } 4227 4228 TemplateSpecializationKind 4229 FunctionDecl::getTemplateSpecializationKindForInstantiation() const { 4230 // This is the same as getTemplateSpecializationKind(), except that for a 4231 // function that is both a function template specialization and a member 4232 // specialization, we prefer the member specialization information. Eg: 4233 // 4234 // template<typename T> struct A { 4235 // template<typename U> void f() {} 4236 // template<> void f<int>() {} 4237 // }; 4238 // 4239 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function 4240 // template specialization; both getTemplateSpecializationKind() and 4241 // getTemplateSpecializationKindForInstantiation() will return 4242 // TSK_ExplicitSpecialization. 4243 // 4244 // For A<int>::f<int>(): 4245 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization 4246 // * getTemplateSpecializationKindForInstantiation() will return 4247 // TSK_ImplicitInstantiation 4248 // 4249 // This reflects the facts that A<int>::f<int> is an explicit specialization 4250 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated 4251 // from A::f<int> if a definition is needed. 4252 if (FunctionTemplateSpecializationInfo *FTSInfo = 4253 TemplateOrSpecialization 4254 .dyn_cast<FunctionTemplateSpecializationInfo *>()) { 4255 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo()) 4256 return MSInfo->getTemplateSpecializationKind(); 4257 return FTSInfo->getTemplateSpecializationKind(); 4258 } 4259 4260 if (MemberSpecializationInfo *MSInfo = 4261 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4262 return MSInfo->getTemplateSpecializationKind(); 4263 4264 if (TemplateOrSpecialization 4265 .is<DependentFunctionTemplateSpecializationInfo *>() && 4266 getFriendObjectKind() == FOK_None) 4267 return TSK_ExplicitSpecialization; 4268 4269 return TSK_Undeclared; 4270 } 4271 4272 void 4273 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4274 SourceLocation PointOfInstantiation) { 4275 if (FunctionTemplateSpecializationInfo *FTSInfo 4276 = TemplateOrSpecialization.dyn_cast< 4277 FunctionTemplateSpecializationInfo*>()) { 4278 FTSInfo->setTemplateSpecializationKind(TSK); 4279 if (TSK != TSK_ExplicitSpecialization && 4280 PointOfInstantiation.isValid() && 4281 FTSInfo->getPointOfInstantiation().isInvalid()) { 4282 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 4283 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4284 L->InstantiationRequested(this); 4285 } 4286 } else if (MemberSpecializationInfo *MSInfo 4287 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 4288 MSInfo->setTemplateSpecializationKind(TSK); 4289 if (TSK != TSK_ExplicitSpecialization && 4290 PointOfInstantiation.isValid() && 4291 MSInfo->getPointOfInstantiation().isInvalid()) { 4292 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4293 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4294 L->InstantiationRequested(this); 4295 } 4296 } else 4297 llvm_unreachable("Function cannot have a template specialization kind"); 4298 } 4299 4300 SourceLocation FunctionDecl::getPointOfInstantiation() const { 4301 if (FunctionTemplateSpecializationInfo *FTSInfo 4302 = TemplateOrSpecialization.dyn_cast< 4303 FunctionTemplateSpecializationInfo*>()) 4304 return FTSInfo->getPointOfInstantiation(); 4305 if (MemberSpecializationInfo *MSInfo = 4306 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4307 return MSInfo->getPointOfInstantiation(); 4308 4309 return SourceLocation(); 4310 } 4311 4312 bool FunctionDecl::isOutOfLine() const { 4313 if (Decl::isOutOfLine()) 4314 return true; 4315 4316 // If this function was instantiated from a member function of a 4317 // class template, check whether that member function was defined out-of-line. 4318 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 4319 const FunctionDecl *Definition; 4320 if (FD->hasBody(Definition)) 4321 return Definition->isOutOfLine(); 4322 } 4323 4324 // If this function was instantiated from a function template, 4325 // check whether that function template was defined out-of-line. 4326 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 4327 const FunctionDecl *Definition; 4328 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 4329 return Definition->isOutOfLine(); 4330 } 4331 4332 return false; 4333 } 4334 4335 SourceRange FunctionDecl::getSourceRange() const { 4336 return SourceRange(getOuterLocStart(), EndRangeLoc); 4337 } 4338 4339 unsigned FunctionDecl::getMemoryFunctionKind() const { 4340 IdentifierInfo *FnInfo = getIdentifier(); 4341 4342 if (!FnInfo) 4343 return 0; 4344 4345 // Builtin handling. 4346 switch (getBuiltinID()) { 4347 case Builtin::BI__builtin_memset: 4348 case Builtin::BI__builtin___memset_chk: 4349 case Builtin::BImemset: 4350 return Builtin::BImemset; 4351 4352 case Builtin::BI__builtin_memcpy: 4353 case Builtin::BI__builtin___memcpy_chk: 4354 case Builtin::BImemcpy: 4355 return Builtin::BImemcpy; 4356 4357 case Builtin::BI__builtin_mempcpy: 4358 case Builtin::BI__builtin___mempcpy_chk: 4359 case Builtin::BImempcpy: 4360 return Builtin::BImempcpy; 4361 4362 case Builtin::BI__builtin_memmove: 4363 case Builtin::BI__builtin___memmove_chk: 4364 case Builtin::BImemmove: 4365 return Builtin::BImemmove; 4366 4367 case Builtin::BIstrlcpy: 4368 case Builtin::BI__builtin___strlcpy_chk: 4369 return Builtin::BIstrlcpy; 4370 4371 case Builtin::BIstrlcat: 4372 case Builtin::BI__builtin___strlcat_chk: 4373 return Builtin::BIstrlcat; 4374 4375 case Builtin::BI__builtin_memcmp: 4376 case Builtin::BImemcmp: 4377 return Builtin::BImemcmp; 4378 4379 case Builtin::BI__builtin_bcmp: 4380 case Builtin::BIbcmp: 4381 return Builtin::BIbcmp; 4382 4383 case Builtin::BI__builtin_strncpy: 4384 case Builtin::BI__builtin___strncpy_chk: 4385 case Builtin::BIstrncpy: 4386 return Builtin::BIstrncpy; 4387 4388 case Builtin::BI__builtin_strncmp: 4389 case Builtin::BIstrncmp: 4390 return Builtin::BIstrncmp; 4391 4392 case Builtin::BI__builtin_strncasecmp: 4393 case Builtin::BIstrncasecmp: 4394 return Builtin::BIstrncasecmp; 4395 4396 case Builtin::BI__builtin_strncat: 4397 case Builtin::BI__builtin___strncat_chk: 4398 case Builtin::BIstrncat: 4399 return Builtin::BIstrncat; 4400 4401 case Builtin::BI__builtin_strndup: 4402 case Builtin::BIstrndup: 4403 return Builtin::BIstrndup; 4404 4405 case Builtin::BI__builtin_strlen: 4406 case Builtin::BIstrlen: 4407 return Builtin::BIstrlen; 4408 4409 case Builtin::BI__builtin_bzero: 4410 case Builtin::BIbzero: 4411 return Builtin::BIbzero; 4412 4413 case Builtin::BI__builtin_bcopy: 4414 case Builtin::BIbcopy: 4415 return Builtin::BIbcopy; 4416 4417 case Builtin::BIfree: 4418 return Builtin::BIfree; 4419 4420 default: 4421 if (isExternC()) { 4422 if (FnInfo->isStr("memset")) 4423 return Builtin::BImemset; 4424 if (FnInfo->isStr("memcpy")) 4425 return Builtin::BImemcpy; 4426 if (FnInfo->isStr("mempcpy")) 4427 return Builtin::BImempcpy; 4428 if (FnInfo->isStr("memmove")) 4429 return Builtin::BImemmove; 4430 if (FnInfo->isStr("memcmp")) 4431 return Builtin::BImemcmp; 4432 if (FnInfo->isStr("bcmp")) 4433 return Builtin::BIbcmp; 4434 if (FnInfo->isStr("strncpy")) 4435 return Builtin::BIstrncpy; 4436 if (FnInfo->isStr("strncmp")) 4437 return Builtin::BIstrncmp; 4438 if (FnInfo->isStr("strncasecmp")) 4439 return Builtin::BIstrncasecmp; 4440 if (FnInfo->isStr("strncat")) 4441 return Builtin::BIstrncat; 4442 if (FnInfo->isStr("strndup")) 4443 return Builtin::BIstrndup; 4444 if (FnInfo->isStr("strlen")) 4445 return Builtin::BIstrlen; 4446 if (FnInfo->isStr("bzero")) 4447 return Builtin::BIbzero; 4448 if (FnInfo->isStr("bcopy")) 4449 return Builtin::BIbcopy; 4450 } else if (isInStdNamespace()) { 4451 if (FnInfo->isStr("free")) 4452 return Builtin::BIfree; 4453 } 4454 break; 4455 } 4456 return 0; 4457 } 4458 4459 unsigned FunctionDecl::getODRHash() const { 4460 assert(hasODRHash()); 4461 return ODRHash; 4462 } 4463 4464 unsigned FunctionDecl::getODRHash() { 4465 if (hasODRHash()) 4466 return ODRHash; 4467 4468 if (auto *FT = getInstantiatedFromMemberFunction()) { 4469 setHasODRHash(true); 4470 ODRHash = FT->getODRHash(); 4471 return ODRHash; 4472 } 4473 4474 class ODRHash Hash; 4475 Hash.AddFunctionDecl(this); 4476 setHasODRHash(true); 4477 ODRHash = Hash.CalculateHash(); 4478 return ODRHash; 4479 } 4480 4481 //===----------------------------------------------------------------------===// 4482 // FieldDecl Implementation 4483 //===----------------------------------------------------------------------===// 4484 4485 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 4486 SourceLocation StartLoc, SourceLocation IdLoc, 4487 IdentifierInfo *Id, QualType T, 4488 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 4489 InClassInitStyle InitStyle) { 4490 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 4491 BW, Mutable, InitStyle); 4492 } 4493 4494 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4495 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 4496 SourceLocation(), nullptr, QualType(), nullptr, 4497 nullptr, false, ICIS_NoInit); 4498 } 4499 4500 bool FieldDecl::isAnonymousStructOrUnion() const { 4501 if (!isImplicit() || getDeclName()) 4502 return false; 4503 4504 if (const auto *Record = getType()->getAs<RecordType>()) 4505 return Record->getDecl()->isAnonymousStructOrUnion(); 4506 4507 return false; 4508 } 4509 4510 Expr *FieldDecl::getInClassInitializer() const { 4511 if (!hasInClassInitializer()) 4512 return nullptr; 4513 4514 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init; 4515 return cast_if_present<Expr>( 4516 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource()) 4517 : InitPtr.get(nullptr)); 4518 } 4519 4520 void FieldDecl::setInClassInitializer(Expr *NewInit) { 4521 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit)); 4522 } 4523 4524 void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) { 4525 assert(hasInClassInitializer() && !getInClassInitializer()); 4526 if (BitField) 4527 InitAndBitWidth->Init = NewInit; 4528 else 4529 Init = NewInit; 4530 } 4531 4532 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 4533 assert(isBitField() && "not a bitfield"); 4534 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 4535 } 4536 4537 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const { 4538 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() && 4539 getBitWidthValue(Ctx) == 0; 4540 } 4541 4542 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { 4543 if (isZeroLengthBitField(Ctx)) 4544 return true; 4545 4546 // C++2a [intro.object]p7: 4547 // An object has nonzero size if it 4548 // -- is not a potentially-overlapping subobject, or 4549 if (!hasAttr<NoUniqueAddressAttr>()) 4550 return false; 4551 4552 // -- is not of class type, or 4553 const auto *RT = getType()->getAs<RecordType>(); 4554 if (!RT) 4555 return false; 4556 const RecordDecl *RD = RT->getDecl()->getDefinition(); 4557 if (!RD) { 4558 assert(isInvalidDecl() && "valid field has incomplete type"); 4559 return false; 4560 } 4561 4562 // -- [has] virtual member functions or virtual base classes, or 4563 // -- has subobjects of nonzero size or bit-fields of nonzero length 4564 const auto *CXXRD = cast<CXXRecordDecl>(RD); 4565 if (!CXXRD->isEmpty()) 4566 return false; 4567 4568 // Otherwise, [...] the circumstances under which the object has zero size 4569 // are implementation-defined. 4570 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft()) 4571 return true; 4572 4573 // MS ABI: has nonzero size if it is a class type with class type fields, 4574 // whether or not they have nonzero size 4575 return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) { 4576 return Field->getType()->getAs<RecordType>(); 4577 }); 4578 } 4579 4580 bool FieldDecl::isPotentiallyOverlapping() const { 4581 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl(); 4582 } 4583 4584 unsigned FieldDecl::getFieldIndex() const { 4585 const FieldDecl *Canonical = getCanonicalDecl(); 4586 if (Canonical != this) 4587 return Canonical->getFieldIndex(); 4588 4589 if (CachedFieldIndex) return CachedFieldIndex - 1; 4590 4591 unsigned Index = 0; 4592 const RecordDecl *RD = getParent()->getDefinition(); 4593 assert(RD && "requested index for field of struct with no definition"); 4594 4595 for (auto *Field : RD->fields()) { 4596 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 4597 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 && 4598 "overflow in field numbering"); 4599 ++Index; 4600 } 4601 4602 assert(CachedFieldIndex && "failed to find field in parent"); 4603 return CachedFieldIndex - 1; 4604 } 4605 4606 SourceRange FieldDecl::getSourceRange() const { 4607 const Expr *FinalExpr = getInClassInitializer(); 4608 if (!FinalExpr) 4609 FinalExpr = getBitWidth(); 4610 if (FinalExpr) 4611 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc()); 4612 return DeclaratorDecl::getSourceRange(); 4613 } 4614 4615 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 4616 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 4617 "capturing type in non-lambda or captured record."); 4618 assert(StorageKind == ISK_NoInit && !BitField && 4619 "bit-field or field with default member initializer cannot capture " 4620 "VLA type"); 4621 StorageKind = ISK_CapturedVLAType; 4622 CapturedVLAType = VLAType; 4623 } 4624 4625 void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 4626 // Print unnamed members using name of their type. 4627 if (isAnonymousStructOrUnion()) { 4628 this->getType().print(OS, Policy); 4629 return; 4630 } 4631 // Otherwise, do the normal printing. 4632 DeclaratorDecl::printName(OS, Policy); 4633 } 4634 4635 //===----------------------------------------------------------------------===// 4636 // TagDecl Implementation 4637 //===----------------------------------------------------------------------===// 4638 4639 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, 4640 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, 4641 SourceLocation StartL) 4642 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), 4643 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { 4644 assert((DK != Enum || TK == TagTypeKind::Enum) && 4645 "EnumDecl not matched with TagTypeKind::Enum"); 4646 setPreviousDecl(PrevDecl); 4647 setTagKind(TK); 4648 setCompleteDefinition(false); 4649 setBeingDefined(false); 4650 setEmbeddedInDeclarator(false); 4651 setFreeStanding(false); 4652 setCompleteDefinitionRequired(false); 4653 TagDeclBits.IsThisDeclarationADemotedDefinition = false; 4654 } 4655 4656 SourceLocation TagDecl::getOuterLocStart() const { 4657 return getTemplateOrInnerLocStart(this); 4658 } 4659 4660 SourceRange TagDecl::getSourceRange() const { 4661 SourceLocation RBraceLoc = BraceRange.getEnd(); 4662 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 4663 return SourceRange(getOuterLocStart(), E); 4664 } 4665 4666 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 4667 4668 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 4669 TypedefNameDeclOrQualifier = TDD; 4670 if (const Type *T = getTypeForDecl()) { 4671 (void)T; 4672 assert(T->isLinkageValid()); 4673 } 4674 assert(isLinkageValid()); 4675 } 4676 4677 void TagDecl::startDefinition() { 4678 setBeingDefined(true); 4679 4680 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 4681 struct CXXRecordDecl::DefinitionData *Data = 4682 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 4683 for (auto *I : redecls()) 4684 cast<CXXRecordDecl>(I)->DefinitionData = Data; 4685 } 4686 } 4687 4688 void TagDecl::completeDefinition() { 4689 assert((!isa<CXXRecordDecl>(this) || 4690 cast<CXXRecordDecl>(this)->hasDefinition()) && 4691 "definition completed but not started"); 4692 4693 setCompleteDefinition(true); 4694 setBeingDefined(false); 4695 4696 if (ASTMutationListener *L = getASTMutationListener()) 4697 L->CompletedTagDefinition(this); 4698 } 4699 4700 TagDecl *TagDecl::getDefinition() const { 4701 if (isCompleteDefinition()) 4702 return const_cast<TagDecl *>(this); 4703 4704 // If it's possible for us to have an out-of-date definition, check now. 4705 if (mayHaveOutOfDateDef()) { 4706 if (IdentifierInfo *II = getIdentifier()) { 4707 if (II->isOutOfDate()) { 4708 updateOutOfDate(*II); 4709 } 4710 } 4711 } 4712 4713 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 4714 return CXXRD->getDefinition(); 4715 4716 for (auto *R : redecls()) 4717 if (R->isCompleteDefinition()) 4718 return R; 4719 4720 return nullptr; 4721 } 4722 4723 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 4724 if (QualifierLoc) { 4725 // Make sure the extended qualifier info is allocated. 4726 if (!hasExtInfo()) 4727 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4728 // Set qualifier info. 4729 getExtInfo()->QualifierLoc = QualifierLoc; 4730 } else { 4731 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 4732 if (hasExtInfo()) { 4733 if (getExtInfo()->NumTemplParamLists == 0) { 4734 getASTContext().Deallocate(getExtInfo()); 4735 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 4736 } 4737 else 4738 getExtInfo()->QualifierLoc = QualifierLoc; 4739 } 4740 } 4741 } 4742 4743 void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const { 4744 DeclarationName Name = getDeclName(); 4745 // If the name is supposed to have an identifier but does not have one, then 4746 // the tag is anonymous and we should print it differently. 4747 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) { 4748 // If the caller wanted to print a qualified name, they've already printed 4749 // the scope. And if the caller doesn't want that, the scope information 4750 // is already printed as part of the type. 4751 PrintingPolicy Copy(Policy); 4752 Copy.SuppressScope = true; 4753 getASTContext().getTagDeclType(this).print(OS, Copy); 4754 return; 4755 } 4756 // Otherwise, do the normal printing. 4757 Name.print(OS, Policy); 4758 } 4759 4760 void TagDecl::setTemplateParameterListsInfo( 4761 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 4762 assert(!TPLists.empty()); 4763 // Make sure the extended decl info is allocated. 4764 if (!hasExtInfo()) 4765 // Allocate external info struct. 4766 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4767 // Set the template parameter lists info. 4768 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 4769 } 4770 4771 //===----------------------------------------------------------------------===// 4772 // EnumDecl Implementation 4773 //===----------------------------------------------------------------------===// 4774 4775 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4776 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, 4777 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 4778 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4779 assert(Scoped || !ScopedUsingClassTag); 4780 IntegerType = nullptr; 4781 setNumPositiveBits(0); 4782 setNumNegativeBits(0); 4783 setScoped(Scoped); 4784 setScopedUsingClassTag(ScopedUsingClassTag); 4785 setFixed(Fixed); 4786 setHasODRHash(false); 4787 ODRHash = 0; 4788 } 4789 4790 void EnumDecl::anchor() {} 4791 4792 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 4793 SourceLocation StartLoc, SourceLocation IdLoc, 4794 IdentifierInfo *Id, 4795 EnumDecl *PrevDecl, bool IsScoped, 4796 bool IsScopedUsingClassTag, bool IsFixed) { 4797 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 4798 IsScoped, IsScopedUsingClassTag, IsFixed); 4799 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4800 C.getTypeDeclType(Enum, PrevDecl); 4801 return Enum; 4802 } 4803 4804 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4805 EnumDecl *Enum = 4806 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 4807 nullptr, nullptr, false, false, false); 4808 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4809 return Enum; 4810 } 4811 4812 SourceRange EnumDecl::getIntegerTypeRange() const { 4813 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 4814 return TI->getTypeLoc().getSourceRange(); 4815 return SourceRange(); 4816 } 4817 4818 void EnumDecl::completeDefinition(QualType NewType, 4819 QualType NewPromotionType, 4820 unsigned NumPositiveBits, 4821 unsigned NumNegativeBits) { 4822 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 4823 if (!IntegerType) 4824 IntegerType = NewType.getTypePtr(); 4825 PromotionType = NewPromotionType; 4826 setNumPositiveBits(NumPositiveBits); 4827 setNumNegativeBits(NumNegativeBits); 4828 TagDecl::completeDefinition(); 4829 } 4830 4831 bool EnumDecl::isClosed() const { 4832 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 4833 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 4834 return true; 4835 } 4836 4837 bool EnumDecl::isClosedFlag() const { 4838 return isClosed() && hasAttr<FlagEnumAttr>(); 4839 } 4840 4841 bool EnumDecl::isClosedNonFlag() const { 4842 return isClosed() && !hasAttr<FlagEnumAttr>(); 4843 } 4844 4845 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 4846 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 4847 return MSI->getTemplateSpecializationKind(); 4848 4849 return TSK_Undeclared; 4850 } 4851 4852 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4853 SourceLocation PointOfInstantiation) { 4854 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 4855 assert(MSI && "Not an instantiated member enumeration?"); 4856 MSI->setTemplateSpecializationKind(TSK); 4857 if (TSK != TSK_ExplicitSpecialization && 4858 PointOfInstantiation.isValid() && 4859 MSI->getPointOfInstantiation().isInvalid()) 4860 MSI->setPointOfInstantiation(PointOfInstantiation); 4861 } 4862 4863 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 4864 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 4865 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 4866 EnumDecl *ED = getInstantiatedFromMemberEnum(); 4867 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 4868 ED = NewED; 4869 return getDefinitionOrSelf(ED); 4870 } 4871 } 4872 4873 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 4874 "couldn't find pattern for enum instantiation"); 4875 return nullptr; 4876 } 4877 4878 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 4879 if (SpecializationInfo) 4880 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 4881 4882 return nullptr; 4883 } 4884 4885 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 4886 TemplateSpecializationKind TSK) { 4887 assert(!SpecializationInfo && "Member enum is already a specialization"); 4888 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 4889 } 4890 4891 unsigned EnumDecl::getODRHash() { 4892 if (hasODRHash()) 4893 return ODRHash; 4894 4895 class ODRHash Hash; 4896 Hash.AddEnumDecl(this); 4897 setHasODRHash(true); 4898 ODRHash = Hash.CalculateHash(); 4899 return ODRHash; 4900 } 4901 4902 SourceRange EnumDecl::getSourceRange() const { 4903 auto Res = TagDecl::getSourceRange(); 4904 // Set end-point to enum-base, e.g. enum foo : ^bar 4905 if (auto *TSI = getIntegerTypeSourceInfo()) { 4906 // TagDecl doesn't know about the enum base. 4907 if (!getBraceRange().getEnd().isValid()) 4908 Res.setEnd(TSI->getTypeLoc().getEndLoc()); 4909 } 4910 return Res; 4911 } 4912 4913 void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const { 4914 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType()); 4915 unsigned NumNegativeBits = getNumNegativeBits(); 4916 unsigned NumPositiveBits = getNumPositiveBits(); 4917 4918 if (NumNegativeBits) { 4919 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 4920 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 4921 Min = -Max; 4922 } else { 4923 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 4924 Min = llvm::APInt::getZero(Bitwidth); 4925 } 4926 } 4927 4928 //===----------------------------------------------------------------------===// 4929 // RecordDecl Implementation 4930 //===----------------------------------------------------------------------===// 4931 4932 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 4933 DeclContext *DC, SourceLocation StartLoc, 4934 SourceLocation IdLoc, IdentifierInfo *Id, 4935 RecordDecl *PrevDecl) 4936 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4937 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!"); 4938 setHasFlexibleArrayMember(false); 4939 setAnonymousStructOrUnion(false); 4940 setHasObjectMember(false); 4941 setHasVolatileMember(false); 4942 setHasLoadedFieldsFromExternalStorage(false); 4943 setNonTrivialToPrimitiveDefaultInitialize(false); 4944 setNonTrivialToPrimitiveCopy(false); 4945 setNonTrivialToPrimitiveDestroy(false); 4946 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false); 4947 setHasNonTrivialToPrimitiveDestructCUnion(false); 4948 setHasNonTrivialToPrimitiveCopyCUnion(false); 4949 setParamDestroyedInCallee(false); 4950 setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs); 4951 setIsRandomized(false); 4952 setODRHash(0); 4953 } 4954 4955 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 4956 SourceLocation StartLoc, SourceLocation IdLoc, 4957 IdentifierInfo *Id, RecordDecl* PrevDecl) { 4958 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 4959 StartLoc, IdLoc, Id, PrevDecl); 4960 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4961 4962 C.getTypeDeclType(R, PrevDecl); 4963 return R; 4964 } 4965 4966 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 4967 RecordDecl *R = new (C, ID) 4968 RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(), 4969 SourceLocation(), nullptr, nullptr); 4970 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4971 return R; 4972 } 4973 4974 bool RecordDecl::isInjectedClassName() const { 4975 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 4976 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 4977 } 4978 4979 bool RecordDecl::isLambda() const { 4980 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 4981 return RD->isLambda(); 4982 return false; 4983 } 4984 4985 bool RecordDecl::isCapturedRecord() const { 4986 return hasAttr<CapturedRecordAttr>(); 4987 } 4988 4989 void RecordDecl::setCapturedRecord() { 4990 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 4991 } 4992 4993 bool RecordDecl::isOrContainsUnion() const { 4994 if (isUnion()) 4995 return true; 4996 4997 if (const RecordDecl *Def = getDefinition()) { 4998 for (const FieldDecl *FD : Def->fields()) { 4999 const RecordType *RT = FD->getType()->getAs<RecordType>(); 5000 if (RT && RT->getDecl()->isOrContainsUnion()) 5001 return true; 5002 } 5003 } 5004 5005 return false; 5006 } 5007 5008 RecordDecl::field_iterator RecordDecl::field_begin() const { 5009 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage()) 5010 LoadFieldsFromExternalStorage(); 5011 // This is necessary for correctness for C++ with modules. 5012 // FIXME: Come up with a test case that breaks without definition. 5013 if (RecordDecl *D = getDefinition(); D && D != this) 5014 return D->field_begin(); 5015 return field_iterator(decl_iterator(FirstDecl)); 5016 } 5017 5018 /// completeDefinition - Notes that the definition of this type is now 5019 /// complete. 5020 void RecordDecl::completeDefinition() { 5021 assert(!isCompleteDefinition() && "Cannot redefine record!"); 5022 TagDecl::completeDefinition(); 5023 5024 ASTContext &Ctx = getASTContext(); 5025 5026 // Layouts are dumped when computed, so if we are dumping for all complete 5027 // types, we need to force usage to get types that wouldn't be used elsewhere. 5028 if (Ctx.getLangOpts().DumpRecordLayoutsComplete) 5029 (void)Ctx.getASTRecordLayout(this); 5030 } 5031 5032 /// isMsStruct - Get whether or not this record uses ms_struct layout. 5033 /// This which can be turned on with an attribute, pragma, or the 5034 /// -mms-bitfields command-line option. 5035 bool RecordDecl::isMsStruct(const ASTContext &C) const { 5036 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 5037 } 5038 5039 void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) { 5040 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false); 5041 LastDecl->NextInContextAndBits.setPointer(nullptr); 5042 setIsRandomized(true); 5043 } 5044 5045 void RecordDecl::LoadFieldsFromExternalStorage() const { 5046 ExternalASTSource *Source = getASTContext().getExternalSource(); 5047 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 5048 5049 // Notify that we have a RecordDecl doing some initialization. 5050 ExternalASTSource::Deserializing TheFields(Source); 5051 5052 SmallVector<Decl*, 64> Decls; 5053 setHasLoadedFieldsFromExternalStorage(true); 5054 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 5055 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 5056 }, Decls); 5057 5058 #ifndef NDEBUG 5059 // Check that all decls we got were FieldDecls. 5060 for (unsigned i=0, e=Decls.size(); i != e; ++i) 5061 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 5062 #endif 5063 5064 if (Decls.empty()) 5065 return; 5066 5067 auto [ExternalFirst, ExternalLast] = 5068 BuildDeclChain(Decls, 5069 /*FieldsAlreadyLoaded=*/false); 5070 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 5071 FirstDecl = ExternalFirst; 5072 if (!LastDecl) 5073 LastDecl = ExternalLast; 5074 } 5075 5076 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 5077 ASTContext &Context = getASTContext(); 5078 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 5079 (SanitizerKind::Address | SanitizerKind::KernelAddress); 5080 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 5081 return false; 5082 const auto &NoSanitizeList = Context.getNoSanitizeList(); 5083 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 5084 // We may be able to relax some of these requirements. 5085 int ReasonToReject = -1; 5086 if (!CXXRD || CXXRD->isExternCContext()) 5087 ReasonToReject = 0; // is not C++. 5088 else if (CXXRD->hasAttr<PackedAttr>()) 5089 ReasonToReject = 1; // is packed. 5090 else if (CXXRD->isUnion()) 5091 ReasonToReject = 2; // is a union. 5092 else if (CXXRD->isTriviallyCopyable()) 5093 ReasonToReject = 3; // is trivially copyable. 5094 else if (CXXRD->hasTrivialDestructor()) 5095 ReasonToReject = 4; // has trivial destructor. 5096 else if (CXXRD->isStandardLayout()) 5097 ReasonToReject = 5; // is standard layout. 5098 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), 5099 "field-padding")) 5100 ReasonToReject = 6; // is in an excluded file. 5101 else if (NoSanitizeList.containsType( 5102 EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) 5103 ReasonToReject = 7; // The type is excluded. 5104 5105 if (EmitRemark) { 5106 if (ReasonToReject >= 0) 5107 Context.getDiagnostics().Report( 5108 getLocation(), 5109 diag::remark_sanitize_address_insert_extra_padding_rejected) 5110 << getQualifiedNameAsString() << ReasonToReject; 5111 else 5112 Context.getDiagnostics().Report( 5113 getLocation(), 5114 diag::remark_sanitize_address_insert_extra_padding_accepted) 5115 << getQualifiedNameAsString(); 5116 } 5117 return ReasonToReject < 0; 5118 } 5119 5120 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 5121 for (const auto *I : fields()) { 5122 if (I->getIdentifier()) 5123 return I; 5124 5125 if (const auto *RT = I->getType()->getAs<RecordType>()) 5126 if (const FieldDecl *NamedDataMember = 5127 RT->getDecl()->findFirstNamedDataMember()) 5128 return NamedDataMember; 5129 } 5130 5131 // We didn't find a named data member. 5132 return nullptr; 5133 } 5134 5135 unsigned RecordDecl::getODRHash() { 5136 if (hasODRHash()) 5137 return RecordDeclBits.ODRHash; 5138 5139 // Only calculate hash on first call of getODRHash per record. 5140 ODRHash Hash; 5141 Hash.AddRecordDecl(this); 5142 // For RecordDecl the ODRHash is stored in the remaining 26 5143 // bit of RecordDeclBits, adjust the hash to accomodate. 5144 setODRHash(Hash.CalculateHash() >> 6); 5145 return RecordDeclBits.ODRHash; 5146 } 5147 5148 //===----------------------------------------------------------------------===// 5149 // BlockDecl Implementation 5150 //===----------------------------------------------------------------------===// 5151 5152 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 5153 : Decl(Block, DC, CaretLoc), DeclContext(Block) { 5154 setIsVariadic(false); 5155 setCapturesCXXThis(false); 5156 setBlockMissingReturnType(true); 5157 setIsConversionFromLambda(false); 5158 setDoesNotEscape(false); 5159 setCanAvoidCopyToHeap(false); 5160 } 5161 5162 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 5163 assert(!ParamInfo && "Already has param info!"); 5164 5165 // Zero params -> null pointer. 5166 if (!NewParamInfo.empty()) { 5167 NumParams = NewParamInfo.size(); 5168 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 5169 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 5170 } 5171 } 5172 5173 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 5174 bool CapturesCXXThis) { 5175 this->setCapturesCXXThis(CapturesCXXThis); 5176 this->NumCaptures = Captures.size(); 5177 5178 if (Captures.empty()) { 5179 this->Captures = nullptr; 5180 return; 5181 } 5182 5183 this->Captures = Captures.copy(Context).data(); 5184 } 5185 5186 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 5187 for (const auto &I : captures()) 5188 // Only auto vars can be captured, so no redeclaration worries. 5189 if (I.getVariable() == variable) 5190 return true; 5191 5192 return false; 5193 } 5194 5195 SourceRange BlockDecl::getSourceRange() const { 5196 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation()); 5197 } 5198 5199 //===----------------------------------------------------------------------===// 5200 // Other Decl Allocation/Deallocation Method Implementations 5201 //===----------------------------------------------------------------------===// 5202 5203 void TranslationUnitDecl::anchor() {} 5204 5205 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 5206 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 5207 } 5208 5209 void PragmaCommentDecl::anchor() {} 5210 5211 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 5212 TranslationUnitDecl *DC, 5213 SourceLocation CommentLoc, 5214 PragmaMSCommentKind CommentKind, 5215 StringRef Arg) { 5216 PragmaCommentDecl *PCD = 5217 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 5218 PragmaCommentDecl(DC, CommentLoc, CommentKind); 5219 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 5220 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 5221 return PCD; 5222 } 5223 5224 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 5225 unsigned ID, 5226 unsigned ArgSize) { 5227 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 5228 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 5229 } 5230 5231 void PragmaDetectMismatchDecl::anchor() {} 5232 5233 PragmaDetectMismatchDecl * 5234 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 5235 SourceLocation Loc, StringRef Name, 5236 StringRef Value) { 5237 size_t ValueStart = Name.size() + 1; 5238 PragmaDetectMismatchDecl *PDMD = 5239 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 5240 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 5241 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 5242 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 5243 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 5244 Value.size()); 5245 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 5246 return PDMD; 5247 } 5248 5249 PragmaDetectMismatchDecl * 5250 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5251 unsigned NameValueSize) { 5252 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 5253 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 5254 } 5255 5256 void ExternCContextDecl::anchor() {} 5257 5258 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 5259 TranslationUnitDecl *DC) { 5260 return new (C, DC) ExternCContextDecl(DC); 5261 } 5262 5263 void LabelDecl::anchor() {} 5264 5265 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 5266 SourceLocation IdentL, IdentifierInfo *II) { 5267 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 5268 } 5269 5270 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 5271 SourceLocation IdentL, IdentifierInfo *II, 5272 SourceLocation GnuLabelL) { 5273 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 5274 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 5275 } 5276 5277 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5278 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 5279 SourceLocation()); 5280 } 5281 5282 void LabelDecl::setMSAsmLabel(StringRef Name) { 5283 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 5284 memcpy(Buffer, Name.data(), Name.size()); 5285 Buffer[Name.size()] = '\0'; 5286 MSAsmName = Buffer; 5287 } 5288 5289 void ValueDecl::anchor() {} 5290 5291 bool ValueDecl::isWeak() const { 5292 auto *MostRecent = getMostRecentDecl(); 5293 return MostRecent->hasAttr<WeakAttr>() || 5294 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported(); 5295 } 5296 5297 bool ValueDecl::isInitCapture() const { 5298 if (auto *Var = llvm::dyn_cast<VarDecl>(this)) 5299 return Var->isInitCapture(); 5300 return false; 5301 } 5302 5303 void ImplicitParamDecl::anchor() {} 5304 5305 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 5306 SourceLocation IdLoc, 5307 IdentifierInfo *Id, QualType Type, 5308 ImplicitParamKind ParamKind) { 5309 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 5310 } 5311 5312 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 5313 ImplicitParamKind ParamKind) { 5314 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 5315 } 5316 5317 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 5318 unsigned ID) { 5319 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 5320 } 5321 5322 FunctionDecl * 5323 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 5324 const DeclarationNameInfo &NameInfo, QualType T, 5325 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 5326 bool isInlineSpecified, bool hasWrittenPrototype, 5327 ConstexprSpecKind ConstexprKind, 5328 Expr *TrailingRequiresClause) { 5329 FunctionDecl *New = new (C, DC) FunctionDecl( 5330 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 5331 isInlineSpecified, ConstexprKind, TrailingRequiresClause); 5332 New->setHasWrittenPrototype(hasWrittenPrototype); 5333 return New; 5334 } 5335 5336 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5337 return new (C, ID) FunctionDecl( 5338 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), 5339 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr); 5340 } 5341 5342 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5343 return new (C, DC) BlockDecl(DC, L); 5344 } 5345 5346 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5347 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 5348 } 5349 5350 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 5351 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 5352 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 5353 5354 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 5355 unsigned NumParams) { 5356 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5357 CapturedDecl(DC, NumParams); 5358 } 5359 5360 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5361 unsigned NumParams) { 5362 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5363 CapturedDecl(nullptr, NumParams); 5364 } 5365 5366 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 5367 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 5368 5369 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 5370 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 5371 5372 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 5373 SourceLocation L, 5374 IdentifierInfo *Id, QualType T, 5375 Expr *E, const llvm::APSInt &V) { 5376 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 5377 } 5378 5379 EnumConstantDecl * 5380 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5381 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 5382 QualType(), nullptr, llvm::APSInt()); 5383 } 5384 5385 void IndirectFieldDecl::anchor() {} 5386 5387 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 5388 SourceLocation L, DeclarationName N, 5389 QualType T, 5390 MutableArrayRef<NamedDecl *> CH) 5391 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 5392 ChainingSize(CH.size()) { 5393 // In C++, indirect field declarations conflict with tag declarations in the 5394 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 5395 if (C.getLangOpts().CPlusPlus) 5396 IdentifierNamespace |= IDNS_Tag; 5397 } 5398 5399 IndirectFieldDecl * 5400 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 5401 IdentifierInfo *Id, QualType T, 5402 llvm::MutableArrayRef<NamedDecl *> CH) { 5403 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 5404 } 5405 5406 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 5407 unsigned ID) { 5408 return new (C, ID) 5409 IndirectFieldDecl(C, nullptr, SourceLocation(), DeclarationName(), 5410 QualType(), std::nullopt); 5411 } 5412 5413 SourceRange EnumConstantDecl::getSourceRange() const { 5414 SourceLocation End = getLocation(); 5415 if (Init) 5416 End = Init->getEndLoc(); 5417 return SourceRange(getLocation(), End); 5418 } 5419 5420 void TypeDecl::anchor() {} 5421 5422 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 5423 SourceLocation StartLoc, SourceLocation IdLoc, 5424 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 5425 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5426 } 5427 5428 void TypedefNameDecl::anchor() {} 5429 5430 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 5431 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 5432 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 5433 auto *ThisTypedef = this; 5434 if (AnyRedecl && OwningTypedef) { 5435 OwningTypedef = OwningTypedef->getCanonicalDecl(); 5436 ThisTypedef = ThisTypedef->getCanonicalDecl(); 5437 } 5438 if (OwningTypedef == ThisTypedef) 5439 return TT->getDecl(); 5440 } 5441 5442 return nullptr; 5443 } 5444 5445 bool TypedefNameDecl::isTransparentTagSlow() const { 5446 auto determineIsTransparent = [&]() { 5447 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 5448 if (auto *TD = TT->getDecl()) { 5449 if (TD->getName() != getName()) 5450 return false; 5451 SourceLocation TTLoc = getLocation(); 5452 SourceLocation TDLoc = TD->getLocation(); 5453 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 5454 return false; 5455 SourceManager &SM = getASTContext().getSourceManager(); 5456 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 5457 } 5458 } 5459 return false; 5460 }; 5461 5462 bool isTransparent = determineIsTransparent(); 5463 MaybeModedTInfo.setInt((isTransparent << 1) | 1); 5464 return isTransparent; 5465 } 5466 5467 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5468 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 5469 nullptr, nullptr); 5470 } 5471 5472 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 5473 SourceLocation StartLoc, 5474 SourceLocation IdLoc, IdentifierInfo *Id, 5475 TypeSourceInfo *TInfo) { 5476 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5477 } 5478 5479 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5480 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 5481 SourceLocation(), nullptr, nullptr); 5482 } 5483 5484 SourceRange TypedefDecl::getSourceRange() const { 5485 SourceLocation RangeEnd = getLocation(); 5486 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 5487 if (typeIsPostfix(TInfo->getType())) 5488 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5489 } 5490 return SourceRange(getBeginLoc(), RangeEnd); 5491 } 5492 5493 SourceRange TypeAliasDecl::getSourceRange() const { 5494 SourceLocation RangeEnd = getBeginLoc(); 5495 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 5496 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5497 return SourceRange(getBeginLoc(), RangeEnd); 5498 } 5499 5500 void FileScopeAsmDecl::anchor() {} 5501 5502 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 5503 StringLiteral *Str, 5504 SourceLocation AsmLoc, 5505 SourceLocation RParenLoc) { 5506 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 5507 } 5508 5509 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 5510 unsigned ID) { 5511 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 5512 SourceLocation()); 5513 } 5514 5515 void TopLevelStmtDecl::anchor() {} 5516 5517 TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) { 5518 assert(Statement); 5519 assert(C.getLangOpts().IncrementalExtensions && 5520 "Must be used only in incremental mode"); 5521 5522 SourceLocation BeginLoc = Statement->getBeginLoc(); 5523 DeclContext *DC = C.getTranslationUnitDecl(); 5524 5525 return new (C, DC) TopLevelStmtDecl(DC, BeginLoc, Statement); 5526 } 5527 5528 TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C, 5529 unsigned ID) { 5530 return new (C, ID) 5531 TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr); 5532 } 5533 5534 SourceRange TopLevelStmtDecl::getSourceRange() const { 5535 return SourceRange(getLocation(), Statement->getEndLoc()); 5536 } 5537 5538 void EmptyDecl::anchor() {} 5539 5540 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5541 return new (C, DC) EmptyDecl(DC, L); 5542 } 5543 5544 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5545 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 5546 } 5547 5548 HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer, 5549 SourceLocation KwLoc, IdentifierInfo *ID, 5550 SourceLocation IDLoc, SourceLocation LBrace) 5551 : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)), 5552 DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc), 5553 IsCBuffer(CBuffer) {} 5554 5555 HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C, 5556 DeclContext *LexicalParent, bool CBuffer, 5557 SourceLocation KwLoc, IdentifierInfo *ID, 5558 SourceLocation IDLoc, 5559 SourceLocation LBrace) { 5560 // For hlsl like this 5561 // cbuffer A { 5562 // cbuffer B { 5563 // } 5564 // } 5565 // compiler should treat it as 5566 // cbuffer A { 5567 // } 5568 // cbuffer B { 5569 // } 5570 // FIXME: support nested buffers if required for back-compat. 5571 DeclContext *DC = LexicalParent; 5572 HLSLBufferDecl *Result = 5573 new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace); 5574 return Result; 5575 } 5576 5577 HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5578 return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr, 5579 SourceLocation(), SourceLocation()); 5580 } 5581 5582 //===----------------------------------------------------------------------===// 5583 // ImportDecl Implementation 5584 //===----------------------------------------------------------------------===// 5585 5586 /// Retrieve the number of module identifiers needed to name the given 5587 /// module. 5588 static unsigned getNumModuleIdentifiers(Module *Mod) { 5589 unsigned Result = 1; 5590 while (Mod->Parent) { 5591 Mod = Mod->Parent; 5592 ++Result; 5593 } 5594 return Result; 5595 } 5596 5597 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5598 Module *Imported, 5599 ArrayRef<SourceLocation> IdentifierLocs) 5600 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5601 NextLocalImportAndComplete(nullptr, true) { 5602 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 5603 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5604 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 5605 StoredLocs); 5606 } 5607 5608 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5609 Module *Imported, SourceLocation EndLoc) 5610 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5611 NextLocalImportAndComplete(nullptr, false) { 5612 *getTrailingObjects<SourceLocation>() = EndLoc; 5613 } 5614 5615 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 5616 SourceLocation StartLoc, Module *Imported, 5617 ArrayRef<SourceLocation> IdentifierLocs) { 5618 return new (C, DC, 5619 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 5620 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 5621 } 5622 5623 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 5624 SourceLocation StartLoc, 5625 Module *Imported, 5626 SourceLocation EndLoc) { 5627 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 5628 ImportDecl(DC, StartLoc, Imported, EndLoc); 5629 Import->setImplicit(); 5630 return Import; 5631 } 5632 5633 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5634 unsigned NumLocations) { 5635 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 5636 ImportDecl(EmptyShell()); 5637 } 5638 5639 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 5640 if (!isImportComplete()) 5641 return std::nullopt; 5642 5643 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5644 return llvm::ArrayRef(StoredLocs, 5645 getNumModuleIdentifiers(getImportedModule())); 5646 } 5647 5648 SourceRange ImportDecl::getSourceRange() const { 5649 if (!isImportComplete()) 5650 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 5651 5652 return SourceRange(getLocation(), getIdentifierLocs().back()); 5653 } 5654 5655 //===----------------------------------------------------------------------===// 5656 // ExportDecl Implementation 5657 //===----------------------------------------------------------------------===// 5658 5659 void ExportDecl::anchor() {} 5660 5661 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 5662 SourceLocation ExportLoc) { 5663 return new (C, DC) ExportDecl(DC, ExportLoc); 5664 } 5665 5666 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5667 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 5668 } 5669