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::GlobalModuleFragment: { 1565 // External linkage declarations in the global module have no owning module 1566 // for linkage purposes. But internal linkage declarations in the global 1567 // module fragment of a particular module are owned by that module for 1568 // linkage purposes. 1569 // FIXME: p1815 removes the need for this distinction -- there are no 1570 // internal linkage declarations that need to be referred to from outside 1571 // this TU. 1572 if (IgnoreLinkage) 1573 return nullptr; 1574 bool InternalLinkage; 1575 if (auto *ND = dyn_cast<NamedDecl>(this)) 1576 InternalLinkage = !ND->hasExternalFormalLinkage(); 1577 else 1578 InternalLinkage = isInAnonymousNamespace(); 1579 return InternalLinkage ? M->Parent : nullptr; 1580 } 1581 1582 case Module::PrivateModuleFragment: 1583 // The private module fragment is part of its containing module for linkage 1584 // purposes. 1585 return M->Parent; 1586 } 1587 1588 llvm_unreachable("unknown module kind"); 1589 } 1590 1591 void NamedDecl::printName(raw_ostream &os) const { 1592 os << Name; 1593 } 1594 1595 std::string NamedDecl::getQualifiedNameAsString() const { 1596 std::string QualName; 1597 llvm::raw_string_ostream OS(QualName); 1598 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1599 return QualName; 1600 } 1601 1602 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1603 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1604 } 1605 1606 void NamedDecl::printQualifiedName(raw_ostream &OS, 1607 const PrintingPolicy &P) const { 1608 if (getDeclContext()->isFunctionOrMethod()) { 1609 // We do not print '(anonymous)' for function parameters without name. 1610 printName(OS); 1611 return; 1612 } 1613 printNestedNameSpecifier(OS, P); 1614 if (getDeclName()) 1615 OS << *this; 1616 else { 1617 // Give the printName override a chance to pick a different name before we 1618 // fall back to "(anonymous)". 1619 SmallString<64> NameBuffer; 1620 llvm::raw_svector_ostream NameOS(NameBuffer); 1621 printName(NameOS); 1622 if (NameBuffer.empty()) 1623 OS << "(anonymous)"; 1624 else 1625 OS << NameBuffer; 1626 } 1627 } 1628 1629 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const { 1630 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy()); 1631 } 1632 1633 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS, 1634 const PrintingPolicy &P) const { 1635 const DeclContext *Ctx = getDeclContext(); 1636 1637 // For ObjC methods and properties, look through categories and use the 1638 // interface as context. 1639 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) { 1640 if (auto *ID = MD->getClassInterface()) 1641 Ctx = ID; 1642 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) { 1643 if (auto *MD = PD->getGetterMethodDecl()) 1644 if (auto *ID = MD->getClassInterface()) 1645 Ctx = ID; 1646 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) { 1647 if (auto *CI = ID->getContainingInterface()) 1648 Ctx = CI; 1649 } 1650 1651 if (Ctx->isFunctionOrMethod()) 1652 return; 1653 1654 using ContextsTy = SmallVector<const DeclContext *, 8>; 1655 ContextsTy Contexts; 1656 1657 // Collect named contexts. 1658 DeclarationName NameInScope = getDeclName(); 1659 for (; Ctx; Ctx = Ctx->getParent()) { 1660 // Suppress anonymous namespace if requested. 1661 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) && 1662 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace()) 1663 continue; 1664 1665 // Suppress inline namespace if it doesn't make the result ambiguous. 1666 if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope && 1667 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope)) 1668 continue; 1669 1670 // Skip non-named contexts such as linkage specifications and ExportDecls. 1671 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx); 1672 if (!ND) 1673 continue; 1674 1675 Contexts.push_back(Ctx); 1676 NameInScope = ND->getDeclName(); 1677 } 1678 1679 for (const DeclContext *DC : llvm::reverse(Contexts)) { 1680 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1681 OS << Spec->getName(); 1682 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1683 printTemplateArgumentList( 1684 OS, TemplateArgs.asArray(), P, 1685 Spec->getSpecializedTemplate()->getTemplateParameters()); 1686 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 1687 if (ND->isAnonymousNamespace()) { 1688 OS << (P.MSVCFormatting ? "`anonymous namespace\'" 1689 : "(anonymous namespace)"); 1690 } 1691 else 1692 OS << *ND; 1693 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { 1694 if (!RD->getIdentifier()) 1695 OS << "(anonymous " << RD->getKindName() << ')'; 1696 else 1697 OS << *RD; 1698 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1699 const FunctionProtoType *FT = nullptr; 1700 if (FD->hasWrittenPrototype()) 1701 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1702 1703 OS << *FD << '('; 1704 if (FT) { 1705 unsigned NumParams = FD->getNumParams(); 1706 for (unsigned i = 0; i < NumParams; ++i) { 1707 if (i) 1708 OS << ", "; 1709 OS << FD->getParamDecl(i)->getType().stream(P); 1710 } 1711 1712 if (FT->isVariadic()) { 1713 if (NumParams > 0) 1714 OS << ", "; 1715 OS << "..."; 1716 } 1717 } 1718 OS << ')'; 1719 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) { 1720 // C++ [dcl.enum]p10: Each enum-name and each unscoped 1721 // enumerator is declared in the scope that immediately contains 1722 // the enum-specifier. Each scoped enumerator is declared in the 1723 // scope of the enumeration. 1724 // For the case of unscoped enumerator, do not include in the qualified 1725 // name any information about its enum enclosing scope, as its visibility 1726 // is global. 1727 if (ED->isScoped()) 1728 OS << *ED; 1729 else 1730 continue; 1731 } else { 1732 OS << *cast<NamedDecl>(DC); 1733 } 1734 OS << "::"; 1735 } 1736 } 1737 1738 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1739 const PrintingPolicy &Policy, 1740 bool Qualified) const { 1741 if (Qualified) 1742 printQualifiedName(OS, Policy); 1743 else 1744 printName(OS); 1745 } 1746 1747 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1748 return true; 1749 } 1750 static bool isRedeclarableImpl(...) { return false; } 1751 static bool isRedeclarable(Decl::Kind K) { 1752 switch (K) { 1753 #define DECL(Type, Base) \ 1754 case Decl::Type: \ 1755 return isRedeclarableImpl((Type##Decl *)nullptr); 1756 #define ABSTRACT_DECL(DECL) 1757 #include "clang/AST/DeclNodes.inc" 1758 } 1759 llvm_unreachable("unknown decl kind"); 1760 } 1761 1762 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const { 1763 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1764 1765 // Never replace one imported declaration with another; we need both results 1766 // when re-exporting. 1767 if (OldD->isFromASTFile() && isFromASTFile()) 1768 return false; 1769 1770 // A kind mismatch implies that the declaration is not replaced. 1771 if (OldD->getKind() != getKind()) 1772 return false; 1773 1774 // For method declarations, we never replace. (Why?) 1775 if (isa<ObjCMethodDecl>(this)) 1776 return false; 1777 1778 // For parameters, pick the newer one. This is either an error or (in 1779 // Objective-C) permitted as an extension. 1780 if (isa<ParmVarDecl>(this)) 1781 return true; 1782 1783 // Inline namespaces can give us two declarations with the same 1784 // name and kind in the same scope but different contexts; we should 1785 // keep both declarations in this case. 1786 if (!this->getDeclContext()->getRedeclContext()->Equals( 1787 OldD->getDeclContext()->getRedeclContext())) 1788 return false; 1789 1790 // Using declarations can be replaced if they import the same name from the 1791 // same context. 1792 if (auto *UD = dyn_cast<UsingDecl>(this)) { 1793 ASTContext &Context = getASTContext(); 1794 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1795 Context.getCanonicalNestedNameSpecifier( 1796 cast<UsingDecl>(OldD)->getQualifier()); 1797 } 1798 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1799 ASTContext &Context = getASTContext(); 1800 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1801 Context.getCanonicalNestedNameSpecifier( 1802 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1803 } 1804 1805 if (isRedeclarable(getKind())) { 1806 if (getCanonicalDecl() != OldD->getCanonicalDecl()) 1807 return false; 1808 1809 if (IsKnownNewer) 1810 return true; 1811 1812 // Check whether this is actually newer than OldD. We want to keep the 1813 // newer declaration. This loop will usually only iterate once, because 1814 // OldD is usually the previous declaration. 1815 for (auto D : redecls()) { 1816 if (D == OldD) 1817 break; 1818 1819 // If we reach the canonical declaration, then OldD is not actually older 1820 // than this one. 1821 // 1822 // FIXME: In this case, we should not add this decl to the lookup table. 1823 if (D->isCanonicalDecl()) 1824 return false; 1825 } 1826 1827 // It's a newer declaration of the same kind of declaration in the same 1828 // scope: we want this decl instead of the existing one. 1829 return true; 1830 } 1831 1832 // In all other cases, we need to keep both declarations in case they have 1833 // different visibility. Any attempt to use the name will result in an 1834 // ambiguity if more than one is visible. 1835 return false; 1836 } 1837 1838 bool NamedDecl::hasLinkage() const { 1839 return getFormalLinkage() != NoLinkage; 1840 } 1841 1842 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1843 NamedDecl *ND = this; 1844 while (auto *UD = dyn_cast<UsingShadowDecl>(ND)) 1845 ND = UD->getTargetDecl(); 1846 1847 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1848 return AD->getClassInterface(); 1849 1850 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND)) 1851 return AD->getNamespace(); 1852 1853 return ND; 1854 } 1855 1856 bool NamedDecl::isCXXInstanceMember() const { 1857 if (!isCXXClassMember()) 1858 return false; 1859 1860 const NamedDecl *D = this; 1861 if (isa<UsingShadowDecl>(D)) 1862 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1863 1864 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1865 return true; 1866 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction())) 1867 return MD->isInstance(); 1868 return false; 1869 } 1870 1871 //===----------------------------------------------------------------------===// 1872 // DeclaratorDecl Implementation 1873 //===----------------------------------------------------------------------===// 1874 1875 template <typename DeclT> 1876 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1877 if (decl->getNumTemplateParameterLists() > 0) 1878 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1879 return decl->getInnerLocStart(); 1880 } 1881 1882 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1883 TypeSourceInfo *TSI = getTypeSourceInfo(); 1884 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1885 return SourceLocation(); 1886 } 1887 1888 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const { 1889 TypeSourceInfo *TSI = getTypeSourceInfo(); 1890 if (TSI) return TSI->getTypeLoc().getEndLoc(); 1891 return SourceLocation(); 1892 } 1893 1894 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1895 if (QualifierLoc) { 1896 // Make sure the extended decl info is allocated. 1897 if (!hasExtInfo()) { 1898 // Save (non-extended) type source info pointer. 1899 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1900 // Allocate external info struct. 1901 DeclInfo = new (getASTContext()) ExtInfo; 1902 // Restore savedTInfo into (extended) decl info. 1903 getExtInfo()->TInfo = savedTInfo; 1904 } 1905 // Set qualifier info. 1906 getExtInfo()->QualifierLoc = QualifierLoc; 1907 } else if (hasExtInfo()) { 1908 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1909 getExtInfo()->QualifierLoc = QualifierLoc; 1910 } 1911 } 1912 1913 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) { 1914 assert(TrailingRequiresClause); 1915 // Make sure the extended decl info is allocated. 1916 if (!hasExtInfo()) { 1917 // Save (non-extended) type source info pointer. 1918 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1919 // Allocate external info struct. 1920 DeclInfo = new (getASTContext()) ExtInfo; 1921 // Restore savedTInfo into (extended) decl info. 1922 getExtInfo()->TInfo = savedTInfo; 1923 } 1924 // Set requires clause info. 1925 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause; 1926 } 1927 1928 void DeclaratorDecl::setTemplateParameterListsInfo( 1929 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1930 assert(!TPLists.empty()); 1931 // Make sure the extended decl info is allocated. 1932 if (!hasExtInfo()) { 1933 // Save (non-extended) type source info pointer. 1934 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1935 // Allocate external info struct. 1936 DeclInfo = new (getASTContext()) ExtInfo; 1937 // Restore savedTInfo into (extended) decl info. 1938 getExtInfo()->TInfo = savedTInfo; 1939 } 1940 // Set the template parameter lists info. 1941 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 1942 } 1943 1944 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1945 return getTemplateOrInnerLocStart(this); 1946 } 1947 1948 // Helper function: returns true if QT is or contains a type 1949 // having a postfix component. 1950 static bool typeIsPostfix(QualType QT) { 1951 while (true) { 1952 const Type* T = QT.getTypePtr(); 1953 switch (T->getTypeClass()) { 1954 default: 1955 return false; 1956 case Type::Pointer: 1957 QT = cast<PointerType>(T)->getPointeeType(); 1958 break; 1959 case Type::BlockPointer: 1960 QT = cast<BlockPointerType>(T)->getPointeeType(); 1961 break; 1962 case Type::MemberPointer: 1963 QT = cast<MemberPointerType>(T)->getPointeeType(); 1964 break; 1965 case Type::LValueReference: 1966 case Type::RValueReference: 1967 QT = cast<ReferenceType>(T)->getPointeeType(); 1968 break; 1969 case Type::PackExpansion: 1970 QT = cast<PackExpansionType>(T)->getPattern(); 1971 break; 1972 case Type::Paren: 1973 case Type::ConstantArray: 1974 case Type::DependentSizedArray: 1975 case Type::IncompleteArray: 1976 case Type::VariableArray: 1977 case Type::FunctionProto: 1978 case Type::FunctionNoProto: 1979 return true; 1980 } 1981 } 1982 } 1983 1984 SourceRange DeclaratorDecl::getSourceRange() const { 1985 SourceLocation RangeEnd = getLocation(); 1986 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1987 // If the declaration has no name or the type extends past the name take the 1988 // end location of the type. 1989 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 1990 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1991 } 1992 return SourceRange(getOuterLocStart(), RangeEnd); 1993 } 1994 1995 void QualifierInfo::setTemplateParameterListsInfo( 1996 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1997 // Free previous template parameters (if any). 1998 if (NumTemplParamLists > 0) { 1999 Context.Deallocate(TemplParamLists); 2000 TemplParamLists = nullptr; 2001 NumTemplParamLists = 0; 2002 } 2003 // Set info on matched template parameter lists (if any). 2004 if (!TPLists.empty()) { 2005 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 2006 NumTemplParamLists = TPLists.size(); 2007 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 2008 } 2009 } 2010 2011 //===----------------------------------------------------------------------===// 2012 // VarDecl Implementation 2013 //===----------------------------------------------------------------------===// 2014 2015 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 2016 switch (SC) { 2017 case SC_None: break; 2018 case SC_Auto: return "auto"; 2019 case SC_Extern: return "extern"; 2020 case SC_PrivateExtern: return "__private_extern__"; 2021 case SC_Register: return "register"; 2022 case SC_Static: return "static"; 2023 } 2024 2025 llvm_unreachable("Invalid storage class"); 2026 } 2027 2028 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 2029 SourceLocation StartLoc, SourceLocation IdLoc, 2030 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 2031 StorageClass SC) 2032 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 2033 redeclarable_base(C) { 2034 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 2035 "VarDeclBitfields too large!"); 2036 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 2037 "ParmVarDeclBitfields too large!"); 2038 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 2039 "NonParmVarDeclBitfields too large!"); 2040 AllBits = 0; 2041 VarDeclBits.SClass = SC; 2042 // Everything else is implicitly initialized to false. 2043 } 2044 2045 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL, 2046 SourceLocation IdL, const IdentifierInfo *Id, 2047 QualType T, TypeSourceInfo *TInfo, StorageClass S) { 2048 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 2049 } 2050 2051 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2052 return new (C, ID) 2053 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 2054 QualType(), nullptr, SC_None); 2055 } 2056 2057 void VarDecl::setStorageClass(StorageClass SC) { 2058 assert(isLegalForVariable(SC)); 2059 VarDeclBits.SClass = SC; 2060 } 2061 2062 VarDecl::TLSKind VarDecl::getTLSKind() const { 2063 switch (VarDeclBits.TSCSpec) { 2064 case TSCS_unspecified: 2065 if (!hasAttr<ThreadAttr>() && 2066 !(getASTContext().getLangOpts().OpenMPUseTLS && 2067 getASTContext().getTargetInfo().isTLSSupported() && 2068 hasAttr<OMPThreadPrivateDeclAttr>())) 2069 return TLS_None; 2070 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 2071 LangOptions::MSVC2015)) || 2072 hasAttr<OMPThreadPrivateDeclAttr>()) 2073 ? TLS_Dynamic 2074 : TLS_Static; 2075 case TSCS___thread: // Fall through. 2076 case TSCS__Thread_local: 2077 return TLS_Static; 2078 case TSCS_thread_local: 2079 return TLS_Dynamic; 2080 } 2081 llvm_unreachable("Unknown thread storage class specifier!"); 2082 } 2083 2084 SourceRange VarDecl::getSourceRange() const { 2085 if (const Expr *Init = getInit()) { 2086 SourceLocation InitEnd = Init->getEndLoc(); 2087 // If Init is implicit, ignore its source range and fallback on 2088 // DeclaratorDecl::getSourceRange() to handle postfix elements. 2089 if (InitEnd.isValid() && InitEnd != getLocation()) 2090 return SourceRange(getOuterLocStart(), InitEnd); 2091 } 2092 return DeclaratorDecl::getSourceRange(); 2093 } 2094 2095 template<typename T> 2096 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 2097 // C++ [dcl.link]p1: All function types, function names with external linkage, 2098 // and variable names with external linkage have a language linkage. 2099 if (!D.hasExternalFormalLinkage()) 2100 return NoLanguageLinkage; 2101 2102 // Language linkage is a C++ concept, but saying that everything else in C has 2103 // C language linkage fits the implementation nicely. 2104 ASTContext &Context = D.getASTContext(); 2105 if (!Context.getLangOpts().CPlusPlus) 2106 return CLanguageLinkage; 2107 2108 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 2109 // language linkage of the names of class members and the function type of 2110 // class member functions. 2111 const DeclContext *DC = D.getDeclContext(); 2112 if (DC->isRecord()) 2113 return CXXLanguageLinkage; 2114 2115 // If the first decl is in an extern "C" context, any other redeclaration 2116 // will have C language linkage. If the first one is not in an extern "C" 2117 // context, we would have reported an error for any other decl being in one. 2118 if (isFirstInExternCContext(&D)) 2119 return CLanguageLinkage; 2120 return CXXLanguageLinkage; 2121 } 2122 2123 template<typename T> 2124 static bool isDeclExternC(const T &D) { 2125 // Since the context is ignored for class members, they can only have C++ 2126 // language linkage or no language linkage. 2127 const DeclContext *DC = D.getDeclContext(); 2128 if (DC->isRecord()) { 2129 assert(D.getASTContext().getLangOpts().CPlusPlus); 2130 return false; 2131 } 2132 2133 return D.getLanguageLinkage() == CLanguageLinkage; 2134 } 2135 2136 LanguageLinkage VarDecl::getLanguageLinkage() const { 2137 return getDeclLanguageLinkage(*this); 2138 } 2139 2140 bool VarDecl::isExternC() const { 2141 return isDeclExternC(*this); 2142 } 2143 2144 bool VarDecl::isInExternCContext() const { 2145 return getLexicalDeclContext()->isExternCContext(); 2146 } 2147 2148 bool VarDecl::isInExternCXXContext() const { 2149 return getLexicalDeclContext()->isExternCXXContext(); 2150 } 2151 2152 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 2153 2154 VarDecl::DefinitionKind 2155 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 2156 if (isThisDeclarationADemotedDefinition()) 2157 return DeclarationOnly; 2158 2159 // C++ [basic.def]p2: 2160 // A declaration is a definition unless [...] it contains the 'extern' 2161 // specifier or a linkage-specification and neither an initializer [...], 2162 // it declares a non-inline static data member in a class declaration [...], 2163 // it declares a static data member outside a class definition and the variable 2164 // was defined within the class with the constexpr specifier [...], 2165 // C++1y [temp.expl.spec]p15: 2166 // An explicit specialization of a static data member or an explicit 2167 // specialization of a static data member template is a definition if the 2168 // declaration includes an initializer; otherwise, it is a declaration. 2169 // 2170 // FIXME: How do you declare (but not define) a partial specialization of 2171 // a static data member template outside the containing class? 2172 if (isStaticDataMember()) { 2173 if (isOutOfLine() && 2174 !(getCanonicalDecl()->isInline() && 2175 getCanonicalDecl()->isConstexpr()) && 2176 (hasInit() || 2177 // If the first declaration is out-of-line, this may be an 2178 // instantiation of an out-of-line partial specialization of a variable 2179 // template for which we have not yet instantiated the initializer. 2180 (getFirstDecl()->isOutOfLine() 2181 ? getTemplateSpecializationKind() == TSK_Undeclared 2182 : getTemplateSpecializationKind() != 2183 TSK_ExplicitSpecialization) || 2184 isa<VarTemplatePartialSpecializationDecl>(this))) 2185 return Definition; 2186 if (!isOutOfLine() && isInline()) 2187 return Definition; 2188 return DeclarationOnly; 2189 } 2190 // C99 6.7p5: 2191 // A definition of an identifier is a declaration for that identifier that 2192 // [...] causes storage to be reserved for that object. 2193 // Note: that applies for all non-file-scope objects. 2194 // C99 6.9.2p1: 2195 // If the declaration of an identifier for an object has file scope and an 2196 // initializer, the declaration is an external definition for the identifier 2197 if (hasInit()) 2198 return Definition; 2199 2200 if (hasDefiningAttr()) 2201 return Definition; 2202 2203 if (const auto *SAA = getAttr<SelectAnyAttr>()) 2204 if (!SAA->isInherited()) 2205 return Definition; 2206 2207 // A variable template specialization (other than a static data member 2208 // template or an explicit specialization) is a declaration until we 2209 // instantiate its initializer. 2210 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) { 2211 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2212 !isa<VarTemplatePartialSpecializationDecl>(VTSD) && 2213 !VTSD->IsCompleteDefinition) 2214 return DeclarationOnly; 2215 } 2216 2217 if (hasExternalStorage()) 2218 return DeclarationOnly; 2219 2220 // [dcl.link] p7: 2221 // A declaration directly contained in a linkage-specification is treated 2222 // as if it contains the extern specifier for the purpose of determining 2223 // the linkage of the declared name and whether it is a definition. 2224 if (isSingleLineLanguageLinkage(*this)) 2225 return DeclarationOnly; 2226 2227 // C99 6.9.2p2: 2228 // A declaration of an object that has file scope without an initializer, 2229 // and without a storage class specifier or the scs 'static', constitutes 2230 // a tentative definition. 2231 // No such thing in C++. 2232 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 2233 return TentativeDefinition; 2234 2235 // What's left is (in C, block-scope) declarations without initializers or 2236 // external storage. These are definitions. 2237 return Definition; 2238 } 2239 2240 VarDecl *VarDecl::getActingDefinition() { 2241 DefinitionKind Kind = isThisDeclarationADefinition(); 2242 if (Kind != TentativeDefinition) 2243 return nullptr; 2244 2245 VarDecl *LastTentative = nullptr; 2246 2247 // Loop through the declaration chain, starting with the most recent. 2248 for (VarDecl *Decl = getMostRecentDecl(); Decl; 2249 Decl = Decl->getPreviousDecl()) { 2250 Kind = Decl->isThisDeclarationADefinition(); 2251 if (Kind == Definition) 2252 return nullptr; 2253 // Record the first (most recent) TentativeDefinition that is encountered. 2254 if (Kind == TentativeDefinition && !LastTentative) 2255 LastTentative = Decl; 2256 } 2257 2258 return LastTentative; 2259 } 2260 2261 VarDecl *VarDecl::getDefinition(ASTContext &C) { 2262 VarDecl *First = getFirstDecl(); 2263 for (auto I : First->redecls()) { 2264 if (I->isThisDeclarationADefinition(C) == Definition) 2265 return I; 2266 } 2267 return nullptr; 2268 } 2269 2270 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 2271 DefinitionKind Kind = DeclarationOnly; 2272 2273 const VarDecl *First = getFirstDecl(); 2274 for (auto I : First->redecls()) { 2275 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 2276 if (Kind == Definition) 2277 break; 2278 } 2279 2280 return Kind; 2281 } 2282 2283 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2284 for (auto I : redecls()) { 2285 if (auto Expr = I->getInit()) { 2286 D = I; 2287 return Expr; 2288 } 2289 } 2290 return nullptr; 2291 } 2292 2293 bool VarDecl::hasInit() const { 2294 if (auto *P = dyn_cast<ParmVarDecl>(this)) 2295 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg()) 2296 return false; 2297 2298 return !Init.isNull(); 2299 } 2300 2301 Expr *VarDecl::getInit() { 2302 if (!hasInit()) 2303 return nullptr; 2304 2305 if (auto *S = Init.dyn_cast<Stmt *>()) 2306 return cast<Expr>(S); 2307 2308 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value); 2309 } 2310 2311 Stmt **VarDecl::getInitAddress() { 2312 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>()) 2313 return &ES->Value; 2314 2315 return Init.getAddrOfPtr1(); 2316 } 2317 2318 VarDecl *VarDecl::getInitializingDeclaration() { 2319 VarDecl *Def = nullptr; 2320 for (auto I : redecls()) { 2321 if (I->hasInit()) 2322 return I; 2323 2324 if (I->isThisDeclarationADefinition()) { 2325 if (isStaticDataMember()) 2326 return I; 2327 Def = I; 2328 } 2329 } 2330 return Def; 2331 } 2332 2333 bool VarDecl::isOutOfLine() const { 2334 if (Decl::isOutOfLine()) 2335 return true; 2336 2337 if (!isStaticDataMember()) 2338 return false; 2339 2340 // If this static data member was instantiated from a static data member of 2341 // a class template, check whether that static data member was defined 2342 // out-of-line. 2343 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2344 return VD->isOutOfLine(); 2345 2346 return false; 2347 } 2348 2349 void VarDecl::setInit(Expr *I) { 2350 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2351 Eval->~EvaluatedStmt(); 2352 getASTContext().Deallocate(Eval); 2353 } 2354 2355 Init = I; 2356 } 2357 2358 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const { 2359 const LangOptions &Lang = C.getLangOpts(); 2360 2361 // OpenCL permits const integral variables to be used in constant 2362 // expressions, like in C++98. 2363 if (!Lang.CPlusPlus && !Lang.OpenCL) 2364 return false; 2365 2366 // Function parameters are never usable in constant expressions. 2367 if (isa<ParmVarDecl>(this)) 2368 return false; 2369 2370 // The values of weak variables are never usable in constant expressions. 2371 if (isWeak()) 2372 return false; 2373 2374 // In C++11, any variable of reference type can be used in a constant 2375 // expression if it is initialized by a constant expression. 2376 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2377 return true; 2378 2379 // Only const objects can be used in constant expressions in C++. C++98 does 2380 // not require the variable to be non-volatile, but we consider this to be a 2381 // defect. 2382 if (!getType().isConstant(C) || getType().isVolatileQualified()) 2383 return false; 2384 2385 // In C++, const, non-volatile variables of integral or enumeration types 2386 // can be used in constant expressions. 2387 if (getType()->isIntegralOrEnumerationType()) 2388 return true; 2389 2390 // Additionally, in C++11, non-volatile constexpr variables can be used in 2391 // constant expressions. 2392 return Lang.CPlusPlus11 && isConstexpr(); 2393 } 2394 2395 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const { 2396 // C++2a [expr.const]p3: 2397 // A variable is usable in constant expressions after its initializing 2398 // declaration is encountered... 2399 const VarDecl *DefVD = nullptr; 2400 const Expr *Init = getAnyInitializer(DefVD); 2401 if (!Init || Init->isValueDependent() || getType()->isDependentType()) 2402 return false; 2403 // ... if it is a constexpr variable, or it is of reference type or of 2404 // const-qualified integral or enumeration type, ... 2405 if (!DefVD->mightBeUsableInConstantExpressions(Context)) 2406 return false; 2407 // ... and its initializer is a constant initializer. 2408 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization()) 2409 return false; 2410 // C++98 [expr.const]p1: 2411 // An integral constant-expression can involve only [...] const variables 2412 // or static data members of integral or enumeration types initialized with 2413 // [integer] constant expressions (dcl.init) 2414 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) && 2415 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context)) 2416 return false; 2417 return true; 2418 } 2419 2420 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2421 /// form, which contains extra information on the evaluated value of the 2422 /// initializer. 2423 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2424 auto *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2425 if (!Eval) { 2426 // Note: EvaluatedStmt contains an APValue, which usually holds 2427 // resources not allocated from the ASTContext. We need to do some 2428 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2429 // where we can detect whether there's anything to clean up or not. 2430 Eval = new (getASTContext()) EvaluatedStmt; 2431 Eval->Value = Init.get<Stmt *>(); 2432 Init = Eval; 2433 } 2434 return Eval; 2435 } 2436 2437 EvaluatedStmt *VarDecl::getEvaluatedStmt() const { 2438 return Init.dyn_cast<EvaluatedStmt *>(); 2439 } 2440 2441 APValue *VarDecl::evaluateValue() const { 2442 SmallVector<PartialDiagnosticAt, 8> Notes; 2443 return evaluateValueImpl(Notes, hasConstantInitialization()); 2444 } 2445 2446 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes, 2447 bool IsConstantInitialization) const { 2448 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2449 2450 const auto *Init = cast<Expr>(Eval->Value); 2451 assert(!Init->isValueDependent()); 2452 2453 // We only produce notes indicating why an initializer is non-constant the 2454 // first time it is evaluated. FIXME: The notes won't always be emitted the 2455 // first time we try evaluation, so might not be produced at all. 2456 if (Eval->WasEvaluated) 2457 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated; 2458 2459 if (Eval->IsEvaluating) { 2460 // FIXME: Produce a diagnostic for self-initialization. 2461 return nullptr; 2462 } 2463 2464 Eval->IsEvaluating = true; 2465 2466 ASTContext &Ctx = getASTContext(); 2467 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes, 2468 IsConstantInitialization); 2469 2470 // In C++11, this isn't a constant initializer if we produced notes. In that 2471 // case, we can't keep the result, because it may only be correct under the 2472 // assumption that the initializer is a constant context. 2473 if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 && 2474 !Notes.empty()) 2475 Result = false; 2476 2477 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2478 // or that it's empty (so that there's nothing to clean up) if evaluation 2479 // failed. 2480 if (!Result) 2481 Eval->Evaluated = APValue(); 2482 else if (Eval->Evaluated.needsCleanup()) 2483 Ctx.addDestruction(&Eval->Evaluated); 2484 2485 Eval->IsEvaluating = false; 2486 Eval->WasEvaluated = true; 2487 2488 return Result ? &Eval->Evaluated : nullptr; 2489 } 2490 2491 APValue *VarDecl::getEvaluatedValue() const { 2492 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2493 if (Eval->WasEvaluated) 2494 return &Eval->Evaluated; 2495 2496 return nullptr; 2497 } 2498 2499 bool VarDecl::hasICEInitializer(const ASTContext &Context) const { 2500 const Expr *Init = getInit(); 2501 assert(Init && "no initializer"); 2502 2503 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2504 if (!Eval->CheckedForICEInit) { 2505 Eval->CheckedForICEInit = true; 2506 Eval->HasICEInit = Init->isIntegerConstantExpr(Context); 2507 } 2508 return Eval->HasICEInit; 2509 } 2510 2511 bool VarDecl::hasConstantInitialization() const { 2512 // In C, all globals (and only globals) have constant initialization. 2513 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus) 2514 return true; 2515 2516 // In C++, it depends on whether the evaluation at the point of definition 2517 // was evaluatable as a constant initializer. 2518 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2519 return Eval->HasConstantInitialization; 2520 2521 return false; 2522 } 2523 2524 bool VarDecl::checkForConstantInitialization( 2525 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2526 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2527 // If we ask for the value before we know whether we have a constant 2528 // initializer, we can compute the wrong value (for example, due to 2529 // std::is_constant_evaluated()). 2530 assert(!Eval->WasEvaluated && 2531 "already evaluated var value before checking for constant init"); 2532 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++"); 2533 2534 assert(!cast<Expr>(Eval->Value)->isValueDependent()); 2535 2536 // Evaluate the initializer to check whether it's a constant expression. 2537 Eval->HasConstantInitialization = 2538 evaluateValueImpl(Notes, true) && Notes.empty(); 2539 2540 // If evaluation as a constant initializer failed, allow re-evaluation as a 2541 // non-constant initializer if we later find we want the value. 2542 if (!Eval->HasConstantInitialization) 2543 Eval->WasEvaluated = false; 2544 2545 return Eval->HasConstantInitialization; 2546 } 2547 2548 bool VarDecl::isParameterPack() const { 2549 return isa<PackExpansionType>(getType()); 2550 } 2551 2552 template<typename DeclT> 2553 static DeclT *getDefinitionOrSelf(DeclT *D) { 2554 assert(D); 2555 if (auto *Def = D->getDefinition()) 2556 return Def; 2557 return D; 2558 } 2559 2560 bool VarDecl::isEscapingByref() const { 2561 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref; 2562 } 2563 2564 bool VarDecl::isNonEscapingByref() const { 2565 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref; 2566 } 2567 2568 bool VarDecl::hasDependentAlignment() const { 2569 QualType T = getType(); 2570 return T->isDependentType() || T->isUndeducedAutoType() || 2571 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) { 2572 return AA->isAlignmentDependent(); 2573 }); 2574 } 2575 2576 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2577 const VarDecl *VD = this; 2578 2579 // If this is an instantiated member, walk back to the template from which 2580 // it was instantiated. 2581 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) { 2582 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2583 VD = VD->getInstantiatedFromStaticDataMember(); 2584 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2585 VD = NewVD; 2586 } 2587 } 2588 2589 // If it's an instantiated variable template specialization, find the 2590 // template or partial specialization from which it was instantiated. 2591 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 2592 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) { 2593 auto From = VDTemplSpec->getInstantiatedFrom(); 2594 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2595 while (!VTD->isMemberSpecialization()) { 2596 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate(); 2597 if (!NewVTD) 2598 break; 2599 VTD = NewVTD; 2600 } 2601 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2602 } 2603 if (auto *VTPSD = 2604 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2605 while (!VTPSD->isMemberSpecialization()) { 2606 auto *NewVTPSD = VTPSD->getInstantiatedFromMember(); 2607 if (!NewVTPSD) 2608 break; 2609 VTPSD = NewVTPSD; 2610 } 2611 return getDefinitionOrSelf<VarDecl>(VTPSD); 2612 } 2613 } 2614 } 2615 2616 // If this is the pattern of a variable template, find where it was 2617 // instantiated from. FIXME: Is this necessary? 2618 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) { 2619 while (!VarTemplate->isMemberSpecialization()) { 2620 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate(); 2621 if (!NewVT) 2622 break; 2623 VarTemplate = NewVT; 2624 } 2625 2626 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl()); 2627 } 2628 2629 if (VD == this) 2630 return nullptr; 2631 return getDefinitionOrSelf(const_cast<VarDecl*>(VD)); 2632 } 2633 2634 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2635 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2636 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2637 2638 return nullptr; 2639 } 2640 2641 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2642 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2643 return Spec->getSpecializationKind(); 2644 2645 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2646 return MSI->getTemplateSpecializationKind(); 2647 2648 return TSK_Undeclared; 2649 } 2650 2651 TemplateSpecializationKind 2652 VarDecl::getTemplateSpecializationKindForInstantiation() const { 2653 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2654 return MSI->getTemplateSpecializationKind(); 2655 2656 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2657 return Spec->getSpecializationKind(); 2658 2659 return TSK_Undeclared; 2660 } 2661 2662 SourceLocation VarDecl::getPointOfInstantiation() const { 2663 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2664 return Spec->getPointOfInstantiation(); 2665 2666 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2667 return MSI->getPointOfInstantiation(); 2668 2669 return SourceLocation(); 2670 } 2671 2672 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2673 return getASTContext().getTemplateOrSpecializationInfo(this) 2674 .dyn_cast<VarTemplateDecl *>(); 2675 } 2676 2677 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2678 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2679 } 2680 2681 bool VarDecl::isKnownToBeDefined() const { 2682 const auto &LangOpts = getASTContext().getLangOpts(); 2683 // In CUDA mode without relocatable device code, variables of form 'extern 2684 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared 2685 // memory pool. These are never undefined variables, even if they appear 2686 // inside of an anon namespace or static function. 2687 // 2688 // With CUDA relocatable device code enabled, these variables don't get 2689 // special handling; they're treated like regular extern variables. 2690 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode && 2691 hasExternalStorage() && hasAttr<CUDASharedAttr>() && 2692 isa<IncompleteArrayType>(getType())) 2693 return true; 2694 2695 return hasDefinition(); 2696 } 2697 2698 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { 2699 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() || 2700 (!Ctx.getLangOpts().RegisterStaticDestructors && 2701 !hasAttr<AlwaysDestroyAttr>())); 2702 } 2703 2704 QualType::DestructionKind 2705 VarDecl::needsDestruction(const ASTContext &Ctx) const { 2706 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2707 if (Eval->HasConstantDestruction) 2708 return QualType::DK_none; 2709 2710 if (isNoDestroy(Ctx)) 2711 return QualType::DK_none; 2712 2713 return getType().isDestructedType(); 2714 } 2715 2716 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2717 if (isStaticDataMember()) 2718 // FIXME: Remove ? 2719 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2720 return getASTContext().getTemplateOrSpecializationInfo(this) 2721 .dyn_cast<MemberSpecializationInfo *>(); 2722 return nullptr; 2723 } 2724 2725 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2726 SourceLocation PointOfInstantiation) { 2727 assert((isa<VarTemplateSpecializationDecl>(this) || 2728 getMemberSpecializationInfo()) && 2729 "not a variable or static data member template specialization"); 2730 2731 if (VarTemplateSpecializationDecl *Spec = 2732 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2733 Spec->setSpecializationKind(TSK); 2734 if (TSK != TSK_ExplicitSpecialization && 2735 PointOfInstantiation.isValid() && 2736 Spec->getPointOfInstantiation().isInvalid()) { 2737 Spec->setPointOfInstantiation(PointOfInstantiation); 2738 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2739 L->InstantiationRequested(this); 2740 } 2741 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2742 MSI->setTemplateSpecializationKind(TSK); 2743 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2744 MSI->getPointOfInstantiation().isInvalid()) { 2745 MSI->setPointOfInstantiation(PointOfInstantiation); 2746 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2747 L->InstantiationRequested(this); 2748 } 2749 } 2750 } 2751 2752 void 2753 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2754 TemplateSpecializationKind TSK) { 2755 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2756 "Previous template or instantiation?"); 2757 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2758 } 2759 2760 //===----------------------------------------------------------------------===// 2761 // ParmVarDecl Implementation 2762 //===----------------------------------------------------------------------===// 2763 2764 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2765 SourceLocation StartLoc, 2766 SourceLocation IdLoc, IdentifierInfo *Id, 2767 QualType T, TypeSourceInfo *TInfo, 2768 StorageClass S, Expr *DefArg) { 2769 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2770 S, DefArg); 2771 } 2772 2773 QualType ParmVarDecl::getOriginalType() const { 2774 TypeSourceInfo *TSI = getTypeSourceInfo(); 2775 QualType T = TSI ? TSI->getType() : getType(); 2776 if (const auto *DT = dyn_cast<DecayedType>(T)) 2777 return DT->getOriginalType(); 2778 return T; 2779 } 2780 2781 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2782 return new (C, ID) 2783 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2784 nullptr, QualType(), nullptr, SC_None, nullptr); 2785 } 2786 2787 SourceRange ParmVarDecl::getSourceRange() const { 2788 if (!hasInheritedDefaultArg()) { 2789 SourceRange ArgRange = getDefaultArgRange(); 2790 if (ArgRange.isValid()) 2791 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2792 } 2793 2794 // DeclaratorDecl considers the range of postfix types as overlapping with the 2795 // declaration name, but this is not the case with parameters in ObjC methods. 2796 if (isa<ObjCMethodDecl>(getDeclContext())) 2797 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation()); 2798 2799 return DeclaratorDecl::getSourceRange(); 2800 } 2801 2802 bool ParmVarDecl::isDestroyedInCallee() const { 2803 // ns_consumed only affects code generation in ARC 2804 if (hasAttr<NSConsumedAttr>()) 2805 return getASTContext().getLangOpts().ObjCAutoRefCount; 2806 2807 // FIXME: isParamDestroyedInCallee() should probably imply 2808 // isDestructedType() 2809 auto *RT = getType()->getAs<RecordType>(); 2810 if (RT && RT->getDecl()->isParamDestroyedInCallee() && 2811 getType().isDestructedType()) 2812 return true; 2813 2814 return false; 2815 } 2816 2817 Expr *ParmVarDecl::getDefaultArg() { 2818 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2819 assert(!hasUninstantiatedDefaultArg() && 2820 "Default argument is not yet instantiated!"); 2821 2822 Expr *Arg = getInit(); 2823 if (auto *E = dyn_cast_or_null<FullExpr>(Arg)) 2824 return E->getSubExpr(); 2825 2826 return Arg; 2827 } 2828 2829 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2830 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2831 Init = defarg; 2832 } 2833 2834 SourceRange ParmVarDecl::getDefaultArgRange() const { 2835 switch (ParmVarDeclBits.DefaultArgKind) { 2836 case DAK_None: 2837 case DAK_Unparsed: 2838 // Nothing we can do here. 2839 return SourceRange(); 2840 2841 case DAK_Uninstantiated: 2842 return getUninstantiatedDefaultArg()->getSourceRange(); 2843 2844 case DAK_Normal: 2845 if (const Expr *E = getInit()) 2846 return E->getSourceRange(); 2847 2848 // Missing an actual expression, may be invalid. 2849 return SourceRange(); 2850 } 2851 llvm_unreachable("Invalid default argument kind."); 2852 } 2853 2854 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 2855 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 2856 Init = arg; 2857 } 2858 2859 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 2860 assert(hasUninstantiatedDefaultArg() && 2861 "Wrong kind of initialization expression!"); 2862 return cast_or_null<Expr>(Init.get<Stmt *>()); 2863 } 2864 2865 bool ParmVarDecl::hasDefaultArg() const { 2866 // FIXME: We should just return false for DAK_None here once callers are 2867 // prepared for the case that we encountered an invalid default argument and 2868 // were unable to even build an invalid expression. 2869 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 2870 !Init.isNull(); 2871 } 2872 2873 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 2874 getASTContext().setParameterIndex(this, parameterIndex); 2875 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 2876 } 2877 2878 unsigned ParmVarDecl::getParameterIndexLarge() const { 2879 return getASTContext().getParameterIndex(this); 2880 } 2881 2882 //===----------------------------------------------------------------------===// 2883 // FunctionDecl Implementation 2884 //===----------------------------------------------------------------------===// 2885 2886 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, 2887 SourceLocation StartLoc, 2888 const DeclarationNameInfo &NameInfo, QualType T, 2889 TypeSourceInfo *TInfo, StorageClass S, 2890 bool UsesFPIntrin, bool isInlineSpecified, 2891 ConstexprSpecKind ConstexprKind, 2892 Expr *TrailingRequiresClause) 2893 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 2894 StartLoc), 2895 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0), 2896 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) { 2897 assert(T.isNull() || T->isFunctionType()); 2898 FunctionDeclBits.SClass = S; 2899 FunctionDeclBits.IsInline = isInlineSpecified; 2900 FunctionDeclBits.IsInlineSpecified = isInlineSpecified; 2901 FunctionDeclBits.IsVirtualAsWritten = false; 2902 FunctionDeclBits.IsPure = false; 2903 FunctionDeclBits.HasInheritedPrototype = false; 2904 FunctionDeclBits.HasWrittenPrototype = true; 2905 FunctionDeclBits.IsDeleted = false; 2906 FunctionDeclBits.IsTrivial = false; 2907 FunctionDeclBits.IsTrivialForCall = false; 2908 FunctionDeclBits.IsDefaulted = false; 2909 FunctionDeclBits.IsExplicitlyDefaulted = false; 2910 FunctionDeclBits.HasDefaultedFunctionInfo = false; 2911 FunctionDeclBits.HasImplicitReturnZero = false; 2912 FunctionDeclBits.IsLateTemplateParsed = false; 2913 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind); 2914 FunctionDeclBits.InstantiationIsPending = false; 2915 FunctionDeclBits.UsesSEHTry = false; 2916 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin; 2917 FunctionDeclBits.HasSkippedBody = false; 2918 FunctionDeclBits.WillHaveBody = false; 2919 FunctionDeclBits.IsMultiVersion = false; 2920 FunctionDeclBits.IsCopyDeductionCandidate = false; 2921 FunctionDeclBits.HasODRHash = false; 2922 if (TrailingRequiresClause) 2923 setTrailingRequiresClause(TrailingRequiresClause); 2924 } 2925 2926 void FunctionDecl::getNameForDiagnostic( 2927 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 2928 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 2929 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 2930 if (TemplateArgs) 2931 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 2932 } 2933 2934 bool FunctionDecl::isVariadic() const { 2935 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 2936 return FT->isVariadic(); 2937 return false; 2938 } 2939 2940 FunctionDecl::DefaultedFunctionInfo * 2941 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context, 2942 ArrayRef<DeclAccessPair> Lookups) { 2943 DefaultedFunctionInfo *Info = new (Context.Allocate( 2944 totalSizeToAlloc<DeclAccessPair>(Lookups.size()), 2945 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair)))) 2946 DefaultedFunctionInfo; 2947 Info->NumLookups = Lookups.size(); 2948 std::uninitialized_copy(Lookups.begin(), Lookups.end(), 2949 Info->getTrailingObjects<DeclAccessPair>()); 2950 return Info; 2951 } 2952 2953 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) { 2954 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this"); 2955 assert(!Body && "can't replace function body with defaulted function info"); 2956 2957 FunctionDeclBits.HasDefaultedFunctionInfo = true; 2958 DefaultedInfo = Info; 2959 } 2960 2961 FunctionDecl::DefaultedFunctionInfo * 2962 FunctionDecl::getDefaultedFunctionInfo() const { 2963 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr; 2964 } 2965 2966 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 2967 for (auto I : redecls()) { 2968 if (I->doesThisDeclarationHaveABody()) { 2969 Definition = I; 2970 return true; 2971 } 2972 } 2973 2974 return false; 2975 } 2976 2977 bool FunctionDecl::hasTrivialBody() const { 2978 Stmt *S = getBody(); 2979 if (!S) { 2980 // Since we don't have a body for this function, we don't know if it's 2981 // trivial or not. 2982 return false; 2983 } 2984 2985 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 2986 return true; 2987 return false; 2988 } 2989 2990 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const { 2991 if (!getFriendObjectKind()) 2992 return false; 2993 2994 // Check for a friend function instantiated from a friend function 2995 // definition in a templated class. 2996 if (const FunctionDecl *InstantiatedFrom = 2997 getInstantiatedFromMemberFunction()) 2998 return InstantiatedFrom->getFriendObjectKind() && 2999 InstantiatedFrom->isThisDeclarationADefinition(); 3000 3001 // Check for a friend function template instantiated from a friend 3002 // function template definition in a templated class. 3003 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { 3004 if (const FunctionTemplateDecl *InstantiatedFrom = 3005 Template->getInstantiatedFromMemberTemplate()) 3006 return InstantiatedFrom->getFriendObjectKind() && 3007 InstantiatedFrom->isThisDeclarationADefinition(); 3008 } 3009 3010 return false; 3011 } 3012 3013 bool FunctionDecl::isDefined(const FunctionDecl *&Definition, 3014 bool CheckForPendingFriendDefinition) const { 3015 for (const FunctionDecl *FD : redecls()) { 3016 if (FD->isThisDeclarationADefinition()) { 3017 Definition = FD; 3018 return true; 3019 } 3020 3021 // If this is a friend function defined in a class template, it does not 3022 // have a body until it is used, nevertheless it is a definition, see 3023 // [temp.inst]p2: 3024 // 3025 // ... for the purpose of determining whether an instantiated redeclaration 3026 // is valid according to [basic.def.odr] and [class.mem], a declaration that 3027 // corresponds to a definition in the template is considered to be a 3028 // definition. 3029 // 3030 // The following code must produce redefinition error: 3031 // 3032 // template<typename T> struct C20 { friend void func_20() {} }; 3033 // C20<int> c20i; 3034 // void func_20() {} 3035 // 3036 if (CheckForPendingFriendDefinition && 3037 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 3038 Definition = FD; 3039 return true; 3040 } 3041 } 3042 3043 return false; 3044 } 3045 3046 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 3047 if (!hasBody(Definition)) 3048 return nullptr; 3049 3050 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo && 3051 "definition should not have a body"); 3052 if (Definition->Body) 3053 return Definition->Body.get(getASTContext().getExternalSource()); 3054 3055 return nullptr; 3056 } 3057 3058 void FunctionDecl::setBody(Stmt *B) { 3059 FunctionDeclBits.HasDefaultedFunctionInfo = false; 3060 Body = LazyDeclStmtPtr(B); 3061 if (B) 3062 EndRangeLoc = B->getEndLoc(); 3063 } 3064 3065 void FunctionDecl::setPure(bool P) { 3066 FunctionDeclBits.IsPure = P; 3067 if (P) 3068 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 3069 Parent->markedVirtualFunctionPure(); 3070 } 3071 3072 template<std::size_t Len> 3073 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 3074 IdentifierInfo *II = ND->getIdentifier(); 3075 return II && II->isStr(Str); 3076 } 3077 3078 bool FunctionDecl::isMain() const { 3079 const TranslationUnitDecl *tunit = 3080 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3081 return tunit && 3082 !tunit->getASTContext().getLangOpts().Freestanding && 3083 isNamed(this, "main"); 3084 } 3085 3086 bool FunctionDecl::isMSVCRTEntryPoint() const { 3087 const TranslationUnitDecl *TUnit = 3088 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3089 if (!TUnit) 3090 return false; 3091 3092 // Even though we aren't really targeting MSVCRT if we are freestanding, 3093 // semantic analysis for these functions remains the same. 3094 3095 // MSVCRT entry points only exist on MSVCRT targets. 3096 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 3097 return false; 3098 3099 // Nameless functions like constructors cannot be entry points. 3100 if (!getIdentifier()) 3101 return false; 3102 3103 return llvm::StringSwitch<bool>(getName()) 3104 .Cases("main", // an ANSI console app 3105 "wmain", // a Unicode console App 3106 "WinMain", // an ANSI GUI app 3107 "wWinMain", // a Unicode GUI app 3108 "DllMain", // a DLL 3109 true) 3110 .Default(false); 3111 } 3112 3113 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 3114 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 3115 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 3116 getDeclName().getCXXOverloadedOperator() == OO_Delete || 3117 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 3118 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 3119 3120 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3121 return false; 3122 3123 const auto *proto = getType()->castAs<FunctionProtoType>(); 3124 if (proto->getNumParams() != 2 || proto->isVariadic()) 3125 return false; 3126 3127 ASTContext &Context = 3128 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 3129 ->getASTContext(); 3130 3131 // The result type and first argument type are constant across all 3132 // these operators. The second argument must be exactly void*. 3133 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 3134 } 3135 3136 bool FunctionDecl::isReplaceableGlobalAllocationFunction( 3137 Optional<unsigned> *AlignmentParam, bool *IsNothrow) const { 3138 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3139 return false; 3140 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3141 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3142 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3143 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3144 return false; 3145 3146 if (isa<CXXRecordDecl>(getDeclContext())) 3147 return false; 3148 3149 // This can only fail for an invalid 'operator new' declaration. 3150 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3151 return false; 3152 3153 const auto *FPT = getType()->castAs<FunctionProtoType>(); 3154 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic()) 3155 return false; 3156 3157 // If this is a single-parameter function, it must be a replaceable global 3158 // allocation or deallocation function. 3159 if (FPT->getNumParams() == 1) 3160 return true; 3161 3162 unsigned Params = 1; 3163 QualType Ty = FPT->getParamType(Params); 3164 ASTContext &Ctx = getASTContext(); 3165 3166 auto Consume = [&] { 3167 ++Params; 3168 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 3169 }; 3170 3171 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 3172 bool IsSizedDelete = false; 3173 if (Ctx.getLangOpts().SizedDeallocation && 3174 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 3175 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 3176 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 3177 IsSizedDelete = true; 3178 Consume(); 3179 } 3180 3181 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 3182 // new/delete. 3183 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 3184 Consume(); 3185 if (AlignmentParam) 3186 *AlignmentParam = Params; 3187 } 3188 3189 // Finally, if this is not a sized delete, the final parameter can 3190 // be a 'const std::nothrow_t&'. 3191 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 3192 Ty = Ty->getPointeeType(); 3193 if (Ty.getCVRQualifiers() != Qualifiers::Const) 3194 return false; 3195 if (Ty->isNothrowT()) { 3196 if (IsNothrow) 3197 *IsNothrow = true; 3198 Consume(); 3199 } 3200 } 3201 3202 return Params == FPT->getNumParams(); 3203 } 3204 3205 bool FunctionDecl::isInlineBuiltinDeclaration() const { 3206 if (!getBuiltinID()) 3207 return false; 3208 3209 const FunctionDecl *Definition; 3210 return hasBody(Definition) && Definition->isInlineSpecified() && 3211 Definition->hasAttr<AlwaysInlineAttr>() && 3212 Definition->hasAttr<GNUInlineAttr>(); 3213 } 3214 3215 bool FunctionDecl::isDestroyingOperatorDelete() const { 3216 // C++ P0722: 3217 // Within a class C, a single object deallocation function with signature 3218 // (T, std::destroying_delete_t, <more params>) 3219 // is a destroying operator delete. 3220 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 3221 getNumParams() < 2) 3222 return false; 3223 3224 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 3225 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 3226 RD->getIdentifier()->isStr("destroying_delete_t"); 3227 } 3228 3229 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 3230 return getDeclLanguageLinkage(*this); 3231 } 3232 3233 bool FunctionDecl::isExternC() const { 3234 return isDeclExternC(*this); 3235 } 3236 3237 bool FunctionDecl::isInExternCContext() const { 3238 if (hasAttr<OpenCLKernelAttr>()) 3239 return true; 3240 return getLexicalDeclContext()->isExternCContext(); 3241 } 3242 3243 bool FunctionDecl::isInExternCXXContext() const { 3244 return getLexicalDeclContext()->isExternCXXContext(); 3245 } 3246 3247 bool FunctionDecl::isGlobal() const { 3248 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 3249 return Method->isStatic(); 3250 3251 if (getCanonicalDecl()->getStorageClass() == SC_Static) 3252 return false; 3253 3254 for (const DeclContext *DC = getDeclContext(); 3255 DC->isNamespace(); 3256 DC = DC->getParent()) { 3257 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 3258 if (!Namespace->getDeclName()) 3259 return false; 3260 } 3261 } 3262 3263 return true; 3264 } 3265 3266 bool FunctionDecl::isNoReturn() const { 3267 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 3268 hasAttr<C11NoReturnAttr>()) 3269 return true; 3270 3271 if (auto *FnTy = getType()->getAs<FunctionType>()) 3272 return FnTy->getNoReturnAttr(); 3273 3274 return false; 3275 } 3276 3277 3278 MultiVersionKind FunctionDecl::getMultiVersionKind() const { 3279 if (hasAttr<TargetAttr>()) 3280 return MultiVersionKind::Target; 3281 if (hasAttr<CPUDispatchAttr>()) 3282 return MultiVersionKind::CPUDispatch; 3283 if (hasAttr<CPUSpecificAttr>()) 3284 return MultiVersionKind::CPUSpecific; 3285 if (hasAttr<TargetClonesAttr>()) 3286 return MultiVersionKind::TargetClones; 3287 return MultiVersionKind::None; 3288 } 3289 3290 bool FunctionDecl::isCPUDispatchMultiVersion() const { 3291 return isMultiVersion() && hasAttr<CPUDispatchAttr>(); 3292 } 3293 3294 bool FunctionDecl::isCPUSpecificMultiVersion() const { 3295 return isMultiVersion() && hasAttr<CPUSpecificAttr>(); 3296 } 3297 3298 bool FunctionDecl::isTargetMultiVersion() const { 3299 return isMultiVersion() && hasAttr<TargetAttr>(); 3300 } 3301 3302 bool FunctionDecl::isTargetClonesMultiVersion() const { 3303 return isMultiVersion() && hasAttr<TargetClonesAttr>(); 3304 } 3305 3306 void 3307 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 3308 redeclarable_base::setPreviousDecl(PrevDecl); 3309 3310 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 3311 FunctionTemplateDecl *PrevFunTmpl 3312 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 3313 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 3314 FunTmpl->setPreviousDecl(PrevFunTmpl); 3315 } 3316 3317 if (PrevDecl && PrevDecl->isInlined()) 3318 setImplicitlyInline(true); 3319 } 3320 3321 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 3322 3323 /// Returns a value indicating whether this function corresponds to a builtin 3324 /// function. 3325 /// 3326 /// The function corresponds to a built-in function if it is declared at 3327 /// translation scope or within an extern "C" block and its name matches with 3328 /// the name of a builtin. The returned value will be 0 for functions that do 3329 /// not correspond to a builtin, a value of type \c Builtin::ID if in the 3330 /// target-independent range \c [1,Builtin::First), or a target-specific builtin 3331 /// value. 3332 /// 3333 /// \param ConsiderWrapperFunctions If true, we should consider wrapper 3334 /// functions as their wrapped builtins. This shouldn't be done in general, but 3335 /// it's useful in Sema to diagnose calls to wrappers based on their semantics. 3336 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { 3337 unsigned BuiltinID = 0; 3338 3339 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) { 3340 BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); 3341 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) { 3342 BuiltinID = BAA->getBuiltinName()->getBuiltinID(); 3343 } else if (const auto *A = getAttr<BuiltinAttr>()) { 3344 BuiltinID = A->getID(); 3345 } 3346 3347 if (!BuiltinID) 3348 return 0; 3349 3350 // If the function is marked "overloadable", it has a different mangled name 3351 // and is not the C library function. 3352 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() && 3353 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>())) 3354 return 0; 3355 3356 ASTContext &Context = getASTContext(); 3357 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3358 return BuiltinID; 3359 3360 // This function has the name of a known C library 3361 // function. Determine whether it actually refers to the C library 3362 // function or whether it just has the same name. 3363 3364 // If this is a static function, it's not a builtin. 3365 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static) 3366 return 0; 3367 3368 // OpenCL v1.2 s6.9.f - The library functions defined in 3369 // the C99 standard headers are not available. 3370 if (Context.getLangOpts().OpenCL && 3371 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3372 return 0; 3373 3374 // CUDA does not have device-side standard library. printf and malloc are the 3375 // only special cases that are supported by device-side runtime. 3376 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && 3377 !hasAttr<CUDAHostAttr>() && 3378 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3379 return 0; 3380 3381 // As AMDGCN implementation of OpenMP does not have a device-side standard 3382 // library, none of the predefined library functions except printf and malloc 3383 // should be treated as a builtin i.e. 0 should be returned for them. 3384 if (Context.getTargetInfo().getTriple().isAMDGCN() && 3385 Context.getLangOpts().OpenMPIsDevice && 3386 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 3387 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3388 return 0; 3389 3390 return BuiltinID; 3391 } 3392 3393 /// getNumParams - Return the number of parameters this function must have 3394 /// based on its FunctionType. This is the length of the ParamInfo array 3395 /// after it has been created. 3396 unsigned FunctionDecl::getNumParams() const { 3397 const auto *FPT = getType()->getAs<FunctionProtoType>(); 3398 return FPT ? FPT->getNumParams() : 0; 3399 } 3400 3401 void FunctionDecl::setParams(ASTContext &C, 3402 ArrayRef<ParmVarDecl *> NewParamInfo) { 3403 assert(!ParamInfo && "Already has param info!"); 3404 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 3405 3406 // Zero params -> null pointer. 3407 if (!NewParamInfo.empty()) { 3408 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 3409 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3410 } 3411 } 3412 3413 /// getMinRequiredArguments - Returns the minimum number of arguments 3414 /// needed to call this function. This may be fewer than the number of 3415 /// function parameters, if some of the parameters have default 3416 /// arguments (in C++) or are parameter packs (C++11). 3417 unsigned FunctionDecl::getMinRequiredArguments() const { 3418 if (!getASTContext().getLangOpts().CPlusPlus) 3419 return getNumParams(); 3420 3421 // Note that it is possible for a parameter with no default argument to 3422 // follow a parameter with a default argument. 3423 unsigned NumRequiredArgs = 0; 3424 unsigned MinParamsSoFar = 0; 3425 for (auto *Param : parameters()) { 3426 if (!Param->isParameterPack()) { 3427 ++MinParamsSoFar; 3428 if (!Param->hasDefaultArg()) 3429 NumRequiredArgs = MinParamsSoFar; 3430 } 3431 } 3432 return NumRequiredArgs; 3433 } 3434 3435 bool FunctionDecl::hasOneParamOrDefaultArgs() const { 3436 return getNumParams() == 1 || 3437 (getNumParams() > 1 && 3438 std::all_of(param_begin() + 1, param_end(), 3439 [](ParmVarDecl *P) { return P->hasDefaultArg(); })); 3440 } 3441 3442 /// The combination of the extern and inline keywords under MSVC forces 3443 /// the function to be required. 3444 /// 3445 /// Note: This function assumes that we will only get called when isInlined() 3446 /// would return true for this FunctionDecl. 3447 bool FunctionDecl::isMSExternInline() const { 3448 assert(isInlined() && "expected to get called on an inlined function!"); 3449 3450 const ASTContext &Context = getASTContext(); 3451 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 3452 !hasAttr<DLLExportAttr>()) 3453 return false; 3454 3455 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 3456 FD = FD->getPreviousDecl()) 3457 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3458 return true; 3459 3460 return false; 3461 } 3462 3463 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 3464 if (Redecl->getStorageClass() != SC_Extern) 3465 return false; 3466 3467 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 3468 FD = FD->getPreviousDecl()) 3469 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3470 return false; 3471 3472 return true; 3473 } 3474 3475 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 3476 // Only consider file-scope declarations in this test. 3477 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 3478 return false; 3479 3480 // Only consider explicit declarations; the presence of a builtin for a 3481 // libcall shouldn't affect whether a definition is externally visible. 3482 if (Redecl->isImplicit()) 3483 return false; 3484 3485 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 3486 return true; // Not an inline definition 3487 3488 return false; 3489 } 3490 3491 /// For a function declaration in C or C++, determine whether this 3492 /// declaration causes the definition to be externally visible. 3493 /// 3494 /// For instance, this determines if adding the current declaration to the set 3495 /// of redeclarations of the given functions causes 3496 /// isInlineDefinitionExternallyVisible to change from false to true. 3497 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 3498 assert(!doesThisDeclarationHaveABody() && 3499 "Must have a declaration without a body."); 3500 3501 ASTContext &Context = getASTContext(); 3502 3503 if (Context.getLangOpts().MSVCCompat) { 3504 const FunctionDecl *Definition; 3505 if (hasBody(Definition) && Definition->isInlined() && 3506 redeclForcesDefMSVC(this)) 3507 return true; 3508 } 3509 3510 if (Context.getLangOpts().CPlusPlus) 3511 return false; 3512 3513 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3514 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3515 // an externally visible definition. 3516 // 3517 // FIXME: What happens if gnu_inline gets added on after the first 3518 // declaration? 3519 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3520 return false; 3521 3522 const FunctionDecl *Prev = this; 3523 bool FoundBody = false; 3524 while ((Prev = Prev->getPreviousDecl())) { 3525 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3526 3527 if (Prev->doesThisDeclarationHaveABody()) { 3528 // If it's not the case that both 'inline' and 'extern' are 3529 // specified on the definition, then it is always externally visible. 3530 if (!Prev->isInlineSpecified() || 3531 Prev->getStorageClass() != SC_Extern) 3532 return false; 3533 } else if (Prev->isInlineSpecified() && 3534 Prev->getStorageClass() != SC_Extern) { 3535 return false; 3536 } 3537 } 3538 return FoundBody; 3539 } 3540 3541 // C99 6.7.4p6: 3542 // [...] If all of the file scope declarations for a function in a 3543 // translation unit include the inline function specifier without extern, 3544 // then the definition in that translation unit is an inline definition. 3545 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3546 return false; 3547 const FunctionDecl *Prev = this; 3548 bool FoundBody = false; 3549 while ((Prev = Prev->getPreviousDecl())) { 3550 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3551 if (RedeclForcesDefC99(Prev)) 3552 return false; 3553 } 3554 return FoundBody; 3555 } 3556 3557 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { 3558 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3559 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>() 3560 : FunctionTypeLoc(); 3561 } 3562 3563 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3564 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3565 if (!FTL) 3566 return SourceRange(); 3567 3568 // Skip self-referential return types. 3569 const SourceManager &SM = getASTContext().getSourceManager(); 3570 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3571 SourceLocation Boundary = getNameInfo().getBeginLoc(); 3572 if (RTRange.isInvalid() || Boundary.isInvalid() || 3573 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3574 return SourceRange(); 3575 3576 return RTRange; 3577 } 3578 3579 SourceRange FunctionDecl::getParametersSourceRange() const { 3580 unsigned NP = getNumParams(); 3581 SourceLocation EllipsisLoc = getEllipsisLoc(); 3582 3583 if (NP == 0 && EllipsisLoc.isInvalid()) 3584 return SourceRange(); 3585 3586 SourceLocation Begin = 3587 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc; 3588 SourceLocation End = EllipsisLoc.isValid() 3589 ? EllipsisLoc 3590 : ParamInfo[NP - 1]->getSourceRange().getEnd(); 3591 3592 return SourceRange(Begin, End); 3593 } 3594 3595 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3596 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3597 return FTL ? FTL.getExceptionSpecRange() : SourceRange(); 3598 } 3599 3600 /// For an inline function definition in C, or for a gnu_inline function 3601 /// in C++, determine whether the definition will be externally visible. 3602 /// 3603 /// Inline function definitions are always available for inlining optimizations. 3604 /// However, depending on the language dialect, declaration specifiers, and 3605 /// attributes, the definition of an inline function may or may not be 3606 /// "externally" visible to other translation units in the program. 3607 /// 3608 /// In C99, inline definitions are not externally visible by default. However, 3609 /// if even one of the global-scope declarations is marked "extern inline", the 3610 /// inline definition becomes externally visible (C99 6.7.4p6). 3611 /// 3612 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3613 /// definition, we use the GNU semantics for inline, which are nearly the 3614 /// opposite of C99 semantics. In particular, "inline" by itself will create 3615 /// an externally visible symbol, but "extern inline" will not create an 3616 /// externally visible symbol. 3617 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3618 assert((doesThisDeclarationHaveABody() || willHaveBody() || 3619 hasAttr<AliasAttr>()) && 3620 "Must be a function definition"); 3621 assert(isInlined() && "Function must be inline"); 3622 ASTContext &Context = getASTContext(); 3623 3624 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3625 // Note: If you change the logic here, please change 3626 // doesDeclarationForceExternallyVisibleDefinition as well. 3627 // 3628 // If it's not the case that both 'inline' and 'extern' are 3629 // specified on the definition, then this inline definition is 3630 // externally visible. 3631 if (Context.getLangOpts().CPlusPlus) 3632 return false; 3633 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3634 return true; 3635 3636 // If any declaration is 'inline' but not 'extern', then this definition 3637 // is externally visible. 3638 for (auto Redecl : redecls()) { 3639 if (Redecl->isInlineSpecified() && 3640 Redecl->getStorageClass() != SC_Extern) 3641 return true; 3642 } 3643 3644 return false; 3645 } 3646 3647 // The rest of this function is C-only. 3648 assert(!Context.getLangOpts().CPlusPlus && 3649 "should not use C inline rules in C++"); 3650 3651 // C99 6.7.4p6: 3652 // [...] If all of the file scope declarations for a function in a 3653 // translation unit include the inline function specifier without extern, 3654 // then the definition in that translation unit is an inline definition. 3655 for (auto Redecl : redecls()) { 3656 if (RedeclForcesDefC99(Redecl)) 3657 return true; 3658 } 3659 3660 // C99 6.7.4p6: 3661 // An inline definition does not provide an external definition for the 3662 // function, and does not forbid an external definition in another 3663 // translation unit. 3664 return false; 3665 } 3666 3667 /// getOverloadedOperator - Which C++ overloaded operator this 3668 /// function represents, if any. 3669 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3670 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3671 return getDeclName().getCXXOverloadedOperator(); 3672 return OO_None; 3673 } 3674 3675 /// getLiteralIdentifier - The literal suffix identifier this function 3676 /// represents, if any. 3677 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3678 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3679 return getDeclName().getCXXLiteralIdentifier(); 3680 return nullptr; 3681 } 3682 3683 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 3684 if (TemplateOrSpecialization.isNull()) 3685 return TK_NonTemplate; 3686 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 3687 return TK_FunctionTemplate; 3688 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 3689 return TK_MemberSpecialization; 3690 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 3691 return TK_FunctionTemplateSpecialization; 3692 if (TemplateOrSpecialization.is 3693 <DependentFunctionTemplateSpecializationInfo*>()) 3694 return TK_DependentFunctionTemplateSpecialization; 3695 3696 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 3697 } 3698 3699 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 3700 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 3701 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 3702 3703 return nullptr; 3704 } 3705 3706 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 3707 if (auto *MSI = 3708 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3709 return MSI; 3710 if (auto *FTSI = TemplateOrSpecialization 3711 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 3712 return FTSI->getMemberSpecializationInfo(); 3713 return nullptr; 3714 } 3715 3716 void 3717 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 3718 FunctionDecl *FD, 3719 TemplateSpecializationKind TSK) { 3720 assert(TemplateOrSpecialization.isNull() && 3721 "Member function is already a specialization"); 3722 MemberSpecializationInfo *Info 3723 = new (C) MemberSpecializationInfo(FD, TSK); 3724 TemplateOrSpecialization = Info; 3725 } 3726 3727 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 3728 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>(); 3729 } 3730 3731 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { 3732 assert(TemplateOrSpecialization.isNull() && 3733 "Member function is already a specialization"); 3734 TemplateOrSpecialization = Template; 3735 } 3736 3737 bool FunctionDecl::isImplicitlyInstantiable() const { 3738 // If the function is invalid, it can't be implicitly instantiated. 3739 if (isInvalidDecl()) 3740 return false; 3741 3742 switch (getTemplateSpecializationKindForInstantiation()) { 3743 case TSK_Undeclared: 3744 case TSK_ExplicitInstantiationDefinition: 3745 case TSK_ExplicitSpecialization: 3746 return false; 3747 3748 case TSK_ImplicitInstantiation: 3749 return true; 3750 3751 case TSK_ExplicitInstantiationDeclaration: 3752 // Handled below. 3753 break; 3754 } 3755 3756 // Find the actual template from which we will instantiate. 3757 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 3758 bool HasPattern = false; 3759 if (PatternDecl) 3760 HasPattern = PatternDecl->hasBody(PatternDecl); 3761 3762 // C++0x [temp.explicit]p9: 3763 // Except for inline functions, other explicit instantiation declarations 3764 // have the effect of suppressing the implicit instantiation of the entity 3765 // to which they refer. 3766 if (!HasPattern || !PatternDecl) 3767 return true; 3768 3769 return PatternDecl->isInlined(); 3770 } 3771 3772 bool FunctionDecl::isTemplateInstantiation() const { 3773 // FIXME: Remove this, it's not clear what it means. (Which template 3774 // specialization kind?) 3775 return clang::isTemplateInstantiation(getTemplateSpecializationKind()); 3776 } 3777 3778 FunctionDecl * 3779 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const { 3780 // If this is a generic lambda call operator specialization, its 3781 // instantiation pattern is always its primary template's pattern 3782 // even if its primary template was instantiated from another 3783 // member template (which happens with nested generic lambdas). 3784 // Since a lambda's call operator's body is transformed eagerly, 3785 // we don't have to go hunting for a prototype definition template 3786 // (i.e. instantiated-from-member-template) to use as an instantiation 3787 // pattern. 3788 3789 if (isGenericLambdaCallOperatorSpecialization( 3790 dyn_cast<CXXMethodDecl>(this))) { 3791 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 3792 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 3793 } 3794 3795 // Check for a declaration of this function that was instantiated from a 3796 // friend definition. 3797 const FunctionDecl *FD = nullptr; 3798 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true)) 3799 FD = this; 3800 3801 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) { 3802 if (ForDefinition && 3803 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind())) 3804 return nullptr; 3805 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom())); 3806 } 3807 3808 if (ForDefinition && 3809 !clang::isTemplateInstantiation(getTemplateSpecializationKind())) 3810 return nullptr; 3811 3812 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 3813 // If we hit a point where the user provided a specialization of this 3814 // template, we're done looking. 3815 while (!ForDefinition || !Primary->isMemberSpecialization()) { 3816 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate(); 3817 if (!NewPrimary) 3818 break; 3819 Primary = NewPrimary; 3820 } 3821 3822 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 3823 } 3824 3825 return nullptr; 3826 } 3827 3828 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 3829 if (FunctionTemplateSpecializationInfo *Info 3830 = TemplateOrSpecialization 3831 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3832 return Info->getTemplate(); 3833 } 3834 return nullptr; 3835 } 3836 3837 FunctionTemplateSpecializationInfo * 3838 FunctionDecl::getTemplateSpecializationInfo() const { 3839 return TemplateOrSpecialization 3840 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 3841 } 3842 3843 const TemplateArgumentList * 3844 FunctionDecl::getTemplateSpecializationArgs() const { 3845 if (FunctionTemplateSpecializationInfo *Info 3846 = TemplateOrSpecialization 3847 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3848 return Info->TemplateArguments; 3849 } 3850 return nullptr; 3851 } 3852 3853 const ASTTemplateArgumentListInfo * 3854 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 3855 if (FunctionTemplateSpecializationInfo *Info 3856 = TemplateOrSpecialization 3857 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3858 return Info->TemplateArgumentsAsWritten; 3859 } 3860 return nullptr; 3861 } 3862 3863 void 3864 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 3865 FunctionTemplateDecl *Template, 3866 const TemplateArgumentList *TemplateArgs, 3867 void *InsertPos, 3868 TemplateSpecializationKind TSK, 3869 const TemplateArgumentListInfo *TemplateArgsAsWritten, 3870 SourceLocation PointOfInstantiation) { 3871 assert((TemplateOrSpecialization.isNull() || 3872 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && 3873 "Member function is already a specialization"); 3874 assert(TSK != TSK_Undeclared && 3875 "Must specify the type of function template specialization"); 3876 assert((TemplateOrSpecialization.isNull() || 3877 TSK == TSK_ExplicitSpecialization) && 3878 "Member specialization must be an explicit specialization"); 3879 FunctionTemplateSpecializationInfo *Info = 3880 FunctionTemplateSpecializationInfo::Create( 3881 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten, 3882 PointOfInstantiation, 3883 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()); 3884 TemplateOrSpecialization = Info; 3885 Template->addSpecialization(Info, InsertPos); 3886 } 3887 3888 void 3889 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 3890 const UnresolvedSetImpl &Templates, 3891 const TemplateArgumentListInfo &TemplateArgs) { 3892 assert(TemplateOrSpecialization.isNull()); 3893 DependentFunctionTemplateSpecializationInfo *Info = 3894 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 3895 TemplateArgs); 3896 TemplateOrSpecialization = Info; 3897 } 3898 3899 DependentFunctionTemplateSpecializationInfo * 3900 FunctionDecl::getDependentSpecializationInfo() const { 3901 return TemplateOrSpecialization 3902 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 3903 } 3904 3905 DependentFunctionTemplateSpecializationInfo * 3906 DependentFunctionTemplateSpecializationInfo::Create( 3907 ASTContext &Context, const UnresolvedSetImpl &Ts, 3908 const TemplateArgumentListInfo &TArgs) { 3909 void *Buffer = Context.Allocate( 3910 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>( 3911 TArgs.size(), Ts.size())); 3912 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs); 3913 } 3914 3915 DependentFunctionTemplateSpecializationInfo:: 3916 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 3917 const TemplateArgumentListInfo &TArgs) 3918 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 3919 NumTemplates = Ts.size(); 3920 NumArgs = TArgs.size(); 3921 3922 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>(); 3923 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 3924 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 3925 3926 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>(); 3927 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 3928 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 3929 } 3930 3931 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 3932 // For a function template specialization, query the specialization 3933 // information object. 3934 if (FunctionTemplateSpecializationInfo *FTSInfo = 3935 TemplateOrSpecialization 3936 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 3937 return FTSInfo->getTemplateSpecializationKind(); 3938 3939 if (MemberSpecializationInfo *MSInfo = 3940 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3941 return MSInfo->getTemplateSpecializationKind(); 3942 3943 return TSK_Undeclared; 3944 } 3945 3946 TemplateSpecializationKind 3947 FunctionDecl::getTemplateSpecializationKindForInstantiation() const { 3948 // This is the same as getTemplateSpecializationKind(), except that for a 3949 // function that is both a function template specialization and a member 3950 // specialization, we prefer the member specialization information. Eg: 3951 // 3952 // template<typename T> struct A { 3953 // template<typename U> void f() {} 3954 // template<> void f<int>() {} 3955 // }; 3956 // 3957 // For A<int>::f<int>(): 3958 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization 3959 // * getTemplateSpecializationKindForInstantiation() will return 3960 // TSK_ImplicitInstantiation 3961 // 3962 // This reflects the facts that A<int>::f<int> is an explicit specialization 3963 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated 3964 // from A::f<int> if a definition is needed. 3965 if (FunctionTemplateSpecializationInfo *FTSInfo = 3966 TemplateOrSpecialization 3967 .dyn_cast<FunctionTemplateSpecializationInfo *>()) { 3968 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo()) 3969 return MSInfo->getTemplateSpecializationKind(); 3970 return FTSInfo->getTemplateSpecializationKind(); 3971 } 3972 3973 if (MemberSpecializationInfo *MSInfo = 3974 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3975 return MSInfo->getTemplateSpecializationKind(); 3976 3977 return TSK_Undeclared; 3978 } 3979 3980 void 3981 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3982 SourceLocation PointOfInstantiation) { 3983 if (FunctionTemplateSpecializationInfo *FTSInfo 3984 = TemplateOrSpecialization.dyn_cast< 3985 FunctionTemplateSpecializationInfo*>()) { 3986 FTSInfo->setTemplateSpecializationKind(TSK); 3987 if (TSK != TSK_ExplicitSpecialization && 3988 PointOfInstantiation.isValid() && 3989 FTSInfo->getPointOfInstantiation().isInvalid()) { 3990 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 3991 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 3992 L->InstantiationRequested(this); 3993 } 3994 } else if (MemberSpecializationInfo *MSInfo 3995 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 3996 MSInfo->setTemplateSpecializationKind(TSK); 3997 if (TSK != TSK_ExplicitSpecialization && 3998 PointOfInstantiation.isValid() && 3999 MSInfo->getPointOfInstantiation().isInvalid()) { 4000 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4001 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4002 L->InstantiationRequested(this); 4003 } 4004 } else 4005 llvm_unreachable("Function cannot have a template specialization kind"); 4006 } 4007 4008 SourceLocation FunctionDecl::getPointOfInstantiation() const { 4009 if (FunctionTemplateSpecializationInfo *FTSInfo 4010 = TemplateOrSpecialization.dyn_cast< 4011 FunctionTemplateSpecializationInfo*>()) 4012 return FTSInfo->getPointOfInstantiation(); 4013 if (MemberSpecializationInfo *MSInfo = 4014 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4015 return MSInfo->getPointOfInstantiation(); 4016 4017 return SourceLocation(); 4018 } 4019 4020 bool FunctionDecl::isOutOfLine() const { 4021 if (Decl::isOutOfLine()) 4022 return true; 4023 4024 // If this function was instantiated from a member function of a 4025 // class template, check whether that member function was defined out-of-line. 4026 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 4027 const FunctionDecl *Definition; 4028 if (FD->hasBody(Definition)) 4029 return Definition->isOutOfLine(); 4030 } 4031 4032 // If this function was instantiated from a function template, 4033 // check whether that function template was defined out-of-line. 4034 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 4035 const FunctionDecl *Definition; 4036 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 4037 return Definition->isOutOfLine(); 4038 } 4039 4040 return false; 4041 } 4042 4043 SourceRange FunctionDecl::getSourceRange() const { 4044 return SourceRange(getOuterLocStart(), EndRangeLoc); 4045 } 4046 4047 unsigned FunctionDecl::getMemoryFunctionKind() const { 4048 IdentifierInfo *FnInfo = getIdentifier(); 4049 4050 if (!FnInfo) 4051 return 0; 4052 4053 // Builtin handling. 4054 switch (getBuiltinID()) { 4055 case Builtin::BI__builtin_memset: 4056 case Builtin::BI__builtin___memset_chk: 4057 case Builtin::BImemset: 4058 return Builtin::BImemset; 4059 4060 case Builtin::BI__builtin_memcpy: 4061 case Builtin::BI__builtin___memcpy_chk: 4062 case Builtin::BImemcpy: 4063 return Builtin::BImemcpy; 4064 4065 case Builtin::BI__builtin_mempcpy: 4066 case Builtin::BI__builtin___mempcpy_chk: 4067 case Builtin::BImempcpy: 4068 return Builtin::BImempcpy; 4069 4070 case Builtin::BI__builtin_memmove: 4071 case Builtin::BI__builtin___memmove_chk: 4072 case Builtin::BImemmove: 4073 return Builtin::BImemmove; 4074 4075 case Builtin::BIstrlcpy: 4076 case Builtin::BI__builtin___strlcpy_chk: 4077 return Builtin::BIstrlcpy; 4078 4079 case Builtin::BIstrlcat: 4080 case Builtin::BI__builtin___strlcat_chk: 4081 return Builtin::BIstrlcat; 4082 4083 case Builtin::BI__builtin_memcmp: 4084 case Builtin::BImemcmp: 4085 return Builtin::BImemcmp; 4086 4087 case Builtin::BI__builtin_bcmp: 4088 case Builtin::BIbcmp: 4089 return Builtin::BIbcmp; 4090 4091 case Builtin::BI__builtin_strncpy: 4092 case Builtin::BI__builtin___strncpy_chk: 4093 case Builtin::BIstrncpy: 4094 return Builtin::BIstrncpy; 4095 4096 case Builtin::BI__builtin_strncmp: 4097 case Builtin::BIstrncmp: 4098 return Builtin::BIstrncmp; 4099 4100 case Builtin::BI__builtin_strncasecmp: 4101 case Builtin::BIstrncasecmp: 4102 return Builtin::BIstrncasecmp; 4103 4104 case Builtin::BI__builtin_strncat: 4105 case Builtin::BI__builtin___strncat_chk: 4106 case Builtin::BIstrncat: 4107 return Builtin::BIstrncat; 4108 4109 case Builtin::BI__builtin_strndup: 4110 case Builtin::BIstrndup: 4111 return Builtin::BIstrndup; 4112 4113 case Builtin::BI__builtin_strlen: 4114 case Builtin::BIstrlen: 4115 return Builtin::BIstrlen; 4116 4117 case Builtin::BI__builtin_bzero: 4118 case Builtin::BIbzero: 4119 return Builtin::BIbzero; 4120 4121 case Builtin::BIfree: 4122 return Builtin::BIfree; 4123 4124 default: 4125 if (isExternC()) { 4126 if (FnInfo->isStr("memset")) 4127 return Builtin::BImemset; 4128 if (FnInfo->isStr("memcpy")) 4129 return Builtin::BImemcpy; 4130 if (FnInfo->isStr("mempcpy")) 4131 return Builtin::BImempcpy; 4132 if (FnInfo->isStr("memmove")) 4133 return Builtin::BImemmove; 4134 if (FnInfo->isStr("memcmp")) 4135 return Builtin::BImemcmp; 4136 if (FnInfo->isStr("bcmp")) 4137 return Builtin::BIbcmp; 4138 if (FnInfo->isStr("strncpy")) 4139 return Builtin::BIstrncpy; 4140 if (FnInfo->isStr("strncmp")) 4141 return Builtin::BIstrncmp; 4142 if (FnInfo->isStr("strncasecmp")) 4143 return Builtin::BIstrncasecmp; 4144 if (FnInfo->isStr("strncat")) 4145 return Builtin::BIstrncat; 4146 if (FnInfo->isStr("strndup")) 4147 return Builtin::BIstrndup; 4148 if (FnInfo->isStr("strlen")) 4149 return Builtin::BIstrlen; 4150 if (FnInfo->isStr("bzero")) 4151 return Builtin::BIbzero; 4152 } else if (isInStdNamespace()) { 4153 if (FnInfo->isStr("free")) 4154 return Builtin::BIfree; 4155 } 4156 break; 4157 } 4158 return 0; 4159 } 4160 4161 unsigned FunctionDecl::getODRHash() const { 4162 assert(hasODRHash()); 4163 return ODRHash; 4164 } 4165 4166 unsigned FunctionDecl::getODRHash() { 4167 if (hasODRHash()) 4168 return ODRHash; 4169 4170 if (auto *FT = getInstantiatedFromMemberFunction()) { 4171 setHasODRHash(true); 4172 ODRHash = FT->getODRHash(); 4173 return ODRHash; 4174 } 4175 4176 class ODRHash Hash; 4177 Hash.AddFunctionDecl(this); 4178 setHasODRHash(true); 4179 ODRHash = Hash.CalculateHash(); 4180 return ODRHash; 4181 } 4182 4183 //===----------------------------------------------------------------------===// 4184 // FieldDecl Implementation 4185 //===----------------------------------------------------------------------===// 4186 4187 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 4188 SourceLocation StartLoc, SourceLocation IdLoc, 4189 IdentifierInfo *Id, QualType T, 4190 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 4191 InClassInitStyle InitStyle) { 4192 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 4193 BW, Mutable, InitStyle); 4194 } 4195 4196 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4197 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 4198 SourceLocation(), nullptr, QualType(), nullptr, 4199 nullptr, false, ICIS_NoInit); 4200 } 4201 4202 bool FieldDecl::isAnonymousStructOrUnion() const { 4203 if (!isImplicit() || getDeclName()) 4204 return false; 4205 4206 if (const auto *Record = getType()->getAs<RecordType>()) 4207 return Record->getDecl()->isAnonymousStructOrUnion(); 4208 4209 return false; 4210 } 4211 4212 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 4213 assert(isBitField() && "not a bitfield"); 4214 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 4215 } 4216 4217 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const { 4218 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() && 4219 getBitWidthValue(Ctx) == 0; 4220 } 4221 4222 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { 4223 if (isZeroLengthBitField(Ctx)) 4224 return true; 4225 4226 // C++2a [intro.object]p7: 4227 // An object has nonzero size if it 4228 // -- is not a potentially-overlapping subobject, or 4229 if (!hasAttr<NoUniqueAddressAttr>()) 4230 return false; 4231 4232 // -- is not of class type, or 4233 const auto *RT = getType()->getAs<RecordType>(); 4234 if (!RT) 4235 return false; 4236 const RecordDecl *RD = RT->getDecl()->getDefinition(); 4237 if (!RD) { 4238 assert(isInvalidDecl() && "valid field has incomplete type"); 4239 return false; 4240 } 4241 4242 // -- [has] virtual member functions or virtual base classes, or 4243 // -- has subobjects of nonzero size or bit-fields of nonzero length 4244 const auto *CXXRD = cast<CXXRecordDecl>(RD); 4245 if (!CXXRD->isEmpty()) 4246 return false; 4247 4248 // Otherwise, [...] the circumstances under which the object has zero size 4249 // are implementation-defined. 4250 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS 4251 // ABI will do. 4252 return true; 4253 } 4254 4255 unsigned FieldDecl::getFieldIndex() const { 4256 const FieldDecl *Canonical = getCanonicalDecl(); 4257 if (Canonical != this) 4258 return Canonical->getFieldIndex(); 4259 4260 if (CachedFieldIndex) return CachedFieldIndex - 1; 4261 4262 unsigned Index = 0; 4263 const RecordDecl *RD = getParent()->getDefinition(); 4264 assert(RD && "requested index for field of struct with no definition"); 4265 4266 for (auto *Field : RD->fields()) { 4267 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 4268 ++Index; 4269 } 4270 4271 assert(CachedFieldIndex && "failed to find field in parent"); 4272 return CachedFieldIndex - 1; 4273 } 4274 4275 SourceRange FieldDecl::getSourceRange() const { 4276 const Expr *FinalExpr = getInClassInitializer(); 4277 if (!FinalExpr) 4278 FinalExpr = getBitWidth(); 4279 if (FinalExpr) 4280 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc()); 4281 return DeclaratorDecl::getSourceRange(); 4282 } 4283 4284 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 4285 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 4286 "capturing type in non-lambda or captured record."); 4287 assert(InitStorage.getInt() == ISK_NoInit && 4288 InitStorage.getPointer() == nullptr && 4289 "bit width, initializer or captured type already set"); 4290 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType), 4291 ISK_CapturedVLAType); 4292 } 4293 4294 //===----------------------------------------------------------------------===// 4295 // TagDecl Implementation 4296 //===----------------------------------------------------------------------===// 4297 4298 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, 4299 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, 4300 SourceLocation StartL) 4301 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), 4302 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { 4303 assert((DK != Enum || TK == TTK_Enum) && 4304 "EnumDecl not matched with TTK_Enum"); 4305 setPreviousDecl(PrevDecl); 4306 setTagKind(TK); 4307 setCompleteDefinition(false); 4308 setBeingDefined(false); 4309 setEmbeddedInDeclarator(false); 4310 setFreeStanding(false); 4311 setCompleteDefinitionRequired(false); 4312 TagDeclBits.IsThisDeclarationADemotedDefinition = false; 4313 } 4314 4315 SourceLocation TagDecl::getOuterLocStart() const { 4316 return getTemplateOrInnerLocStart(this); 4317 } 4318 4319 SourceRange TagDecl::getSourceRange() const { 4320 SourceLocation RBraceLoc = BraceRange.getEnd(); 4321 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 4322 return SourceRange(getOuterLocStart(), E); 4323 } 4324 4325 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 4326 4327 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 4328 TypedefNameDeclOrQualifier = TDD; 4329 if (const Type *T = getTypeForDecl()) { 4330 (void)T; 4331 assert(T->isLinkageValid()); 4332 } 4333 assert(isLinkageValid()); 4334 } 4335 4336 void TagDecl::startDefinition() { 4337 setBeingDefined(true); 4338 4339 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 4340 struct CXXRecordDecl::DefinitionData *Data = 4341 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 4342 for (auto I : redecls()) 4343 cast<CXXRecordDecl>(I)->DefinitionData = Data; 4344 } 4345 } 4346 4347 void TagDecl::completeDefinition() { 4348 assert((!isa<CXXRecordDecl>(this) || 4349 cast<CXXRecordDecl>(this)->hasDefinition()) && 4350 "definition completed but not started"); 4351 4352 setCompleteDefinition(true); 4353 setBeingDefined(false); 4354 4355 if (ASTMutationListener *L = getASTMutationListener()) 4356 L->CompletedTagDefinition(this); 4357 } 4358 4359 TagDecl *TagDecl::getDefinition() const { 4360 if (isCompleteDefinition()) 4361 return const_cast<TagDecl *>(this); 4362 4363 // If it's possible for us to have an out-of-date definition, check now. 4364 if (mayHaveOutOfDateDef()) { 4365 if (IdentifierInfo *II = getIdentifier()) { 4366 if (II->isOutOfDate()) { 4367 updateOutOfDate(*II); 4368 } 4369 } 4370 } 4371 4372 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 4373 return CXXRD->getDefinition(); 4374 4375 for (auto R : redecls()) 4376 if (R->isCompleteDefinition()) 4377 return R; 4378 4379 return nullptr; 4380 } 4381 4382 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 4383 if (QualifierLoc) { 4384 // Make sure the extended qualifier info is allocated. 4385 if (!hasExtInfo()) 4386 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4387 // Set qualifier info. 4388 getExtInfo()->QualifierLoc = QualifierLoc; 4389 } else { 4390 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 4391 if (hasExtInfo()) { 4392 if (getExtInfo()->NumTemplParamLists == 0) { 4393 getASTContext().Deallocate(getExtInfo()); 4394 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 4395 } 4396 else 4397 getExtInfo()->QualifierLoc = QualifierLoc; 4398 } 4399 } 4400 } 4401 4402 void TagDecl::setTemplateParameterListsInfo( 4403 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 4404 assert(!TPLists.empty()); 4405 // Make sure the extended decl info is allocated. 4406 if (!hasExtInfo()) 4407 // Allocate external info struct. 4408 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4409 // Set the template parameter lists info. 4410 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 4411 } 4412 4413 //===----------------------------------------------------------------------===// 4414 // EnumDecl Implementation 4415 //===----------------------------------------------------------------------===// 4416 4417 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4418 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, 4419 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 4420 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4421 assert(Scoped || !ScopedUsingClassTag); 4422 IntegerType = nullptr; 4423 setNumPositiveBits(0); 4424 setNumNegativeBits(0); 4425 setScoped(Scoped); 4426 setScopedUsingClassTag(ScopedUsingClassTag); 4427 setFixed(Fixed); 4428 setHasODRHash(false); 4429 ODRHash = 0; 4430 } 4431 4432 void EnumDecl::anchor() {} 4433 4434 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 4435 SourceLocation StartLoc, SourceLocation IdLoc, 4436 IdentifierInfo *Id, 4437 EnumDecl *PrevDecl, bool IsScoped, 4438 bool IsScopedUsingClassTag, bool IsFixed) { 4439 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 4440 IsScoped, IsScopedUsingClassTag, IsFixed); 4441 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4442 C.getTypeDeclType(Enum, PrevDecl); 4443 return Enum; 4444 } 4445 4446 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4447 EnumDecl *Enum = 4448 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 4449 nullptr, nullptr, false, false, false); 4450 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4451 return Enum; 4452 } 4453 4454 SourceRange EnumDecl::getIntegerTypeRange() const { 4455 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 4456 return TI->getTypeLoc().getSourceRange(); 4457 return SourceRange(); 4458 } 4459 4460 void EnumDecl::completeDefinition(QualType NewType, 4461 QualType NewPromotionType, 4462 unsigned NumPositiveBits, 4463 unsigned NumNegativeBits) { 4464 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 4465 if (!IntegerType) 4466 IntegerType = NewType.getTypePtr(); 4467 PromotionType = NewPromotionType; 4468 setNumPositiveBits(NumPositiveBits); 4469 setNumNegativeBits(NumNegativeBits); 4470 TagDecl::completeDefinition(); 4471 } 4472 4473 bool EnumDecl::isClosed() const { 4474 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 4475 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 4476 return true; 4477 } 4478 4479 bool EnumDecl::isClosedFlag() const { 4480 return isClosed() && hasAttr<FlagEnumAttr>(); 4481 } 4482 4483 bool EnumDecl::isClosedNonFlag() const { 4484 return isClosed() && !hasAttr<FlagEnumAttr>(); 4485 } 4486 4487 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 4488 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 4489 return MSI->getTemplateSpecializationKind(); 4490 4491 return TSK_Undeclared; 4492 } 4493 4494 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4495 SourceLocation PointOfInstantiation) { 4496 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 4497 assert(MSI && "Not an instantiated member enumeration?"); 4498 MSI->setTemplateSpecializationKind(TSK); 4499 if (TSK != TSK_ExplicitSpecialization && 4500 PointOfInstantiation.isValid() && 4501 MSI->getPointOfInstantiation().isInvalid()) 4502 MSI->setPointOfInstantiation(PointOfInstantiation); 4503 } 4504 4505 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 4506 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 4507 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 4508 EnumDecl *ED = getInstantiatedFromMemberEnum(); 4509 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 4510 ED = NewED; 4511 return getDefinitionOrSelf(ED); 4512 } 4513 } 4514 4515 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 4516 "couldn't find pattern for enum instantiation"); 4517 return nullptr; 4518 } 4519 4520 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 4521 if (SpecializationInfo) 4522 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 4523 4524 return nullptr; 4525 } 4526 4527 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 4528 TemplateSpecializationKind TSK) { 4529 assert(!SpecializationInfo && "Member enum is already a specialization"); 4530 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 4531 } 4532 4533 unsigned EnumDecl::getODRHash() { 4534 if (hasODRHash()) 4535 return ODRHash; 4536 4537 class ODRHash Hash; 4538 Hash.AddEnumDecl(this); 4539 setHasODRHash(true); 4540 ODRHash = Hash.CalculateHash(); 4541 return ODRHash; 4542 } 4543 4544 SourceRange EnumDecl::getSourceRange() const { 4545 auto Res = TagDecl::getSourceRange(); 4546 // Set end-point to enum-base, e.g. enum foo : ^bar 4547 if (auto *TSI = getIntegerTypeSourceInfo()) { 4548 // TagDecl doesn't know about the enum base. 4549 if (!getBraceRange().getEnd().isValid()) 4550 Res.setEnd(TSI->getTypeLoc().getEndLoc()); 4551 } 4552 return Res; 4553 } 4554 4555 //===----------------------------------------------------------------------===// 4556 // RecordDecl Implementation 4557 //===----------------------------------------------------------------------===// 4558 4559 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 4560 DeclContext *DC, SourceLocation StartLoc, 4561 SourceLocation IdLoc, IdentifierInfo *Id, 4562 RecordDecl *PrevDecl) 4563 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4564 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!"); 4565 setHasFlexibleArrayMember(false); 4566 setAnonymousStructOrUnion(false); 4567 setHasObjectMember(false); 4568 setHasVolatileMember(false); 4569 setHasLoadedFieldsFromExternalStorage(false); 4570 setNonTrivialToPrimitiveDefaultInitialize(false); 4571 setNonTrivialToPrimitiveCopy(false); 4572 setNonTrivialToPrimitiveDestroy(false); 4573 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false); 4574 setHasNonTrivialToPrimitiveDestructCUnion(false); 4575 setHasNonTrivialToPrimitiveCopyCUnion(false); 4576 setParamDestroyedInCallee(false); 4577 setArgPassingRestrictions(APK_CanPassInRegs); 4578 } 4579 4580 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 4581 SourceLocation StartLoc, SourceLocation IdLoc, 4582 IdentifierInfo *Id, RecordDecl* PrevDecl) { 4583 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 4584 StartLoc, IdLoc, Id, PrevDecl); 4585 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4586 4587 C.getTypeDeclType(R, PrevDecl); 4588 return R; 4589 } 4590 4591 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 4592 RecordDecl *R = 4593 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), 4594 SourceLocation(), nullptr, nullptr); 4595 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4596 return R; 4597 } 4598 4599 bool RecordDecl::isInjectedClassName() const { 4600 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 4601 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 4602 } 4603 4604 bool RecordDecl::isLambda() const { 4605 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 4606 return RD->isLambda(); 4607 return false; 4608 } 4609 4610 bool RecordDecl::isCapturedRecord() const { 4611 return hasAttr<CapturedRecordAttr>(); 4612 } 4613 4614 void RecordDecl::setCapturedRecord() { 4615 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 4616 } 4617 4618 bool RecordDecl::isOrContainsUnion() const { 4619 if (isUnion()) 4620 return true; 4621 4622 if (const RecordDecl *Def = getDefinition()) { 4623 for (const FieldDecl *FD : Def->fields()) { 4624 const RecordType *RT = FD->getType()->getAs<RecordType>(); 4625 if (RT && RT->getDecl()->isOrContainsUnion()) 4626 return true; 4627 } 4628 } 4629 4630 return false; 4631 } 4632 4633 RecordDecl::field_iterator RecordDecl::field_begin() const { 4634 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage()) 4635 LoadFieldsFromExternalStorage(); 4636 4637 return field_iterator(decl_iterator(FirstDecl)); 4638 } 4639 4640 /// completeDefinition - Notes that the definition of this type is now 4641 /// complete. 4642 void RecordDecl::completeDefinition() { 4643 assert(!isCompleteDefinition() && "Cannot redefine record!"); 4644 TagDecl::completeDefinition(); 4645 4646 ASTContext &Ctx = getASTContext(); 4647 4648 // Layouts are dumped when computed, so if we are dumping for all complete 4649 // types, we need to force usage to get types that wouldn't be used elsewhere. 4650 if (Ctx.getLangOpts().DumpRecordLayoutsComplete) 4651 (void)Ctx.getASTRecordLayout(this); 4652 } 4653 4654 /// isMsStruct - Get whether or not this record uses ms_struct layout. 4655 /// This which can be turned on with an attribute, pragma, or the 4656 /// -mms-bitfields command-line option. 4657 bool RecordDecl::isMsStruct(const ASTContext &C) const { 4658 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 4659 } 4660 4661 void RecordDecl::LoadFieldsFromExternalStorage() const { 4662 ExternalASTSource *Source = getASTContext().getExternalSource(); 4663 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 4664 4665 // Notify that we have a RecordDecl doing some initialization. 4666 ExternalASTSource::Deserializing TheFields(Source); 4667 4668 SmallVector<Decl*, 64> Decls; 4669 setHasLoadedFieldsFromExternalStorage(true); 4670 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 4671 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 4672 }, Decls); 4673 4674 #ifndef NDEBUG 4675 // Check that all decls we got were FieldDecls. 4676 for (unsigned i=0, e=Decls.size(); i != e; ++i) 4677 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 4678 #endif 4679 4680 if (Decls.empty()) 4681 return; 4682 4683 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 4684 /*FieldsAlreadyLoaded=*/false); 4685 } 4686 4687 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 4688 ASTContext &Context = getASTContext(); 4689 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 4690 (SanitizerKind::Address | SanitizerKind::KernelAddress); 4691 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 4692 return false; 4693 const auto &NoSanitizeList = Context.getNoSanitizeList(); 4694 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 4695 // We may be able to relax some of these requirements. 4696 int ReasonToReject = -1; 4697 if (!CXXRD || CXXRD->isExternCContext()) 4698 ReasonToReject = 0; // is not C++. 4699 else if (CXXRD->hasAttr<PackedAttr>()) 4700 ReasonToReject = 1; // is packed. 4701 else if (CXXRD->isUnion()) 4702 ReasonToReject = 2; // is a union. 4703 else if (CXXRD->isTriviallyCopyable()) 4704 ReasonToReject = 3; // is trivially copyable. 4705 else if (CXXRD->hasTrivialDestructor()) 4706 ReasonToReject = 4; // has trivial destructor. 4707 else if (CXXRD->isStandardLayout()) 4708 ReasonToReject = 5; // is standard layout. 4709 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), 4710 "field-padding")) 4711 ReasonToReject = 6; // is in an excluded file. 4712 else if (NoSanitizeList.containsType( 4713 EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) 4714 ReasonToReject = 7; // The type is excluded. 4715 4716 if (EmitRemark) { 4717 if (ReasonToReject >= 0) 4718 Context.getDiagnostics().Report( 4719 getLocation(), 4720 diag::remark_sanitize_address_insert_extra_padding_rejected) 4721 << getQualifiedNameAsString() << ReasonToReject; 4722 else 4723 Context.getDiagnostics().Report( 4724 getLocation(), 4725 diag::remark_sanitize_address_insert_extra_padding_accepted) 4726 << getQualifiedNameAsString(); 4727 } 4728 return ReasonToReject < 0; 4729 } 4730 4731 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 4732 for (const auto *I : fields()) { 4733 if (I->getIdentifier()) 4734 return I; 4735 4736 if (const auto *RT = I->getType()->getAs<RecordType>()) 4737 if (const FieldDecl *NamedDataMember = 4738 RT->getDecl()->findFirstNamedDataMember()) 4739 return NamedDataMember; 4740 } 4741 4742 // We didn't find a named data member. 4743 return nullptr; 4744 } 4745 4746 //===----------------------------------------------------------------------===// 4747 // BlockDecl Implementation 4748 //===----------------------------------------------------------------------===// 4749 4750 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 4751 : Decl(Block, DC, CaretLoc), DeclContext(Block) { 4752 setIsVariadic(false); 4753 setCapturesCXXThis(false); 4754 setBlockMissingReturnType(true); 4755 setIsConversionFromLambda(false); 4756 setDoesNotEscape(false); 4757 setCanAvoidCopyToHeap(false); 4758 } 4759 4760 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 4761 assert(!ParamInfo && "Already has param info!"); 4762 4763 // Zero params -> null pointer. 4764 if (!NewParamInfo.empty()) { 4765 NumParams = NewParamInfo.size(); 4766 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 4767 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 4768 } 4769 } 4770 4771 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 4772 bool CapturesCXXThis) { 4773 this->setCapturesCXXThis(CapturesCXXThis); 4774 this->NumCaptures = Captures.size(); 4775 4776 if (Captures.empty()) { 4777 this->Captures = nullptr; 4778 return; 4779 } 4780 4781 this->Captures = Captures.copy(Context).data(); 4782 } 4783 4784 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 4785 for (const auto &I : captures()) 4786 // Only auto vars can be captured, so no redeclaration worries. 4787 if (I.getVariable() == variable) 4788 return true; 4789 4790 return false; 4791 } 4792 4793 SourceRange BlockDecl::getSourceRange() const { 4794 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation()); 4795 } 4796 4797 //===----------------------------------------------------------------------===// 4798 // Other Decl Allocation/Deallocation Method Implementations 4799 //===----------------------------------------------------------------------===// 4800 4801 void TranslationUnitDecl::anchor() {} 4802 4803 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 4804 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 4805 } 4806 4807 void PragmaCommentDecl::anchor() {} 4808 4809 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 4810 TranslationUnitDecl *DC, 4811 SourceLocation CommentLoc, 4812 PragmaMSCommentKind CommentKind, 4813 StringRef Arg) { 4814 PragmaCommentDecl *PCD = 4815 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 4816 PragmaCommentDecl(DC, CommentLoc, CommentKind); 4817 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 4818 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 4819 return PCD; 4820 } 4821 4822 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 4823 unsigned ID, 4824 unsigned ArgSize) { 4825 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 4826 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 4827 } 4828 4829 void PragmaDetectMismatchDecl::anchor() {} 4830 4831 PragmaDetectMismatchDecl * 4832 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 4833 SourceLocation Loc, StringRef Name, 4834 StringRef Value) { 4835 size_t ValueStart = Name.size() + 1; 4836 PragmaDetectMismatchDecl *PDMD = 4837 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 4838 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 4839 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 4840 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 4841 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 4842 Value.size()); 4843 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 4844 return PDMD; 4845 } 4846 4847 PragmaDetectMismatchDecl * 4848 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4849 unsigned NameValueSize) { 4850 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 4851 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 4852 } 4853 4854 void ExternCContextDecl::anchor() {} 4855 4856 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 4857 TranslationUnitDecl *DC) { 4858 return new (C, DC) ExternCContextDecl(DC); 4859 } 4860 4861 void LabelDecl::anchor() {} 4862 4863 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4864 SourceLocation IdentL, IdentifierInfo *II) { 4865 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 4866 } 4867 4868 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4869 SourceLocation IdentL, IdentifierInfo *II, 4870 SourceLocation GnuLabelL) { 4871 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 4872 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 4873 } 4874 4875 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4876 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 4877 SourceLocation()); 4878 } 4879 4880 void LabelDecl::setMSAsmLabel(StringRef Name) { 4881 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 4882 memcpy(Buffer, Name.data(), Name.size()); 4883 Buffer[Name.size()] = '\0'; 4884 MSAsmName = Buffer; 4885 } 4886 4887 void ValueDecl::anchor() {} 4888 4889 bool ValueDecl::isWeak() const { 4890 auto *MostRecent = getMostRecentDecl(); 4891 return MostRecent->hasAttr<WeakAttr>() || 4892 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported(); 4893 } 4894 4895 void ImplicitParamDecl::anchor() {} 4896 4897 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 4898 SourceLocation IdLoc, 4899 IdentifierInfo *Id, QualType Type, 4900 ImplicitParamKind ParamKind) { 4901 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 4902 } 4903 4904 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 4905 ImplicitParamKind ParamKind) { 4906 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 4907 } 4908 4909 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 4910 unsigned ID) { 4911 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 4912 } 4913 4914 FunctionDecl * 4915 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4916 const DeclarationNameInfo &NameInfo, QualType T, 4917 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 4918 bool isInlineSpecified, bool hasWrittenPrototype, 4919 ConstexprSpecKind ConstexprKind, 4920 Expr *TrailingRequiresClause) { 4921 FunctionDecl *New = new (C, DC) FunctionDecl( 4922 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 4923 isInlineSpecified, ConstexprKind, TrailingRequiresClause); 4924 New->setHasWrittenPrototype(hasWrittenPrototype); 4925 return New; 4926 } 4927 4928 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4929 return new (C, ID) FunctionDecl( 4930 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), 4931 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr); 4932 } 4933 4934 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4935 return new (C, DC) BlockDecl(DC, L); 4936 } 4937 4938 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4939 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 4940 } 4941 4942 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 4943 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 4944 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 4945 4946 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 4947 unsigned NumParams) { 4948 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4949 CapturedDecl(DC, NumParams); 4950 } 4951 4952 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4953 unsigned NumParams) { 4954 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 4955 CapturedDecl(nullptr, NumParams); 4956 } 4957 4958 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 4959 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 4960 4961 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 4962 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 4963 4964 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 4965 SourceLocation L, 4966 IdentifierInfo *Id, QualType T, 4967 Expr *E, const llvm::APSInt &V) { 4968 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 4969 } 4970 4971 EnumConstantDecl * 4972 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4973 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 4974 QualType(), nullptr, llvm::APSInt()); 4975 } 4976 4977 void IndirectFieldDecl::anchor() {} 4978 4979 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 4980 SourceLocation L, DeclarationName N, 4981 QualType T, 4982 MutableArrayRef<NamedDecl *> CH) 4983 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 4984 ChainingSize(CH.size()) { 4985 // In C++, indirect field declarations conflict with tag declarations in the 4986 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 4987 if (C.getLangOpts().CPlusPlus) 4988 IdentifierNamespace |= IDNS_Tag; 4989 } 4990 4991 IndirectFieldDecl * 4992 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 4993 IdentifierInfo *Id, QualType T, 4994 llvm::MutableArrayRef<NamedDecl *> CH) { 4995 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 4996 } 4997 4998 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 4999 unsigned ID) { 5000 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), 5001 DeclarationName(), QualType(), None); 5002 } 5003 5004 SourceRange EnumConstantDecl::getSourceRange() const { 5005 SourceLocation End = getLocation(); 5006 if (Init) 5007 End = Init->getEndLoc(); 5008 return SourceRange(getLocation(), End); 5009 } 5010 5011 void TypeDecl::anchor() {} 5012 5013 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 5014 SourceLocation StartLoc, SourceLocation IdLoc, 5015 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 5016 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5017 } 5018 5019 void TypedefNameDecl::anchor() {} 5020 5021 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 5022 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 5023 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 5024 auto *ThisTypedef = this; 5025 if (AnyRedecl && OwningTypedef) { 5026 OwningTypedef = OwningTypedef->getCanonicalDecl(); 5027 ThisTypedef = ThisTypedef->getCanonicalDecl(); 5028 } 5029 if (OwningTypedef == ThisTypedef) 5030 return TT->getDecl(); 5031 } 5032 5033 return nullptr; 5034 } 5035 5036 bool TypedefNameDecl::isTransparentTagSlow() const { 5037 auto determineIsTransparent = [&]() { 5038 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 5039 if (auto *TD = TT->getDecl()) { 5040 if (TD->getName() != getName()) 5041 return false; 5042 SourceLocation TTLoc = getLocation(); 5043 SourceLocation TDLoc = TD->getLocation(); 5044 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 5045 return false; 5046 SourceManager &SM = getASTContext().getSourceManager(); 5047 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 5048 } 5049 } 5050 return false; 5051 }; 5052 5053 bool isTransparent = determineIsTransparent(); 5054 MaybeModedTInfo.setInt((isTransparent << 1) | 1); 5055 return isTransparent; 5056 } 5057 5058 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5059 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 5060 nullptr, nullptr); 5061 } 5062 5063 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 5064 SourceLocation StartLoc, 5065 SourceLocation IdLoc, IdentifierInfo *Id, 5066 TypeSourceInfo *TInfo) { 5067 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5068 } 5069 5070 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5071 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 5072 SourceLocation(), nullptr, nullptr); 5073 } 5074 5075 SourceRange TypedefDecl::getSourceRange() const { 5076 SourceLocation RangeEnd = getLocation(); 5077 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 5078 if (typeIsPostfix(TInfo->getType())) 5079 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5080 } 5081 return SourceRange(getBeginLoc(), RangeEnd); 5082 } 5083 5084 SourceRange TypeAliasDecl::getSourceRange() const { 5085 SourceLocation RangeEnd = getBeginLoc(); 5086 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 5087 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5088 return SourceRange(getBeginLoc(), RangeEnd); 5089 } 5090 5091 void FileScopeAsmDecl::anchor() {} 5092 5093 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 5094 StringLiteral *Str, 5095 SourceLocation AsmLoc, 5096 SourceLocation RParenLoc) { 5097 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 5098 } 5099 5100 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 5101 unsigned ID) { 5102 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 5103 SourceLocation()); 5104 } 5105 5106 void EmptyDecl::anchor() {} 5107 5108 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5109 return new (C, DC) EmptyDecl(DC, L); 5110 } 5111 5112 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5113 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 5114 } 5115 5116 //===----------------------------------------------------------------------===// 5117 // ImportDecl Implementation 5118 //===----------------------------------------------------------------------===// 5119 5120 /// Retrieve the number of module identifiers needed to name the given 5121 /// module. 5122 static unsigned getNumModuleIdentifiers(Module *Mod) { 5123 unsigned Result = 1; 5124 while (Mod->Parent) { 5125 Mod = Mod->Parent; 5126 ++Result; 5127 } 5128 return Result; 5129 } 5130 5131 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5132 Module *Imported, 5133 ArrayRef<SourceLocation> IdentifierLocs) 5134 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5135 NextLocalImportAndComplete(nullptr, true) { 5136 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 5137 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5138 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 5139 StoredLocs); 5140 } 5141 5142 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5143 Module *Imported, SourceLocation EndLoc) 5144 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5145 NextLocalImportAndComplete(nullptr, false) { 5146 *getTrailingObjects<SourceLocation>() = EndLoc; 5147 } 5148 5149 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 5150 SourceLocation StartLoc, Module *Imported, 5151 ArrayRef<SourceLocation> IdentifierLocs) { 5152 return new (C, DC, 5153 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 5154 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 5155 } 5156 5157 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 5158 SourceLocation StartLoc, 5159 Module *Imported, 5160 SourceLocation EndLoc) { 5161 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 5162 ImportDecl(DC, StartLoc, Imported, EndLoc); 5163 Import->setImplicit(); 5164 return Import; 5165 } 5166 5167 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5168 unsigned NumLocations) { 5169 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 5170 ImportDecl(EmptyShell()); 5171 } 5172 5173 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 5174 if (!isImportComplete()) 5175 return None; 5176 5177 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5178 return llvm::makeArrayRef(StoredLocs, 5179 getNumModuleIdentifiers(getImportedModule())); 5180 } 5181 5182 SourceRange ImportDecl::getSourceRange() const { 5183 if (!isImportComplete()) 5184 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 5185 5186 return SourceRange(getLocation(), getIdentifierLocs().back()); 5187 } 5188 5189 //===----------------------------------------------------------------------===// 5190 // ExportDecl Implementation 5191 //===----------------------------------------------------------------------===// 5192 5193 void ExportDecl::anchor() {} 5194 5195 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 5196 SourceLocation ExportLoc) { 5197 return new (C, DC) ExportDecl(DC, ExportLoc); 5198 } 5199 5200 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5201 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 5202 } 5203