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