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