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