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