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 evaluateValue(Notes); 2457 } 2458 2459 APValue *VarDecl::evaluateValue( 2460 SmallVectorImpl<PartialDiagnosticAt> &Notes) 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 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 2480 this, Notes); 2481 2482 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2483 // or that it's empty (so that there's nothing to clean up) if evaluation 2484 // failed. 2485 if (!Result) 2486 Eval->Evaluated = APValue(); 2487 else if (Eval->Evaluated.needsCleanup()) 2488 getASTContext().addDestruction(&Eval->Evaluated); 2489 2490 Eval->IsEvaluating = false; 2491 Eval->WasEvaluated = true; 2492 2493 return Result ? &Eval->Evaluated : nullptr; 2494 } 2495 2496 APValue *VarDecl::getEvaluatedValue() const { 2497 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2498 if (Eval->WasEvaluated) 2499 return &Eval->Evaluated; 2500 2501 return nullptr; 2502 } 2503 2504 bool VarDecl::hasICEInitializer(const ASTContext &Context) const { 2505 const Expr *Init = getInit(); 2506 assert(Init && "no initializer"); 2507 2508 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2509 if (!Eval->CheckedForICEInit) { 2510 Eval->CheckedForICEInit = true; 2511 Eval->HasICEInit = Init->isIntegerConstantExpr(Context); 2512 } 2513 return Eval->HasICEInit; 2514 } 2515 2516 bool VarDecl::hasConstantInitialization() const { 2517 // In C, all globals (and only globals) have constant initialization. 2518 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus) 2519 return true; 2520 2521 // In C++, it depends on whether the evaluation at the point of definition 2522 // was evaluatable as a constant initializer. 2523 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2524 return Eval->HasConstantInitialization; 2525 2526 return false; 2527 } 2528 2529 bool VarDecl::checkForConstantInitialization( 2530 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2531 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2532 // If we ask for the value before we know whether we have a constant 2533 // initializer, we can compute the wrong value (for example, due to 2534 // std::is_constant_evaluated()). 2535 assert(!Eval->WasEvaluated && 2536 "already evaluated var value before checking for constant init"); 2537 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++"); 2538 2539 assert(!cast<Expr>(Eval->Value)->isValueDependent()); 2540 2541 // Evaluate the initializer to check whether it's a constant expression. 2542 Eval->HasConstantInitialization = evaluateValue(Notes) && Notes.empty(); 2543 return Eval->HasConstantInitialization; 2544 } 2545 2546 bool VarDecl::isParameterPack() const { 2547 return isa<PackExpansionType>(getType()); 2548 } 2549 2550 template<typename DeclT> 2551 static DeclT *getDefinitionOrSelf(DeclT *D) { 2552 assert(D); 2553 if (auto *Def = D->getDefinition()) 2554 return Def; 2555 return D; 2556 } 2557 2558 bool VarDecl::isEscapingByref() const { 2559 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref; 2560 } 2561 2562 bool VarDecl::isNonEscapingByref() const { 2563 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref; 2564 } 2565 2566 bool VarDecl::hasDependentAlignment() const { 2567 QualType T = getType(); 2568 return T->isDependentType() || T->isUndeducedAutoType() || 2569 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) { 2570 return AA->isAlignmentDependent(); 2571 }); 2572 } 2573 2574 VarDecl *VarDecl::getTemplateInstantiationPattern() const { 2575 const VarDecl *VD = this; 2576 2577 // If this is an instantiated member, walk back to the template from which 2578 // it was instantiated. 2579 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) { 2580 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 2581 VD = VD->getInstantiatedFromStaticDataMember(); 2582 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember()) 2583 VD = NewVD; 2584 } 2585 } 2586 2587 // If it's an instantiated variable template specialization, find the 2588 // template or partial specialization from which it was instantiated. 2589 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 2590 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) { 2591 auto From = VDTemplSpec->getInstantiatedFrom(); 2592 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) { 2593 while (!VTD->isMemberSpecialization()) { 2594 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate(); 2595 if (!NewVTD) 2596 break; 2597 VTD = NewVTD; 2598 } 2599 return getDefinitionOrSelf(VTD->getTemplatedDecl()); 2600 } 2601 if (auto *VTPSD = 2602 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 2603 while (!VTPSD->isMemberSpecialization()) { 2604 auto *NewVTPSD = VTPSD->getInstantiatedFromMember(); 2605 if (!NewVTPSD) 2606 break; 2607 VTPSD = NewVTPSD; 2608 } 2609 return getDefinitionOrSelf<VarDecl>(VTPSD); 2610 } 2611 } 2612 } 2613 2614 // If this is the pattern of a variable template, find where it was 2615 // instantiated from. FIXME: Is this necessary? 2616 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) { 2617 while (!VarTemplate->isMemberSpecialization()) { 2618 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate(); 2619 if (!NewVT) 2620 break; 2621 VarTemplate = NewVT; 2622 } 2623 2624 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl()); 2625 } 2626 2627 if (VD == this) 2628 return nullptr; 2629 return getDefinitionOrSelf(const_cast<VarDecl*>(VD)); 2630 } 2631 2632 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2633 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2634 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2635 2636 return nullptr; 2637 } 2638 2639 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2640 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2641 return Spec->getSpecializationKind(); 2642 2643 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2644 return MSI->getTemplateSpecializationKind(); 2645 2646 return TSK_Undeclared; 2647 } 2648 2649 TemplateSpecializationKind 2650 VarDecl::getTemplateSpecializationKindForInstantiation() const { 2651 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2652 return MSI->getTemplateSpecializationKind(); 2653 2654 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2655 return Spec->getSpecializationKind(); 2656 2657 return TSK_Undeclared; 2658 } 2659 2660 SourceLocation VarDecl::getPointOfInstantiation() const { 2661 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this)) 2662 return Spec->getPointOfInstantiation(); 2663 2664 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2665 return MSI->getPointOfInstantiation(); 2666 2667 return SourceLocation(); 2668 } 2669 2670 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2671 return getASTContext().getTemplateOrSpecializationInfo(this) 2672 .dyn_cast<VarTemplateDecl *>(); 2673 } 2674 2675 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2676 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2677 } 2678 2679 bool VarDecl::isKnownToBeDefined() const { 2680 const auto &LangOpts = getASTContext().getLangOpts(); 2681 // In CUDA mode without relocatable device code, variables of form 'extern 2682 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared 2683 // memory pool. These are never undefined variables, even if they appear 2684 // inside of an anon namespace or static function. 2685 // 2686 // With CUDA relocatable device code enabled, these variables don't get 2687 // special handling; they're treated like regular extern variables. 2688 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode && 2689 hasExternalStorage() && hasAttr<CUDASharedAttr>() && 2690 isa<IncompleteArrayType>(getType())) 2691 return true; 2692 2693 return hasDefinition(); 2694 } 2695 2696 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { 2697 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() || 2698 (!Ctx.getLangOpts().RegisterStaticDestructors && 2699 !hasAttr<AlwaysDestroyAttr>())); 2700 } 2701 2702 QualType::DestructionKind 2703 VarDecl::needsDestruction(const ASTContext &Ctx) const { 2704 if (EvaluatedStmt *Eval = getEvaluatedStmt()) 2705 if (Eval->HasConstantDestruction) 2706 return QualType::DK_none; 2707 2708 if (isNoDestroy(Ctx)) 2709 return QualType::DK_none; 2710 2711 return getType().isDestructedType(); 2712 } 2713 2714 bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const { 2715 assert(hasInit() && "Expect initializer to check for flexible array init"); 2716 auto *Ty = getType()->getAs<RecordType>(); 2717 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember()) 2718 return false; 2719 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2720 if (!List) 2721 return false; 2722 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2723 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2724 if (!InitTy) 2725 return false; 2726 return InitTy->getSize() != 0; 2727 } 2728 2729 CharUnits VarDecl::getFlexibleArrayInitChars(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 CharUnits::Zero(); 2734 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens()); 2735 if (!List) 2736 return CharUnits::Zero(); 2737 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1); 2738 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType()); 2739 if (!InitTy) 2740 return CharUnits::Zero(); 2741 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy); 2742 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl()); 2743 CharUnits FlexibleArrayOffset = 2744 Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1)); 2745 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize()) 2746 return CharUnits::Zero(); 2747 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize(); 2748 } 2749 2750 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2751 if (isStaticDataMember()) 2752 // FIXME: Remove ? 2753 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2754 return getASTContext().getTemplateOrSpecializationInfo(this) 2755 .dyn_cast<MemberSpecializationInfo *>(); 2756 return nullptr; 2757 } 2758 2759 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2760 SourceLocation PointOfInstantiation) { 2761 assert((isa<VarTemplateSpecializationDecl>(this) || 2762 getMemberSpecializationInfo()) && 2763 "not a variable or static data member template specialization"); 2764 2765 if (VarTemplateSpecializationDecl *Spec = 2766 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2767 Spec->setSpecializationKind(TSK); 2768 if (TSK != TSK_ExplicitSpecialization && 2769 PointOfInstantiation.isValid() && 2770 Spec->getPointOfInstantiation().isInvalid()) { 2771 Spec->setPointOfInstantiation(PointOfInstantiation); 2772 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2773 L->InstantiationRequested(this); 2774 } 2775 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2776 MSI->setTemplateSpecializationKind(TSK); 2777 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2778 MSI->getPointOfInstantiation().isInvalid()) { 2779 MSI->setPointOfInstantiation(PointOfInstantiation); 2780 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 2781 L->InstantiationRequested(this); 2782 } 2783 } 2784 } 2785 2786 void 2787 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2788 TemplateSpecializationKind TSK) { 2789 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2790 "Previous template or instantiation?"); 2791 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2792 } 2793 2794 //===----------------------------------------------------------------------===// 2795 // ParmVarDecl Implementation 2796 //===----------------------------------------------------------------------===// 2797 2798 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2799 SourceLocation StartLoc, 2800 SourceLocation IdLoc, IdentifierInfo *Id, 2801 QualType T, TypeSourceInfo *TInfo, 2802 StorageClass S, Expr *DefArg) { 2803 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2804 S, DefArg); 2805 } 2806 2807 QualType ParmVarDecl::getOriginalType() const { 2808 TypeSourceInfo *TSI = getTypeSourceInfo(); 2809 QualType T = TSI ? TSI->getType() : getType(); 2810 if (const auto *DT = dyn_cast<DecayedType>(T)) 2811 return DT->getOriginalType(); 2812 return T; 2813 } 2814 2815 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2816 return new (C, ID) 2817 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2818 nullptr, QualType(), nullptr, SC_None, nullptr); 2819 } 2820 2821 SourceRange ParmVarDecl::getSourceRange() const { 2822 if (!hasInheritedDefaultArg()) { 2823 SourceRange ArgRange = getDefaultArgRange(); 2824 if (ArgRange.isValid()) 2825 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2826 } 2827 2828 // DeclaratorDecl considers the range of postfix types as overlapping with the 2829 // declaration name, but this is not the case with parameters in ObjC methods. 2830 if (isa<ObjCMethodDecl>(getDeclContext())) 2831 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation()); 2832 2833 return DeclaratorDecl::getSourceRange(); 2834 } 2835 2836 bool ParmVarDecl::isDestroyedInCallee() const { 2837 // ns_consumed only affects code generation in ARC 2838 if (hasAttr<NSConsumedAttr>()) 2839 return getASTContext().getLangOpts().ObjCAutoRefCount; 2840 2841 // FIXME: isParamDestroyedInCallee() should probably imply 2842 // isDestructedType() 2843 auto *RT = getType()->getAs<RecordType>(); 2844 if (RT && RT->getDecl()->isParamDestroyedInCallee() && 2845 getType().isDestructedType()) 2846 return true; 2847 2848 return false; 2849 } 2850 2851 Expr *ParmVarDecl::getDefaultArg() { 2852 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2853 assert(!hasUninstantiatedDefaultArg() && 2854 "Default argument is not yet instantiated!"); 2855 2856 Expr *Arg = getInit(); 2857 if (auto *E = dyn_cast_or_null<FullExpr>(Arg)) 2858 if (!isa<ConstantExpr>(E)) 2859 return E->getSubExpr(); 2860 2861 return Arg; 2862 } 2863 2864 void ParmVarDecl::setDefaultArg(Expr *defarg) { 2865 ParmVarDeclBits.DefaultArgKind = DAK_Normal; 2866 Init = defarg; 2867 } 2868 2869 SourceRange ParmVarDecl::getDefaultArgRange() const { 2870 switch (ParmVarDeclBits.DefaultArgKind) { 2871 case DAK_None: 2872 case DAK_Unparsed: 2873 // Nothing we can do here. 2874 return SourceRange(); 2875 2876 case DAK_Uninstantiated: 2877 return getUninstantiatedDefaultArg()->getSourceRange(); 2878 2879 case DAK_Normal: 2880 if (const Expr *E = getInit()) 2881 return E->getSourceRange(); 2882 2883 // Missing an actual expression, may be invalid. 2884 return SourceRange(); 2885 } 2886 llvm_unreachable("Invalid default argument kind."); 2887 } 2888 2889 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) { 2890 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated; 2891 Init = arg; 2892 } 2893 2894 Expr *ParmVarDecl::getUninstantiatedDefaultArg() { 2895 assert(hasUninstantiatedDefaultArg() && 2896 "Wrong kind of initialization expression!"); 2897 return cast_or_null<Expr>(Init.get<Stmt *>()); 2898 } 2899 2900 bool ParmVarDecl::hasDefaultArg() const { 2901 // FIXME: We should just return false for DAK_None here once callers are 2902 // prepared for the case that we encountered an invalid default argument and 2903 // were unable to even build an invalid expression. 2904 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() || 2905 !Init.isNull(); 2906 } 2907 2908 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 2909 getASTContext().setParameterIndex(this, parameterIndex); 2910 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 2911 } 2912 2913 unsigned ParmVarDecl::getParameterIndexLarge() const { 2914 return getASTContext().getParameterIndex(this); 2915 } 2916 2917 //===----------------------------------------------------------------------===// 2918 // FunctionDecl Implementation 2919 //===----------------------------------------------------------------------===// 2920 2921 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, 2922 SourceLocation StartLoc, 2923 const DeclarationNameInfo &NameInfo, QualType T, 2924 TypeSourceInfo *TInfo, StorageClass S, 2925 bool UsesFPIntrin, bool isInlineSpecified, 2926 ConstexprSpecKind ConstexprKind, 2927 Expr *TrailingRequiresClause) 2928 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 2929 StartLoc), 2930 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0), 2931 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) { 2932 assert(T.isNull() || T->isFunctionType()); 2933 FunctionDeclBits.SClass = S; 2934 FunctionDeclBits.IsInline = isInlineSpecified; 2935 FunctionDeclBits.IsInlineSpecified = isInlineSpecified; 2936 FunctionDeclBits.IsVirtualAsWritten = false; 2937 FunctionDeclBits.IsPure = false; 2938 FunctionDeclBits.HasInheritedPrototype = false; 2939 FunctionDeclBits.HasWrittenPrototype = true; 2940 FunctionDeclBits.IsDeleted = false; 2941 FunctionDeclBits.IsTrivial = false; 2942 FunctionDeclBits.IsTrivialForCall = false; 2943 FunctionDeclBits.IsDefaulted = false; 2944 FunctionDeclBits.IsExplicitlyDefaulted = false; 2945 FunctionDeclBits.HasDefaultedFunctionInfo = false; 2946 FunctionDeclBits.IsIneligibleOrNotSelected = false; 2947 FunctionDeclBits.HasImplicitReturnZero = false; 2948 FunctionDeclBits.IsLateTemplateParsed = false; 2949 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind); 2950 FunctionDeclBits.InstantiationIsPending = false; 2951 FunctionDeclBits.UsesSEHTry = false; 2952 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin; 2953 FunctionDeclBits.HasSkippedBody = false; 2954 FunctionDeclBits.WillHaveBody = false; 2955 FunctionDeclBits.IsMultiVersion = false; 2956 FunctionDeclBits.IsCopyDeductionCandidate = false; 2957 FunctionDeclBits.HasODRHash = false; 2958 if (TrailingRequiresClause) 2959 setTrailingRequiresClause(TrailingRequiresClause); 2960 } 2961 2962 void FunctionDecl::getNameForDiagnostic( 2963 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 2964 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 2965 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 2966 if (TemplateArgs) 2967 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); 2968 } 2969 2970 bool FunctionDecl::isVariadic() const { 2971 if (const auto *FT = getType()->getAs<FunctionProtoType>()) 2972 return FT->isVariadic(); 2973 return false; 2974 } 2975 2976 FunctionDecl::DefaultedFunctionInfo * 2977 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context, 2978 ArrayRef<DeclAccessPair> Lookups) { 2979 DefaultedFunctionInfo *Info = new (Context.Allocate( 2980 totalSizeToAlloc<DeclAccessPair>(Lookups.size()), 2981 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair)))) 2982 DefaultedFunctionInfo; 2983 Info->NumLookups = Lookups.size(); 2984 std::uninitialized_copy(Lookups.begin(), Lookups.end(), 2985 Info->getTrailingObjects<DeclAccessPair>()); 2986 return Info; 2987 } 2988 2989 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) { 2990 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this"); 2991 assert(!Body && "can't replace function body with defaulted function info"); 2992 2993 FunctionDeclBits.HasDefaultedFunctionInfo = true; 2994 DefaultedInfo = Info; 2995 } 2996 2997 FunctionDecl::DefaultedFunctionInfo * 2998 FunctionDecl::getDefaultedFunctionInfo() const { 2999 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr; 3000 } 3001 3002 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 3003 for (auto I : redecls()) { 3004 if (I->doesThisDeclarationHaveABody()) { 3005 Definition = I; 3006 return true; 3007 } 3008 } 3009 3010 return false; 3011 } 3012 3013 bool FunctionDecl::hasTrivialBody() const { 3014 Stmt *S = getBody(); 3015 if (!S) { 3016 // Since we don't have a body for this function, we don't know if it's 3017 // trivial or not. 3018 return false; 3019 } 3020 3021 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 3022 return true; 3023 return false; 3024 } 3025 3026 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const { 3027 if (!getFriendObjectKind()) 3028 return false; 3029 3030 // Check for a friend function instantiated from a friend function 3031 // definition in a templated class. 3032 if (const FunctionDecl *InstantiatedFrom = 3033 getInstantiatedFromMemberFunction()) 3034 return InstantiatedFrom->getFriendObjectKind() && 3035 InstantiatedFrom->isThisDeclarationADefinition(); 3036 3037 // Check for a friend function template instantiated from a friend 3038 // function template definition in a templated class. 3039 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { 3040 if (const FunctionTemplateDecl *InstantiatedFrom = 3041 Template->getInstantiatedFromMemberTemplate()) 3042 return InstantiatedFrom->getFriendObjectKind() && 3043 InstantiatedFrom->isThisDeclarationADefinition(); 3044 } 3045 3046 return false; 3047 } 3048 3049 bool FunctionDecl::isDefined(const FunctionDecl *&Definition, 3050 bool CheckForPendingFriendDefinition) const { 3051 for (const FunctionDecl *FD : redecls()) { 3052 if (FD->isThisDeclarationADefinition()) { 3053 Definition = FD; 3054 return true; 3055 } 3056 3057 // If this is a friend function defined in a class template, it does not 3058 // have a body until it is used, nevertheless it is a definition, see 3059 // [temp.inst]p2: 3060 // 3061 // ... for the purpose of determining whether an instantiated redeclaration 3062 // is valid according to [basic.def.odr] and [class.mem], a declaration that 3063 // corresponds to a definition in the template is considered to be a 3064 // definition. 3065 // 3066 // The following code must produce redefinition error: 3067 // 3068 // template<typename T> struct C20 { friend void func_20() {} }; 3069 // C20<int> c20i; 3070 // void func_20() {} 3071 // 3072 if (CheckForPendingFriendDefinition && 3073 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 3074 Definition = FD; 3075 return true; 3076 } 3077 } 3078 3079 return false; 3080 } 3081 3082 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 3083 if (!hasBody(Definition)) 3084 return nullptr; 3085 3086 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo && 3087 "definition should not have a body"); 3088 if (Definition->Body) 3089 return Definition->Body.get(getASTContext().getExternalSource()); 3090 3091 return nullptr; 3092 } 3093 3094 void FunctionDecl::setBody(Stmt *B) { 3095 FunctionDeclBits.HasDefaultedFunctionInfo = false; 3096 Body = LazyDeclStmtPtr(B); 3097 if (B) 3098 EndRangeLoc = B->getEndLoc(); 3099 } 3100 3101 void FunctionDecl::setPure(bool P) { 3102 FunctionDeclBits.IsPure = P; 3103 if (P) 3104 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 3105 Parent->markedVirtualFunctionPure(); 3106 } 3107 3108 template<std::size_t Len> 3109 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 3110 IdentifierInfo *II = ND->getIdentifier(); 3111 return II && II->isStr(Str); 3112 } 3113 3114 bool FunctionDecl::isMain() const { 3115 const TranslationUnitDecl *tunit = 3116 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3117 return tunit && 3118 !tunit->getASTContext().getLangOpts().Freestanding && 3119 isNamed(this, "main"); 3120 } 3121 3122 bool FunctionDecl::isMSVCRTEntryPoint() const { 3123 const TranslationUnitDecl *TUnit = 3124 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 3125 if (!TUnit) 3126 return false; 3127 3128 // Even though we aren't really targeting MSVCRT if we are freestanding, 3129 // semantic analysis for these functions remains the same. 3130 3131 // MSVCRT entry points only exist on MSVCRT targets. 3132 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 3133 return false; 3134 3135 // Nameless functions like constructors cannot be entry points. 3136 if (!getIdentifier()) 3137 return false; 3138 3139 return llvm::StringSwitch<bool>(getName()) 3140 .Cases("main", // an ANSI console app 3141 "wmain", // a Unicode console App 3142 "WinMain", // an ANSI GUI app 3143 "wWinMain", // a Unicode GUI app 3144 "DllMain", // a DLL 3145 true) 3146 .Default(false); 3147 } 3148 3149 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 3150 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 3151 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 3152 getDeclName().getCXXOverloadedOperator() == OO_Delete || 3153 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 3154 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 3155 3156 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3157 return false; 3158 3159 const auto *proto = getType()->castAs<FunctionProtoType>(); 3160 if (proto->getNumParams() != 2 || proto->isVariadic()) 3161 return false; 3162 3163 ASTContext &Context = 3164 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 3165 ->getASTContext(); 3166 3167 // The result type and first argument type are constant across all 3168 // these operators. The second argument must be exactly void*. 3169 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 3170 } 3171 3172 bool FunctionDecl::isReplaceableGlobalAllocationFunction( 3173 Optional<unsigned> *AlignmentParam, bool *IsNothrow) const { 3174 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 3175 return false; 3176 if (getDeclName().getCXXOverloadedOperator() != OO_New && 3177 getDeclName().getCXXOverloadedOperator() != OO_Delete && 3178 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 3179 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 3180 return false; 3181 3182 if (isa<CXXRecordDecl>(getDeclContext())) 3183 return false; 3184 3185 // This can only fail for an invalid 'operator new' declaration. 3186 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 3187 return false; 3188 3189 const auto *FPT = getType()->castAs<FunctionProtoType>(); 3190 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic()) 3191 return false; 3192 3193 // If this is a single-parameter function, it must be a replaceable global 3194 // allocation or deallocation function. 3195 if (FPT->getNumParams() == 1) 3196 return true; 3197 3198 unsigned Params = 1; 3199 QualType Ty = FPT->getParamType(Params); 3200 ASTContext &Ctx = getASTContext(); 3201 3202 auto Consume = [&] { 3203 ++Params; 3204 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType(); 3205 }; 3206 3207 // In C++14, the next parameter can be a 'std::size_t' for sized delete. 3208 bool IsSizedDelete = false; 3209 if (Ctx.getLangOpts().SizedDeallocation && 3210 (getDeclName().getCXXOverloadedOperator() == OO_Delete || 3211 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) && 3212 Ctx.hasSameType(Ty, Ctx.getSizeType())) { 3213 IsSizedDelete = true; 3214 Consume(); 3215 } 3216 3217 // In C++17, the next parameter can be a 'std::align_val_t' for aligned 3218 // new/delete. 3219 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { 3220 Consume(); 3221 if (AlignmentParam) 3222 *AlignmentParam = Params; 3223 } 3224 3225 // Finally, if this is not a sized delete, the final parameter can 3226 // be a 'const std::nothrow_t&'. 3227 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) { 3228 Ty = Ty->getPointeeType(); 3229 if (Ty.getCVRQualifiers() != Qualifiers::Const) 3230 return false; 3231 if (Ty->isNothrowT()) { 3232 if (IsNothrow) 3233 *IsNothrow = true; 3234 Consume(); 3235 } 3236 } 3237 3238 return Params == FPT->getNumParams(); 3239 } 3240 3241 bool FunctionDecl::isInlineBuiltinDeclaration() const { 3242 if (!getBuiltinID()) 3243 return false; 3244 3245 const FunctionDecl *Definition; 3246 return hasBody(Definition) && Definition->isInlineSpecified() && 3247 Definition->hasAttr<AlwaysInlineAttr>() && 3248 Definition->hasAttr<GNUInlineAttr>(); 3249 } 3250 3251 bool FunctionDecl::isDestroyingOperatorDelete() const { 3252 // C++ P0722: 3253 // Within a class C, a single object deallocation function with signature 3254 // (T, std::destroying_delete_t, <more params>) 3255 // is a destroying operator delete. 3256 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete || 3257 getNumParams() < 2) 3258 return false; 3259 3260 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl(); 3261 return RD && RD->isInStdNamespace() && RD->getIdentifier() && 3262 RD->getIdentifier()->isStr("destroying_delete_t"); 3263 } 3264 3265 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 3266 return getDeclLanguageLinkage(*this); 3267 } 3268 3269 bool FunctionDecl::isExternC() const { 3270 return isDeclExternC(*this); 3271 } 3272 3273 bool FunctionDecl::isInExternCContext() const { 3274 if (hasAttr<OpenCLKernelAttr>()) 3275 return true; 3276 return getLexicalDeclContext()->isExternCContext(); 3277 } 3278 3279 bool FunctionDecl::isInExternCXXContext() const { 3280 return getLexicalDeclContext()->isExternCXXContext(); 3281 } 3282 3283 bool FunctionDecl::isGlobal() const { 3284 if (const auto *Method = dyn_cast<CXXMethodDecl>(this)) 3285 return Method->isStatic(); 3286 3287 if (getCanonicalDecl()->getStorageClass() == SC_Static) 3288 return false; 3289 3290 for (const DeclContext *DC = getDeclContext(); 3291 DC->isNamespace(); 3292 DC = DC->getParent()) { 3293 if (const auto *Namespace = cast<NamespaceDecl>(DC)) { 3294 if (!Namespace->getDeclName()) 3295 return false; 3296 } 3297 } 3298 3299 return true; 3300 } 3301 3302 bool FunctionDecl::isNoReturn() const { 3303 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 3304 hasAttr<C11NoReturnAttr>()) 3305 return true; 3306 3307 if (auto *FnTy = getType()->getAs<FunctionType>()) 3308 return FnTy->getNoReturnAttr(); 3309 3310 return false; 3311 } 3312 3313 3314 MultiVersionKind FunctionDecl::getMultiVersionKind() const { 3315 if (hasAttr<TargetAttr>()) 3316 return MultiVersionKind::Target; 3317 if (hasAttr<CPUDispatchAttr>()) 3318 return MultiVersionKind::CPUDispatch; 3319 if (hasAttr<CPUSpecificAttr>()) 3320 return MultiVersionKind::CPUSpecific; 3321 if (hasAttr<TargetClonesAttr>()) 3322 return MultiVersionKind::TargetClones; 3323 return MultiVersionKind::None; 3324 } 3325 3326 bool FunctionDecl::isCPUDispatchMultiVersion() const { 3327 return isMultiVersion() && hasAttr<CPUDispatchAttr>(); 3328 } 3329 3330 bool FunctionDecl::isCPUSpecificMultiVersion() const { 3331 return isMultiVersion() && hasAttr<CPUSpecificAttr>(); 3332 } 3333 3334 bool FunctionDecl::isTargetMultiVersion() const { 3335 return isMultiVersion() && hasAttr<TargetAttr>(); 3336 } 3337 3338 bool FunctionDecl::isTargetClonesMultiVersion() const { 3339 return isMultiVersion() && hasAttr<TargetClonesAttr>(); 3340 } 3341 3342 void 3343 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 3344 redeclarable_base::setPreviousDecl(PrevDecl); 3345 3346 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 3347 FunctionTemplateDecl *PrevFunTmpl 3348 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 3349 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 3350 FunTmpl->setPreviousDecl(PrevFunTmpl); 3351 } 3352 3353 if (PrevDecl && PrevDecl->isInlined()) 3354 setImplicitlyInline(true); 3355 } 3356 3357 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 3358 3359 /// Returns a value indicating whether this function corresponds to a builtin 3360 /// function. 3361 /// 3362 /// The function corresponds to a built-in function if it is declared at 3363 /// translation scope or within an extern "C" block and its name matches with 3364 /// the name of a builtin. The returned value will be 0 for functions that do 3365 /// not correspond to a builtin, a value of type \c Builtin::ID if in the 3366 /// target-independent range \c [1,Builtin::First), or a target-specific builtin 3367 /// value. 3368 /// 3369 /// \param ConsiderWrapperFunctions If true, we should consider wrapper 3370 /// functions as their wrapped builtins. This shouldn't be done in general, but 3371 /// it's useful in Sema to diagnose calls to wrappers based on their semantics. 3372 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { 3373 unsigned BuiltinID = 0; 3374 3375 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) { 3376 BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); 3377 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) { 3378 BuiltinID = BAA->getBuiltinName()->getBuiltinID(); 3379 } else if (const auto *A = getAttr<BuiltinAttr>()) { 3380 BuiltinID = A->getID(); 3381 } 3382 3383 if (!BuiltinID) 3384 return 0; 3385 3386 // If the function is marked "overloadable", it has a different mangled name 3387 // and is not the C library function. 3388 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() && 3389 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>())) 3390 return 0; 3391 3392 ASTContext &Context = getASTContext(); 3393 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3394 return BuiltinID; 3395 3396 // This function has the name of a known C library 3397 // function. Determine whether it actually refers to the C library 3398 // function or whether it just has the same name. 3399 3400 // If this is a static function, it's not a builtin. 3401 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static) 3402 return 0; 3403 3404 // OpenCL v1.2 s6.9.f - The library functions defined in 3405 // the C99 standard headers are not available. 3406 if (Context.getLangOpts().OpenCL && 3407 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 3408 return 0; 3409 3410 // CUDA does not have device-side standard library. printf and malloc are the 3411 // only special cases that are supported by device-side runtime. 3412 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() && 3413 !hasAttr<CUDAHostAttr>() && 3414 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3415 return 0; 3416 3417 // As AMDGCN implementation of OpenMP does not have a device-side standard 3418 // library, none of the predefined library functions except printf and malloc 3419 // should be treated as a builtin i.e. 0 should be returned for them. 3420 if (Context.getTargetInfo().getTriple().isAMDGCN() && 3421 Context.getLangOpts().OpenMPIsDevice && 3422 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 3423 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc)) 3424 return 0; 3425 3426 return BuiltinID; 3427 } 3428 3429 /// getNumParams - Return the number of parameters this function must have 3430 /// based on its FunctionType. This is the length of the ParamInfo array 3431 /// after it has been created. 3432 unsigned FunctionDecl::getNumParams() const { 3433 const auto *FPT = getType()->getAs<FunctionProtoType>(); 3434 return FPT ? FPT->getNumParams() : 0; 3435 } 3436 3437 void FunctionDecl::setParams(ASTContext &C, 3438 ArrayRef<ParmVarDecl *> NewParamInfo) { 3439 assert(!ParamInfo && "Already has param info!"); 3440 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 3441 3442 // Zero params -> null pointer. 3443 if (!NewParamInfo.empty()) { 3444 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 3445 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3446 } 3447 } 3448 3449 /// getMinRequiredArguments - Returns the minimum number of arguments 3450 /// needed to call this function. This may be fewer than the number of 3451 /// function parameters, if some of the parameters have default 3452 /// arguments (in C++) or are parameter packs (C++11). 3453 unsigned FunctionDecl::getMinRequiredArguments() const { 3454 if (!getASTContext().getLangOpts().CPlusPlus) 3455 return getNumParams(); 3456 3457 // Note that it is possible for a parameter with no default argument to 3458 // follow a parameter with a default argument. 3459 unsigned NumRequiredArgs = 0; 3460 unsigned MinParamsSoFar = 0; 3461 for (auto *Param : parameters()) { 3462 if (!Param->isParameterPack()) { 3463 ++MinParamsSoFar; 3464 if (!Param->hasDefaultArg()) 3465 NumRequiredArgs = MinParamsSoFar; 3466 } 3467 } 3468 return NumRequiredArgs; 3469 } 3470 3471 bool FunctionDecl::hasOneParamOrDefaultArgs() const { 3472 return getNumParams() == 1 || 3473 (getNumParams() > 1 && 3474 std::all_of(param_begin() + 1, param_end(), 3475 [](ParmVarDecl *P) { return P->hasDefaultArg(); })); 3476 } 3477 3478 /// The combination of the extern and inline keywords under MSVC forces 3479 /// the function to be required. 3480 /// 3481 /// Note: This function assumes that we will only get called when isInlined() 3482 /// would return true for this FunctionDecl. 3483 bool FunctionDecl::isMSExternInline() const { 3484 assert(isInlined() && "expected to get called on an inlined function!"); 3485 3486 const ASTContext &Context = getASTContext(); 3487 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 3488 !hasAttr<DLLExportAttr>()) 3489 return false; 3490 3491 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 3492 FD = FD->getPreviousDecl()) 3493 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3494 return true; 3495 3496 return false; 3497 } 3498 3499 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 3500 if (Redecl->getStorageClass() != SC_Extern) 3501 return false; 3502 3503 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 3504 FD = FD->getPreviousDecl()) 3505 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 3506 return false; 3507 3508 return true; 3509 } 3510 3511 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 3512 // Only consider file-scope declarations in this test. 3513 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 3514 return false; 3515 3516 // Only consider explicit declarations; the presence of a builtin for a 3517 // libcall shouldn't affect whether a definition is externally visible. 3518 if (Redecl->isImplicit()) 3519 return false; 3520 3521 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 3522 return true; // Not an inline definition 3523 3524 return false; 3525 } 3526 3527 /// For a function declaration in C or C++, determine whether this 3528 /// declaration causes the definition to be externally visible. 3529 /// 3530 /// For instance, this determines if adding the current declaration to the set 3531 /// of redeclarations of the given functions causes 3532 /// isInlineDefinitionExternallyVisible to change from false to true. 3533 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 3534 assert(!doesThisDeclarationHaveABody() && 3535 "Must have a declaration without a body."); 3536 3537 ASTContext &Context = getASTContext(); 3538 3539 if (Context.getLangOpts().MSVCCompat) { 3540 const FunctionDecl *Definition; 3541 if (hasBody(Definition) && Definition->isInlined() && 3542 redeclForcesDefMSVC(this)) 3543 return true; 3544 } 3545 3546 if (Context.getLangOpts().CPlusPlus) 3547 return false; 3548 3549 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3550 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 3551 // an externally visible definition. 3552 // 3553 // FIXME: What happens if gnu_inline gets added on after the first 3554 // declaration? 3555 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 3556 return false; 3557 3558 const FunctionDecl *Prev = this; 3559 bool FoundBody = false; 3560 while ((Prev = Prev->getPreviousDecl())) { 3561 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3562 3563 if (Prev->doesThisDeclarationHaveABody()) { 3564 // If it's not the case that both 'inline' and 'extern' are 3565 // specified on the definition, then it is always externally visible. 3566 if (!Prev->isInlineSpecified() || 3567 Prev->getStorageClass() != SC_Extern) 3568 return false; 3569 } else if (Prev->isInlineSpecified() && 3570 Prev->getStorageClass() != SC_Extern) { 3571 return false; 3572 } 3573 } 3574 return FoundBody; 3575 } 3576 3577 // C99 6.7.4p6: 3578 // [...] If all of the file scope declarations for a function in a 3579 // translation unit include the inline function specifier without extern, 3580 // then the definition in that translation unit is an inline definition. 3581 if (isInlineSpecified() && getStorageClass() != SC_Extern) 3582 return false; 3583 const FunctionDecl *Prev = this; 3584 bool FoundBody = false; 3585 while ((Prev = Prev->getPreviousDecl())) { 3586 FoundBody |= Prev->doesThisDeclarationHaveABody(); 3587 if (RedeclForcesDefC99(Prev)) 3588 return false; 3589 } 3590 return FoundBody; 3591 } 3592 3593 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { 3594 const TypeSourceInfo *TSI = getTypeSourceInfo(); 3595 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>() 3596 : FunctionTypeLoc(); 3597 } 3598 3599 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 3600 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3601 if (!FTL) 3602 return SourceRange(); 3603 3604 // Skip self-referential return types. 3605 const SourceManager &SM = getASTContext().getSourceManager(); 3606 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 3607 SourceLocation Boundary = getNameInfo().getBeginLoc(); 3608 if (RTRange.isInvalid() || Boundary.isInvalid() || 3609 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 3610 return SourceRange(); 3611 3612 return RTRange; 3613 } 3614 3615 SourceRange FunctionDecl::getParametersSourceRange() const { 3616 unsigned NP = getNumParams(); 3617 SourceLocation EllipsisLoc = getEllipsisLoc(); 3618 3619 if (NP == 0 && EllipsisLoc.isInvalid()) 3620 return SourceRange(); 3621 3622 SourceLocation Begin = 3623 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc; 3624 SourceLocation End = EllipsisLoc.isValid() 3625 ? EllipsisLoc 3626 : ParamInfo[NP - 1]->getSourceRange().getEnd(); 3627 3628 return SourceRange(Begin, End); 3629 } 3630 3631 SourceRange FunctionDecl::getExceptionSpecSourceRange() const { 3632 FunctionTypeLoc FTL = getFunctionTypeLoc(); 3633 return FTL ? FTL.getExceptionSpecRange() : SourceRange(); 3634 } 3635 3636 /// For an inline function definition in C, or for a gnu_inline function 3637 /// in C++, determine whether the definition will be externally visible. 3638 /// 3639 /// Inline function definitions are always available for inlining optimizations. 3640 /// However, depending on the language dialect, declaration specifiers, and 3641 /// attributes, the definition of an inline function may or may not be 3642 /// "externally" visible to other translation units in the program. 3643 /// 3644 /// In C99, inline definitions are not externally visible by default. However, 3645 /// if even one of the global-scope declarations is marked "extern inline", the 3646 /// inline definition becomes externally visible (C99 6.7.4p6). 3647 /// 3648 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 3649 /// definition, we use the GNU semantics for inline, which are nearly the 3650 /// opposite of C99 semantics. In particular, "inline" by itself will create 3651 /// an externally visible symbol, but "extern inline" will not create an 3652 /// externally visible symbol. 3653 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 3654 assert((doesThisDeclarationHaveABody() || willHaveBody() || 3655 hasAttr<AliasAttr>()) && 3656 "Must be a function definition"); 3657 assert(isInlined() && "Function must be inline"); 3658 ASTContext &Context = getASTContext(); 3659 3660 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 3661 // Note: If you change the logic here, please change 3662 // doesDeclarationForceExternallyVisibleDefinition as well. 3663 // 3664 // If it's not the case that both 'inline' and 'extern' are 3665 // specified on the definition, then this inline definition is 3666 // externally visible. 3667 if (Context.getLangOpts().CPlusPlus) 3668 return false; 3669 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 3670 return true; 3671 3672 // If any declaration is 'inline' but not 'extern', then this definition 3673 // is externally visible. 3674 for (auto Redecl : redecls()) { 3675 if (Redecl->isInlineSpecified() && 3676 Redecl->getStorageClass() != SC_Extern) 3677 return true; 3678 } 3679 3680 return false; 3681 } 3682 3683 // The rest of this function is C-only. 3684 assert(!Context.getLangOpts().CPlusPlus && 3685 "should not use C inline rules in C++"); 3686 3687 // C99 6.7.4p6: 3688 // [...] If all of the file scope declarations for a function in a 3689 // translation unit include the inline function specifier without extern, 3690 // then the definition in that translation unit is an inline definition. 3691 for (auto Redecl : redecls()) { 3692 if (RedeclForcesDefC99(Redecl)) 3693 return true; 3694 } 3695 3696 // C99 6.7.4p6: 3697 // An inline definition does not provide an external definition for the 3698 // function, and does not forbid an external definition in another 3699 // translation unit. 3700 return false; 3701 } 3702 3703 /// getOverloadedOperator - Which C++ overloaded operator this 3704 /// function represents, if any. 3705 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 3706 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 3707 return getDeclName().getCXXOverloadedOperator(); 3708 return OO_None; 3709 } 3710 3711 /// getLiteralIdentifier - The literal suffix identifier this function 3712 /// represents, if any. 3713 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 3714 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 3715 return getDeclName().getCXXLiteralIdentifier(); 3716 return nullptr; 3717 } 3718 3719 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 3720 if (TemplateOrSpecialization.isNull()) 3721 return TK_NonTemplate; 3722 if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) { 3723 if (isa<FunctionDecl>(ND)) 3724 return TK_DependentNonTemplate; 3725 assert(isa<FunctionTemplateDecl>(ND) && 3726 "No other valid types in NamedDecl"); 3727 return TK_FunctionTemplate; 3728 } 3729 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 3730 return TK_MemberSpecialization; 3731 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 3732 return TK_FunctionTemplateSpecialization; 3733 if (TemplateOrSpecialization.is 3734 <DependentFunctionTemplateSpecializationInfo*>()) 3735 return TK_DependentFunctionTemplateSpecialization; 3736 3737 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 3738 } 3739 3740 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 3741 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 3742 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 3743 3744 return nullptr; 3745 } 3746 3747 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 3748 if (auto *MSI = 3749 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3750 return MSI; 3751 if (auto *FTSI = TemplateOrSpecialization 3752 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 3753 return FTSI->getMemberSpecializationInfo(); 3754 return nullptr; 3755 } 3756 3757 void 3758 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 3759 FunctionDecl *FD, 3760 TemplateSpecializationKind TSK) { 3761 assert(TemplateOrSpecialization.isNull() && 3762 "Member function is already a specialization"); 3763 MemberSpecializationInfo *Info 3764 = new (C) MemberSpecializationInfo(FD, TSK); 3765 TemplateOrSpecialization = Info; 3766 } 3767 3768 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const { 3769 return dyn_cast_or_null<FunctionTemplateDecl>( 3770 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 3771 } 3772 3773 void FunctionDecl::setDescribedFunctionTemplate( 3774 FunctionTemplateDecl *Template) { 3775 assert(TemplateOrSpecialization.isNull() && 3776 "Member function is already a specialization"); 3777 TemplateOrSpecialization = Template; 3778 } 3779 3780 void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) { 3781 assert(TemplateOrSpecialization.isNull() && 3782 "Function is already a specialization"); 3783 TemplateOrSpecialization = FD; 3784 } 3785 3786 FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const { 3787 return dyn_cast_or_null<FunctionDecl>( 3788 TemplateOrSpecialization.dyn_cast<NamedDecl *>()); 3789 } 3790 3791 bool FunctionDecl::isImplicitlyInstantiable() const { 3792 // If the function is invalid, it can't be implicitly instantiated. 3793 if (isInvalidDecl()) 3794 return false; 3795 3796 switch (getTemplateSpecializationKindForInstantiation()) { 3797 case TSK_Undeclared: 3798 case TSK_ExplicitInstantiationDefinition: 3799 case TSK_ExplicitSpecialization: 3800 return false; 3801 3802 case TSK_ImplicitInstantiation: 3803 return true; 3804 3805 case TSK_ExplicitInstantiationDeclaration: 3806 // Handled below. 3807 break; 3808 } 3809 3810 // Find the actual template from which we will instantiate. 3811 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 3812 bool HasPattern = false; 3813 if (PatternDecl) 3814 HasPattern = PatternDecl->hasBody(PatternDecl); 3815 3816 // C++0x [temp.explicit]p9: 3817 // Except for inline functions, other explicit instantiation declarations 3818 // have the effect of suppressing the implicit instantiation of the entity 3819 // to which they refer. 3820 if (!HasPattern || !PatternDecl) 3821 return true; 3822 3823 return PatternDecl->isInlined(); 3824 } 3825 3826 bool FunctionDecl::isTemplateInstantiation() const { 3827 // FIXME: Remove this, it's not clear what it means. (Which template 3828 // specialization kind?) 3829 return clang::isTemplateInstantiation(getTemplateSpecializationKind()); 3830 } 3831 3832 FunctionDecl * 3833 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const { 3834 // If this is a generic lambda call operator specialization, its 3835 // instantiation pattern is always its primary template's pattern 3836 // even if its primary template was instantiated from another 3837 // member template (which happens with nested generic lambdas). 3838 // Since a lambda's call operator's body is transformed eagerly, 3839 // we don't have to go hunting for a prototype definition template 3840 // (i.e. instantiated-from-member-template) to use as an instantiation 3841 // pattern. 3842 3843 if (isGenericLambdaCallOperatorSpecialization( 3844 dyn_cast<CXXMethodDecl>(this))) { 3845 assert(getPrimaryTemplate() && "not a generic lambda call operator?"); 3846 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl()); 3847 } 3848 3849 // Check for a declaration of this function that was instantiated from a 3850 // friend definition. 3851 const FunctionDecl *FD = nullptr; 3852 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true)) 3853 FD = this; 3854 3855 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) { 3856 if (ForDefinition && 3857 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind())) 3858 return nullptr; 3859 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom())); 3860 } 3861 3862 if (ForDefinition && 3863 !clang::isTemplateInstantiation(getTemplateSpecializationKind())) 3864 return nullptr; 3865 3866 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 3867 // If we hit a point where the user provided a specialization of this 3868 // template, we're done looking. 3869 while (!ForDefinition || !Primary->isMemberSpecialization()) { 3870 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate(); 3871 if (!NewPrimary) 3872 break; 3873 Primary = NewPrimary; 3874 } 3875 3876 return getDefinitionOrSelf(Primary->getTemplatedDecl()); 3877 } 3878 3879 return nullptr; 3880 } 3881 3882 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 3883 if (FunctionTemplateSpecializationInfo *Info 3884 = TemplateOrSpecialization 3885 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3886 return Info->getTemplate(); 3887 } 3888 return nullptr; 3889 } 3890 3891 FunctionTemplateSpecializationInfo * 3892 FunctionDecl::getTemplateSpecializationInfo() const { 3893 return TemplateOrSpecialization 3894 .dyn_cast<FunctionTemplateSpecializationInfo *>(); 3895 } 3896 3897 const TemplateArgumentList * 3898 FunctionDecl::getTemplateSpecializationArgs() const { 3899 if (FunctionTemplateSpecializationInfo *Info 3900 = TemplateOrSpecialization 3901 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3902 return Info->TemplateArguments; 3903 } 3904 return nullptr; 3905 } 3906 3907 const ASTTemplateArgumentListInfo * 3908 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 3909 if (FunctionTemplateSpecializationInfo *Info 3910 = TemplateOrSpecialization 3911 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3912 return Info->TemplateArgumentsAsWritten; 3913 } 3914 return nullptr; 3915 } 3916 3917 void 3918 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 3919 FunctionTemplateDecl *Template, 3920 const TemplateArgumentList *TemplateArgs, 3921 void *InsertPos, 3922 TemplateSpecializationKind TSK, 3923 const TemplateArgumentListInfo *TemplateArgsAsWritten, 3924 SourceLocation PointOfInstantiation) { 3925 assert((TemplateOrSpecialization.isNull() || 3926 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && 3927 "Member function is already a specialization"); 3928 assert(TSK != TSK_Undeclared && 3929 "Must specify the type of function template specialization"); 3930 assert((TemplateOrSpecialization.isNull() || 3931 TSK == TSK_ExplicitSpecialization) && 3932 "Member specialization must be an explicit specialization"); 3933 FunctionTemplateSpecializationInfo *Info = 3934 FunctionTemplateSpecializationInfo::Create( 3935 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten, 3936 PointOfInstantiation, 3937 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()); 3938 TemplateOrSpecialization = Info; 3939 Template->addSpecialization(Info, InsertPos); 3940 } 3941 3942 void 3943 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 3944 const UnresolvedSetImpl &Templates, 3945 const TemplateArgumentListInfo &TemplateArgs) { 3946 assert(TemplateOrSpecialization.isNull()); 3947 DependentFunctionTemplateSpecializationInfo *Info = 3948 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 3949 TemplateArgs); 3950 TemplateOrSpecialization = Info; 3951 } 3952 3953 DependentFunctionTemplateSpecializationInfo * 3954 FunctionDecl::getDependentSpecializationInfo() const { 3955 return TemplateOrSpecialization 3956 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>(); 3957 } 3958 3959 DependentFunctionTemplateSpecializationInfo * 3960 DependentFunctionTemplateSpecializationInfo::Create( 3961 ASTContext &Context, const UnresolvedSetImpl &Ts, 3962 const TemplateArgumentListInfo &TArgs) { 3963 void *Buffer = Context.Allocate( 3964 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>( 3965 TArgs.size(), Ts.size())); 3966 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs); 3967 } 3968 3969 DependentFunctionTemplateSpecializationInfo:: 3970 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 3971 const TemplateArgumentListInfo &TArgs) 3972 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 3973 NumTemplates = Ts.size(); 3974 NumArgs = TArgs.size(); 3975 3976 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>(); 3977 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 3978 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 3979 3980 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>(); 3981 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 3982 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 3983 } 3984 3985 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 3986 // For a function template specialization, query the specialization 3987 // information object. 3988 if (FunctionTemplateSpecializationInfo *FTSInfo = 3989 TemplateOrSpecialization 3990 .dyn_cast<FunctionTemplateSpecializationInfo *>()) 3991 return FTSInfo->getTemplateSpecializationKind(); 3992 3993 if (MemberSpecializationInfo *MSInfo = 3994 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 3995 return MSInfo->getTemplateSpecializationKind(); 3996 3997 return TSK_Undeclared; 3998 } 3999 4000 TemplateSpecializationKind 4001 FunctionDecl::getTemplateSpecializationKindForInstantiation() const { 4002 // This is the same as getTemplateSpecializationKind(), except that for a 4003 // function that is both a function template specialization and a member 4004 // specialization, we prefer the member specialization information. Eg: 4005 // 4006 // template<typename T> struct A { 4007 // template<typename U> void f() {} 4008 // template<> void f<int>() {} 4009 // }; 4010 // 4011 // For A<int>::f<int>(): 4012 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization 4013 // * getTemplateSpecializationKindForInstantiation() will return 4014 // TSK_ImplicitInstantiation 4015 // 4016 // This reflects the facts that A<int>::f<int> is an explicit specialization 4017 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated 4018 // from A::f<int> if a definition is needed. 4019 if (FunctionTemplateSpecializationInfo *FTSInfo = 4020 TemplateOrSpecialization 4021 .dyn_cast<FunctionTemplateSpecializationInfo *>()) { 4022 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo()) 4023 return MSInfo->getTemplateSpecializationKind(); 4024 return FTSInfo->getTemplateSpecializationKind(); 4025 } 4026 4027 if (MemberSpecializationInfo *MSInfo = 4028 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4029 return MSInfo->getTemplateSpecializationKind(); 4030 4031 return TSK_Undeclared; 4032 } 4033 4034 void 4035 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4036 SourceLocation PointOfInstantiation) { 4037 if (FunctionTemplateSpecializationInfo *FTSInfo 4038 = TemplateOrSpecialization.dyn_cast< 4039 FunctionTemplateSpecializationInfo*>()) { 4040 FTSInfo->setTemplateSpecializationKind(TSK); 4041 if (TSK != TSK_ExplicitSpecialization && 4042 PointOfInstantiation.isValid() && 4043 FTSInfo->getPointOfInstantiation().isInvalid()) { 4044 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 4045 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4046 L->InstantiationRequested(this); 4047 } 4048 } else if (MemberSpecializationInfo *MSInfo 4049 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 4050 MSInfo->setTemplateSpecializationKind(TSK); 4051 if (TSK != TSK_ExplicitSpecialization && 4052 PointOfInstantiation.isValid() && 4053 MSInfo->getPointOfInstantiation().isInvalid()) { 4054 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4055 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4056 L->InstantiationRequested(this); 4057 } 4058 } else 4059 llvm_unreachable("Function cannot have a template specialization kind"); 4060 } 4061 4062 SourceLocation FunctionDecl::getPointOfInstantiation() const { 4063 if (FunctionTemplateSpecializationInfo *FTSInfo 4064 = TemplateOrSpecialization.dyn_cast< 4065 FunctionTemplateSpecializationInfo*>()) 4066 return FTSInfo->getPointOfInstantiation(); 4067 if (MemberSpecializationInfo *MSInfo = 4068 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>()) 4069 return MSInfo->getPointOfInstantiation(); 4070 4071 return SourceLocation(); 4072 } 4073 4074 bool FunctionDecl::isOutOfLine() const { 4075 if (Decl::isOutOfLine()) 4076 return true; 4077 4078 // If this function was instantiated from a member function of a 4079 // class template, check whether that member function was defined out-of-line. 4080 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 4081 const FunctionDecl *Definition; 4082 if (FD->hasBody(Definition)) 4083 return Definition->isOutOfLine(); 4084 } 4085 4086 // If this function was instantiated from a function template, 4087 // check whether that function template was defined out-of-line. 4088 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 4089 const FunctionDecl *Definition; 4090 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 4091 return Definition->isOutOfLine(); 4092 } 4093 4094 return false; 4095 } 4096 4097 SourceRange FunctionDecl::getSourceRange() const { 4098 return SourceRange(getOuterLocStart(), EndRangeLoc); 4099 } 4100 4101 unsigned FunctionDecl::getMemoryFunctionKind() const { 4102 IdentifierInfo *FnInfo = getIdentifier(); 4103 4104 if (!FnInfo) 4105 return 0; 4106 4107 // Builtin handling. 4108 switch (getBuiltinID()) { 4109 case Builtin::BI__builtin_memset: 4110 case Builtin::BI__builtin___memset_chk: 4111 case Builtin::BImemset: 4112 return Builtin::BImemset; 4113 4114 case Builtin::BI__builtin_memcpy: 4115 case Builtin::BI__builtin___memcpy_chk: 4116 case Builtin::BImemcpy: 4117 return Builtin::BImemcpy; 4118 4119 case Builtin::BI__builtin_mempcpy: 4120 case Builtin::BI__builtin___mempcpy_chk: 4121 case Builtin::BImempcpy: 4122 return Builtin::BImempcpy; 4123 4124 case Builtin::BI__builtin_memmove: 4125 case Builtin::BI__builtin___memmove_chk: 4126 case Builtin::BImemmove: 4127 return Builtin::BImemmove; 4128 4129 case Builtin::BIstrlcpy: 4130 case Builtin::BI__builtin___strlcpy_chk: 4131 return Builtin::BIstrlcpy; 4132 4133 case Builtin::BIstrlcat: 4134 case Builtin::BI__builtin___strlcat_chk: 4135 return Builtin::BIstrlcat; 4136 4137 case Builtin::BI__builtin_memcmp: 4138 case Builtin::BImemcmp: 4139 return Builtin::BImemcmp; 4140 4141 case Builtin::BI__builtin_bcmp: 4142 case Builtin::BIbcmp: 4143 return Builtin::BIbcmp; 4144 4145 case Builtin::BI__builtin_strncpy: 4146 case Builtin::BI__builtin___strncpy_chk: 4147 case Builtin::BIstrncpy: 4148 return Builtin::BIstrncpy; 4149 4150 case Builtin::BI__builtin_strncmp: 4151 case Builtin::BIstrncmp: 4152 return Builtin::BIstrncmp; 4153 4154 case Builtin::BI__builtin_strncasecmp: 4155 case Builtin::BIstrncasecmp: 4156 return Builtin::BIstrncasecmp; 4157 4158 case Builtin::BI__builtin_strncat: 4159 case Builtin::BI__builtin___strncat_chk: 4160 case Builtin::BIstrncat: 4161 return Builtin::BIstrncat; 4162 4163 case Builtin::BI__builtin_strndup: 4164 case Builtin::BIstrndup: 4165 return Builtin::BIstrndup; 4166 4167 case Builtin::BI__builtin_strlen: 4168 case Builtin::BIstrlen: 4169 return Builtin::BIstrlen; 4170 4171 case Builtin::BI__builtin_bzero: 4172 case Builtin::BIbzero: 4173 return Builtin::BIbzero; 4174 4175 case Builtin::BIfree: 4176 return Builtin::BIfree; 4177 4178 default: 4179 if (isExternC()) { 4180 if (FnInfo->isStr("memset")) 4181 return Builtin::BImemset; 4182 if (FnInfo->isStr("memcpy")) 4183 return Builtin::BImemcpy; 4184 if (FnInfo->isStr("mempcpy")) 4185 return Builtin::BImempcpy; 4186 if (FnInfo->isStr("memmove")) 4187 return Builtin::BImemmove; 4188 if (FnInfo->isStr("memcmp")) 4189 return Builtin::BImemcmp; 4190 if (FnInfo->isStr("bcmp")) 4191 return Builtin::BIbcmp; 4192 if (FnInfo->isStr("strncpy")) 4193 return Builtin::BIstrncpy; 4194 if (FnInfo->isStr("strncmp")) 4195 return Builtin::BIstrncmp; 4196 if (FnInfo->isStr("strncasecmp")) 4197 return Builtin::BIstrncasecmp; 4198 if (FnInfo->isStr("strncat")) 4199 return Builtin::BIstrncat; 4200 if (FnInfo->isStr("strndup")) 4201 return Builtin::BIstrndup; 4202 if (FnInfo->isStr("strlen")) 4203 return Builtin::BIstrlen; 4204 if (FnInfo->isStr("bzero")) 4205 return Builtin::BIbzero; 4206 } else if (isInStdNamespace()) { 4207 if (FnInfo->isStr("free")) 4208 return Builtin::BIfree; 4209 } 4210 break; 4211 } 4212 return 0; 4213 } 4214 4215 unsigned FunctionDecl::getODRHash() const { 4216 assert(hasODRHash()); 4217 return ODRHash; 4218 } 4219 4220 unsigned FunctionDecl::getODRHash() { 4221 if (hasODRHash()) 4222 return ODRHash; 4223 4224 if (auto *FT = getInstantiatedFromMemberFunction()) { 4225 setHasODRHash(true); 4226 ODRHash = FT->getODRHash(); 4227 return ODRHash; 4228 } 4229 4230 class ODRHash Hash; 4231 Hash.AddFunctionDecl(this); 4232 setHasODRHash(true); 4233 ODRHash = Hash.CalculateHash(); 4234 return ODRHash; 4235 } 4236 4237 //===----------------------------------------------------------------------===// 4238 // FieldDecl Implementation 4239 //===----------------------------------------------------------------------===// 4240 4241 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 4242 SourceLocation StartLoc, SourceLocation IdLoc, 4243 IdentifierInfo *Id, QualType T, 4244 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 4245 InClassInitStyle InitStyle) { 4246 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 4247 BW, Mutable, InitStyle); 4248 } 4249 4250 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4251 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 4252 SourceLocation(), nullptr, QualType(), nullptr, 4253 nullptr, false, ICIS_NoInit); 4254 } 4255 4256 bool FieldDecl::isAnonymousStructOrUnion() const { 4257 if (!isImplicit() || getDeclName()) 4258 return false; 4259 4260 if (const auto *Record = getType()->getAs<RecordType>()) 4261 return Record->getDecl()->isAnonymousStructOrUnion(); 4262 4263 return false; 4264 } 4265 4266 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 4267 assert(isBitField() && "not a bitfield"); 4268 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); 4269 } 4270 4271 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const { 4272 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() && 4273 getBitWidthValue(Ctx) == 0; 4274 } 4275 4276 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { 4277 if (isZeroLengthBitField(Ctx)) 4278 return true; 4279 4280 // C++2a [intro.object]p7: 4281 // An object has nonzero size if it 4282 // -- is not a potentially-overlapping subobject, or 4283 if (!hasAttr<NoUniqueAddressAttr>()) 4284 return false; 4285 4286 // -- is not of class type, or 4287 const auto *RT = getType()->getAs<RecordType>(); 4288 if (!RT) 4289 return false; 4290 const RecordDecl *RD = RT->getDecl()->getDefinition(); 4291 if (!RD) { 4292 assert(isInvalidDecl() && "valid field has incomplete type"); 4293 return false; 4294 } 4295 4296 // -- [has] virtual member functions or virtual base classes, or 4297 // -- has subobjects of nonzero size or bit-fields of nonzero length 4298 const auto *CXXRD = cast<CXXRecordDecl>(RD); 4299 if (!CXXRD->isEmpty()) 4300 return false; 4301 4302 // Otherwise, [...] the circumstances under which the object has zero size 4303 // are implementation-defined. 4304 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS 4305 // ABI will do. 4306 return true; 4307 } 4308 4309 unsigned FieldDecl::getFieldIndex() const { 4310 const FieldDecl *Canonical = getCanonicalDecl(); 4311 if (Canonical != this) 4312 return Canonical->getFieldIndex(); 4313 4314 if (CachedFieldIndex) return CachedFieldIndex - 1; 4315 4316 unsigned Index = 0; 4317 const RecordDecl *RD = getParent()->getDefinition(); 4318 assert(RD && "requested index for field of struct with no definition"); 4319 4320 for (auto *Field : RD->fields()) { 4321 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 4322 ++Index; 4323 } 4324 4325 assert(CachedFieldIndex && "failed to find field in parent"); 4326 return CachedFieldIndex - 1; 4327 } 4328 4329 SourceRange FieldDecl::getSourceRange() const { 4330 const Expr *FinalExpr = getInClassInitializer(); 4331 if (!FinalExpr) 4332 FinalExpr = getBitWidth(); 4333 if (FinalExpr) 4334 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc()); 4335 return DeclaratorDecl::getSourceRange(); 4336 } 4337 4338 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 4339 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 4340 "capturing type in non-lambda or captured record."); 4341 assert(InitStorage.getInt() == ISK_NoInit && 4342 InitStorage.getPointer() == nullptr && 4343 "bit width, initializer or captured type already set"); 4344 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType), 4345 ISK_CapturedVLAType); 4346 } 4347 4348 //===----------------------------------------------------------------------===// 4349 // TagDecl Implementation 4350 //===----------------------------------------------------------------------===// 4351 4352 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, 4353 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, 4354 SourceLocation StartL) 4355 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), 4356 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { 4357 assert((DK != Enum || TK == TTK_Enum) && 4358 "EnumDecl not matched with TTK_Enum"); 4359 setPreviousDecl(PrevDecl); 4360 setTagKind(TK); 4361 setCompleteDefinition(false); 4362 setBeingDefined(false); 4363 setEmbeddedInDeclarator(false); 4364 setFreeStanding(false); 4365 setCompleteDefinitionRequired(false); 4366 TagDeclBits.IsThisDeclarationADemotedDefinition = false; 4367 } 4368 4369 SourceLocation TagDecl::getOuterLocStart() const { 4370 return getTemplateOrInnerLocStart(this); 4371 } 4372 4373 SourceRange TagDecl::getSourceRange() const { 4374 SourceLocation RBraceLoc = BraceRange.getEnd(); 4375 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 4376 return SourceRange(getOuterLocStart(), E); 4377 } 4378 4379 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 4380 4381 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 4382 TypedefNameDeclOrQualifier = TDD; 4383 if (const Type *T = getTypeForDecl()) { 4384 (void)T; 4385 assert(T->isLinkageValid()); 4386 } 4387 assert(isLinkageValid()); 4388 } 4389 4390 void TagDecl::startDefinition() { 4391 setBeingDefined(true); 4392 4393 if (auto *D = dyn_cast<CXXRecordDecl>(this)) { 4394 struct CXXRecordDecl::DefinitionData *Data = 4395 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 4396 for (auto I : redecls()) 4397 cast<CXXRecordDecl>(I)->DefinitionData = Data; 4398 } 4399 } 4400 4401 void TagDecl::completeDefinition() { 4402 assert((!isa<CXXRecordDecl>(this) || 4403 cast<CXXRecordDecl>(this)->hasDefinition()) && 4404 "definition completed but not started"); 4405 4406 setCompleteDefinition(true); 4407 setBeingDefined(false); 4408 4409 if (ASTMutationListener *L = getASTMutationListener()) 4410 L->CompletedTagDefinition(this); 4411 } 4412 4413 TagDecl *TagDecl::getDefinition() const { 4414 if (isCompleteDefinition()) 4415 return const_cast<TagDecl *>(this); 4416 4417 // If it's possible for us to have an out-of-date definition, check now. 4418 if (mayHaveOutOfDateDef()) { 4419 if (IdentifierInfo *II = getIdentifier()) { 4420 if (II->isOutOfDate()) { 4421 updateOutOfDate(*II); 4422 } 4423 } 4424 } 4425 4426 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this)) 4427 return CXXRD->getDefinition(); 4428 4429 for (auto R : redecls()) 4430 if (R->isCompleteDefinition()) 4431 return R; 4432 4433 return nullptr; 4434 } 4435 4436 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 4437 if (QualifierLoc) { 4438 // Make sure the extended qualifier info is allocated. 4439 if (!hasExtInfo()) 4440 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4441 // Set qualifier info. 4442 getExtInfo()->QualifierLoc = QualifierLoc; 4443 } else { 4444 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 4445 if (hasExtInfo()) { 4446 if (getExtInfo()->NumTemplParamLists == 0) { 4447 getASTContext().Deallocate(getExtInfo()); 4448 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 4449 } 4450 else 4451 getExtInfo()->QualifierLoc = QualifierLoc; 4452 } 4453 } 4454 } 4455 4456 void TagDecl::setTemplateParameterListsInfo( 4457 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 4458 assert(!TPLists.empty()); 4459 // Make sure the extended decl info is allocated. 4460 if (!hasExtInfo()) 4461 // Allocate external info struct. 4462 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 4463 // Set the template parameter lists info. 4464 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 4465 } 4466 4467 //===----------------------------------------------------------------------===// 4468 // EnumDecl Implementation 4469 //===----------------------------------------------------------------------===// 4470 4471 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4472 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, 4473 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 4474 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4475 assert(Scoped || !ScopedUsingClassTag); 4476 IntegerType = nullptr; 4477 setNumPositiveBits(0); 4478 setNumNegativeBits(0); 4479 setScoped(Scoped); 4480 setScopedUsingClassTag(ScopedUsingClassTag); 4481 setFixed(Fixed); 4482 setHasODRHash(false); 4483 ODRHash = 0; 4484 } 4485 4486 void EnumDecl::anchor() {} 4487 4488 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 4489 SourceLocation StartLoc, SourceLocation IdLoc, 4490 IdentifierInfo *Id, 4491 EnumDecl *PrevDecl, bool IsScoped, 4492 bool IsScopedUsingClassTag, bool IsFixed) { 4493 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 4494 IsScoped, IsScopedUsingClassTag, IsFixed); 4495 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4496 C.getTypeDeclType(Enum, PrevDecl); 4497 return Enum; 4498 } 4499 4500 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4501 EnumDecl *Enum = 4502 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 4503 nullptr, nullptr, false, false, false); 4504 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4505 return Enum; 4506 } 4507 4508 SourceRange EnumDecl::getIntegerTypeRange() const { 4509 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 4510 return TI->getTypeLoc().getSourceRange(); 4511 return SourceRange(); 4512 } 4513 4514 void EnumDecl::completeDefinition(QualType NewType, 4515 QualType NewPromotionType, 4516 unsigned NumPositiveBits, 4517 unsigned NumNegativeBits) { 4518 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 4519 if (!IntegerType) 4520 IntegerType = NewType.getTypePtr(); 4521 PromotionType = NewPromotionType; 4522 setNumPositiveBits(NumPositiveBits); 4523 setNumNegativeBits(NumNegativeBits); 4524 TagDecl::completeDefinition(); 4525 } 4526 4527 bool EnumDecl::isClosed() const { 4528 if (const auto *A = getAttr<EnumExtensibilityAttr>()) 4529 return A->getExtensibility() == EnumExtensibilityAttr::Closed; 4530 return true; 4531 } 4532 4533 bool EnumDecl::isClosedFlag() const { 4534 return isClosed() && hasAttr<FlagEnumAttr>(); 4535 } 4536 4537 bool EnumDecl::isClosedNonFlag() const { 4538 return isClosed() && !hasAttr<FlagEnumAttr>(); 4539 } 4540 4541 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 4542 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 4543 return MSI->getTemplateSpecializationKind(); 4544 4545 return TSK_Undeclared; 4546 } 4547 4548 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 4549 SourceLocation PointOfInstantiation) { 4550 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 4551 assert(MSI && "Not an instantiated member enumeration?"); 4552 MSI->setTemplateSpecializationKind(TSK); 4553 if (TSK != TSK_ExplicitSpecialization && 4554 PointOfInstantiation.isValid() && 4555 MSI->getPointOfInstantiation().isInvalid()) 4556 MSI->setPointOfInstantiation(PointOfInstantiation); 4557 } 4558 4559 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const { 4560 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 4561 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 4562 EnumDecl *ED = getInstantiatedFromMemberEnum(); 4563 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 4564 ED = NewED; 4565 return getDefinitionOrSelf(ED); 4566 } 4567 } 4568 4569 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) && 4570 "couldn't find pattern for enum instantiation"); 4571 return nullptr; 4572 } 4573 4574 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 4575 if (SpecializationInfo) 4576 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 4577 4578 return nullptr; 4579 } 4580 4581 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 4582 TemplateSpecializationKind TSK) { 4583 assert(!SpecializationInfo && "Member enum is already a specialization"); 4584 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 4585 } 4586 4587 unsigned EnumDecl::getODRHash() { 4588 if (hasODRHash()) 4589 return ODRHash; 4590 4591 class ODRHash Hash; 4592 Hash.AddEnumDecl(this); 4593 setHasODRHash(true); 4594 ODRHash = Hash.CalculateHash(); 4595 return ODRHash; 4596 } 4597 4598 SourceRange EnumDecl::getSourceRange() const { 4599 auto Res = TagDecl::getSourceRange(); 4600 // Set end-point to enum-base, e.g. enum foo : ^bar 4601 if (auto *TSI = getIntegerTypeSourceInfo()) { 4602 // TagDecl doesn't know about the enum base. 4603 if (!getBraceRange().getEnd().isValid()) 4604 Res.setEnd(TSI->getTypeLoc().getEndLoc()); 4605 } 4606 return Res; 4607 } 4608 4609 //===----------------------------------------------------------------------===// 4610 // RecordDecl Implementation 4611 //===----------------------------------------------------------------------===// 4612 4613 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 4614 DeclContext *DC, SourceLocation StartLoc, 4615 SourceLocation IdLoc, IdentifierInfo *Id, 4616 RecordDecl *PrevDecl) 4617 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 4618 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!"); 4619 setHasFlexibleArrayMember(false); 4620 setAnonymousStructOrUnion(false); 4621 setHasObjectMember(false); 4622 setHasVolatileMember(false); 4623 setHasLoadedFieldsFromExternalStorage(false); 4624 setNonTrivialToPrimitiveDefaultInitialize(false); 4625 setNonTrivialToPrimitiveCopy(false); 4626 setNonTrivialToPrimitiveDestroy(false); 4627 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false); 4628 setHasNonTrivialToPrimitiveDestructCUnion(false); 4629 setHasNonTrivialToPrimitiveCopyCUnion(false); 4630 setParamDestroyedInCallee(false); 4631 setArgPassingRestrictions(APK_CanPassInRegs); 4632 setIsRandomized(false); 4633 } 4634 4635 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 4636 SourceLocation StartLoc, SourceLocation IdLoc, 4637 IdentifierInfo *Id, RecordDecl* PrevDecl) { 4638 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 4639 StartLoc, IdLoc, Id, PrevDecl); 4640 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4641 4642 C.getTypeDeclType(R, PrevDecl); 4643 return R; 4644 } 4645 4646 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 4647 RecordDecl *R = 4648 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), 4649 SourceLocation(), nullptr, nullptr); 4650 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 4651 return R; 4652 } 4653 4654 bool RecordDecl::isInjectedClassName() const { 4655 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 4656 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 4657 } 4658 4659 bool RecordDecl::isLambda() const { 4660 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 4661 return RD->isLambda(); 4662 return false; 4663 } 4664 4665 bool RecordDecl::isCapturedRecord() const { 4666 return hasAttr<CapturedRecordAttr>(); 4667 } 4668 4669 void RecordDecl::setCapturedRecord() { 4670 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 4671 } 4672 4673 bool RecordDecl::isOrContainsUnion() const { 4674 if (isUnion()) 4675 return true; 4676 4677 if (const RecordDecl *Def = getDefinition()) { 4678 for (const FieldDecl *FD : Def->fields()) { 4679 const RecordType *RT = FD->getType()->getAs<RecordType>(); 4680 if (RT && RT->getDecl()->isOrContainsUnion()) 4681 return true; 4682 } 4683 } 4684 4685 return false; 4686 } 4687 4688 RecordDecl::field_iterator RecordDecl::field_begin() const { 4689 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage()) 4690 LoadFieldsFromExternalStorage(); 4691 4692 return field_iterator(decl_iterator(FirstDecl)); 4693 } 4694 4695 /// completeDefinition - Notes that the definition of this type is now 4696 /// complete. 4697 void RecordDecl::completeDefinition() { 4698 assert(!isCompleteDefinition() && "Cannot redefine record!"); 4699 TagDecl::completeDefinition(); 4700 4701 ASTContext &Ctx = getASTContext(); 4702 4703 // Layouts are dumped when computed, so if we are dumping for all complete 4704 // types, we need to force usage to get types that wouldn't be used elsewhere. 4705 if (Ctx.getLangOpts().DumpRecordLayoutsComplete) 4706 (void)Ctx.getASTRecordLayout(this); 4707 } 4708 4709 /// isMsStruct - Get whether or not this record uses ms_struct layout. 4710 /// This which can be turned on with an attribute, pragma, or the 4711 /// -mms-bitfields command-line option. 4712 bool RecordDecl::isMsStruct(const ASTContext &C) const { 4713 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 4714 } 4715 4716 void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) { 4717 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false); 4718 LastDecl->NextInContextAndBits.setPointer(nullptr); 4719 setIsRandomized(true); 4720 } 4721 4722 void RecordDecl::LoadFieldsFromExternalStorage() const { 4723 ExternalASTSource *Source = getASTContext().getExternalSource(); 4724 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 4725 4726 // Notify that we have a RecordDecl doing some initialization. 4727 ExternalASTSource::Deserializing TheFields(Source); 4728 4729 SmallVector<Decl*, 64> Decls; 4730 setHasLoadedFieldsFromExternalStorage(true); 4731 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 4732 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 4733 }, Decls); 4734 4735 #ifndef NDEBUG 4736 // Check that all decls we got were FieldDecls. 4737 for (unsigned i=0, e=Decls.size(); i != e; ++i) 4738 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 4739 #endif 4740 4741 if (Decls.empty()) 4742 return; 4743 4744 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 4745 /*FieldsAlreadyLoaded=*/false); 4746 } 4747 4748 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 4749 ASTContext &Context = getASTContext(); 4750 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & 4751 (SanitizerKind::Address | SanitizerKind::KernelAddress); 4752 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) 4753 return false; 4754 const auto &NoSanitizeList = Context.getNoSanitizeList(); 4755 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this); 4756 // We may be able to relax some of these requirements. 4757 int ReasonToReject = -1; 4758 if (!CXXRD || CXXRD->isExternCContext()) 4759 ReasonToReject = 0; // is not C++. 4760 else if (CXXRD->hasAttr<PackedAttr>()) 4761 ReasonToReject = 1; // is packed. 4762 else if (CXXRD->isUnion()) 4763 ReasonToReject = 2; // is a union. 4764 else if (CXXRD->isTriviallyCopyable()) 4765 ReasonToReject = 3; // is trivially copyable. 4766 else if (CXXRD->hasTrivialDestructor()) 4767 ReasonToReject = 4; // has trivial destructor. 4768 else if (CXXRD->isStandardLayout()) 4769 ReasonToReject = 5; // is standard layout. 4770 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), 4771 "field-padding")) 4772 ReasonToReject = 6; // is in an excluded file. 4773 else if (NoSanitizeList.containsType( 4774 EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) 4775 ReasonToReject = 7; // The type is excluded. 4776 4777 if (EmitRemark) { 4778 if (ReasonToReject >= 0) 4779 Context.getDiagnostics().Report( 4780 getLocation(), 4781 diag::remark_sanitize_address_insert_extra_padding_rejected) 4782 << getQualifiedNameAsString() << ReasonToReject; 4783 else 4784 Context.getDiagnostics().Report( 4785 getLocation(), 4786 diag::remark_sanitize_address_insert_extra_padding_accepted) 4787 << getQualifiedNameAsString(); 4788 } 4789 return ReasonToReject < 0; 4790 } 4791 4792 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 4793 for (const auto *I : fields()) { 4794 if (I->getIdentifier()) 4795 return I; 4796 4797 if (const auto *RT = I->getType()->getAs<RecordType>()) 4798 if (const FieldDecl *NamedDataMember = 4799 RT->getDecl()->findFirstNamedDataMember()) 4800 return NamedDataMember; 4801 } 4802 4803 // We didn't find a named data member. 4804 return nullptr; 4805 } 4806 4807 //===----------------------------------------------------------------------===// 4808 // BlockDecl Implementation 4809 //===----------------------------------------------------------------------===// 4810 4811 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 4812 : Decl(Block, DC, CaretLoc), DeclContext(Block) { 4813 setIsVariadic(false); 4814 setCapturesCXXThis(false); 4815 setBlockMissingReturnType(true); 4816 setIsConversionFromLambda(false); 4817 setDoesNotEscape(false); 4818 setCanAvoidCopyToHeap(false); 4819 } 4820 4821 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 4822 assert(!ParamInfo && "Already has param info!"); 4823 4824 // Zero params -> null pointer. 4825 if (!NewParamInfo.empty()) { 4826 NumParams = NewParamInfo.size(); 4827 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 4828 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 4829 } 4830 } 4831 4832 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 4833 bool CapturesCXXThis) { 4834 this->setCapturesCXXThis(CapturesCXXThis); 4835 this->NumCaptures = Captures.size(); 4836 4837 if (Captures.empty()) { 4838 this->Captures = nullptr; 4839 return; 4840 } 4841 4842 this->Captures = Captures.copy(Context).data(); 4843 } 4844 4845 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 4846 for (const auto &I : captures()) 4847 // Only auto vars can be captured, so no redeclaration worries. 4848 if (I.getVariable() == variable) 4849 return true; 4850 4851 return false; 4852 } 4853 4854 SourceRange BlockDecl::getSourceRange() const { 4855 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation()); 4856 } 4857 4858 //===----------------------------------------------------------------------===// 4859 // Other Decl Allocation/Deallocation Method Implementations 4860 //===----------------------------------------------------------------------===// 4861 4862 void TranslationUnitDecl::anchor() {} 4863 4864 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 4865 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 4866 } 4867 4868 void PragmaCommentDecl::anchor() {} 4869 4870 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, 4871 TranslationUnitDecl *DC, 4872 SourceLocation CommentLoc, 4873 PragmaMSCommentKind CommentKind, 4874 StringRef Arg) { 4875 PragmaCommentDecl *PCD = 4876 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1)) 4877 PragmaCommentDecl(DC, CommentLoc, CommentKind); 4878 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size()); 4879 PCD->getTrailingObjects<char>()[Arg.size()] = '\0'; 4880 return PCD; 4881 } 4882 4883 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C, 4884 unsigned ID, 4885 unsigned ArgSize) { 4886 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1)) 4887 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown); 4888 } 4889 4890 void PragmaDetectMismatchDecl::anchor() {} 4891 4892 PragmaDetectMismatchDecl * 4893 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, 4894 SourceLocation Loc, StringRef Name, 4895 StringRef Value) { 4896 size_t ValueStart = Name.size() + 1; 4897 PragmaDetectMismatchDecl *PDMD = 4898 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1)) 4899 PragmaDetectMismatchDecl(DC, Loc, ValueStart); 4900 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size()); 4901 PDMD->getTrailingObjects<char>()[Name.size()] = '\0'; 4902 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(), 4903 Value.size()); 4904 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0'; 4905 return PDMD; 4906 } 4907 4908 PragmaDetectMismatchDecl * 4909 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4910 unsigned NameValueSize) { 4911 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1)) 4912 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0); 4913 } 4914 4915 void ExternCContextDecl::anchor() {} 4916 4917 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 4918 TranslationUnitDecl *DC) { 4919 return new (C, DC) ExternCContextDecl(DC); 4920 } 4921 4922 void LabelDecl::anchor() {} 4923 4924 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4925 SourceLocation IdentL, IdentifierInfo *II) { 4926 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 4927 } 4928 4929 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 4930 SourceLocation IdentL, IdentifierInfo *II, 4931 SourceLocation GnuLabelL) { 4932 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 4933 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 4934 } 4935 4936 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4937 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 4938 SourceLocation()); 4939 } 4940 4941 void LabelDecl::setMSAsmLabel(StringRef Name) { 4942 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 4943 memcpy(Buffer, Name.data(), Name.size()); 4944 Buffer[Name.size()] = '\0'; 4945 MSAsmName = Buffer; 4946 } 4947 4948 void ValueDecl::anchor() {} 4949 4950 bool ValueDecl::isWeak() const { 4951 auto *MostRecent = getMostRecentDecl(); 4952 return MostRecent->hasAttr<WeakAttr>() || 4953 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported(); 4954 } 4955 4956 void ImplicitParamDecl::anchor() {} 4957 4958 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 4959 SourceLocation IdLoc, 4960 IdentifierInfo *Id, QualType Type, 4961 ImplicitParamKind ParamKind) { 4962 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind); 4963 } 4964 4965 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type, 4966 ImplicitParamKind ParamKind) { 4967 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind); 4968 } 4969 4970 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 4971 unsigned ID) { 4972 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other); 4973 } 4974 4975 FunctionDecl * 4976 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 4977 const DeclarationNameInfo &NameInfo, QualType T, 4978 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 4979 bool isInlineSpecified, bool hasWrittenPrototype, 4980 ConstexprSpecKind ConstexprKind, 4981 Expr *TrailingRequiresClause) { 4982 FunctionDecl *New = new (C, DC) FunctionDecl( 4983 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 4984 isInlineSpecified, ConstexprKind, TrailingRequiresClause); 4985 New->setHasWrittenPrototype(hasWrittenPrototype); 4986 return New; 4987 } 4988 4989 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 4990 return new (C, ID) FunctionDecl( 4991 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), 4992 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr); 4993 } 4994 4995 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 4996 return new (C, DC) BlockDecl(DC, L); 4997 } 4998 4999 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5000 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 5001 } 5002 5003 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams) 5004 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 5005 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {} 5006 5007 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 5008 unsigned NumParams) { 5009 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5010 CapturedDecl(DC, NumParams); 5011 } 5012 5013 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5014 unsigned NumParams) { 5015 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 5016 CapturedDecl(nullptr, NumParams); 5017 } 5018 5019 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); } 5020 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); } 5021 5022 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); } 5023 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } 5024 5025 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 5026 SourceLocation L, 5027 IdentifierInfo *Id, QualType T, 5028 Expr *E, const llvm::APSInt &V) { 5029 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 5030 } 5031 5032 EnumConstantDecl * 5033 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5034 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 5035 QualType(), nullptr, llvm::APSInt()); 5036 } 5037 5038 void IndirectFieldDecl::anchor() {} 5039 5040 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC, 5041 SourceLocation L, DeclarationName N, 5042 QualType T, 5043 MutableArrayRef<NamedDecl *> CH) 5044 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()), 5045 ChainingSize(CH.size()) { 5046 // In C++, indirect field declarations conflict with tag declarations in the 5047 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them. 5048 if (C.getLangOpts().CPlusPlus) 5049 IdentifierNamespace |= IDNS_Tag; 5050 } 5051 5052 IndirectFieldDecl * 5053 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 5054 IdentifierInfo *Id, QualType T, 5055 llvm::MutableArrayRef<NamedDecl *> CH) { 5056 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH); 5057 } 5058 5059 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 5060 unsigned ID) { 5061 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(), 5062 DeclarationName(), QualType(), None); 5063 } 5064 5065 SourceRange EnumConstantDecl::getSourceRange() const { 5066 SourceLocation End = getLocation(); 5067 if (Init) 5068 End = Init->getEndLoc(); 5069 return SourceRange(getLocation(), End); 5070 } 5071 5072 void TypeDecl::anchor() {} 5073 5074 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 5075 SourceLocation StartLoc, SourceLocation IdLoc, 5076 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 5077 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5078 } 5079 5080 void TypedefNameDecl::anchor() {} 5081 5082 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 5083 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 5084 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 5085 auto *ThisTypedef = this; 5086 if (AnyRedecl && OwningTypedef) { 5087 OwningTypedef = OwningTypedef->getCanonicalDecl(); 5088 ThisTypedef = ThisTypedef->getCanonicalDecl(); 5089 } 5090 if (OwningTypedef == ThisTypedef) 5091 return TT->getDecl(); 5092 } 5093 5094 return nullptr; 5095 } 5096 5097 bool TypedefNameDecl::isTransparentTagSlow() const { 5098 auto determineIsTransparent = [&]() { 5099 if (auto *TT = getUnderlyingType()->getAs<TagType>()) { 5100 if (auto *TD = TT->getDecl()) { 5101 if (TD->getName() != getName()) 5102 return false; 5103 SourceLocation TTLoc = getLocation(); 5104 SourceLocation TDLoc = TD->getLocation(); 5105 if (!TTLoc.isMacroID() || !TDLoc.isMacroID()) 5106 return false; 5107 SourceManager &SM = getASTContext().getSourceManager(); 5108 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc); 5109 } 5110 } 5111 return false; 5112 }; 5113 5114 bool isTransparent = determineIsTransparent(); 5115 MaybeModedTInfo.setInt((isTransparent << 1) | 1); 5116 return isTransparent; 5117 } 5118 5119 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5120 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 5121 nullptr, nullptr); 5122 } 5123 5124 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 5125 SourceLocation StartLoc, 5126 SourceLocation IdLoc, IdentifierInfo *Id, 5127 TypeSourceInfo *TInfo) { 5128 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 5129 } 5130 5131 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5132 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 5133 SourceLocation(), nullptr, nullptr); 5134 } 5135 5136 SourceRange TypedefDecl::getSourceRange() const { 5137 SourceLocation RangeEnd = getLocation(); 5138 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 5139 if (typeIsPostfix(TInfo->getType())) 5140 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5141 } 5142 return SourceRange(getBeginLoc(), RangeEnd); 5143 } 5144 5145 SourceRange TypeAliasDecl::getSourceRange() const { 5146 SourceLocation RangeEnd = getBeginLoc(); 5147 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 5148 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 5149 return SourceRange(getBeginLoc(), RangeEnd); 5150 } 5151 5152 void FileScopeAsmDecl::anchor() {} 5153 5154 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 5155 StringLiteral *Str, 5156 SourceLocation AsmLoc, 5157 SourceLocation RParenLoc) { 5158 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 5159 } 5160 5161 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 5162 unsigned ID) { 5163 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 5164 SourceLocation()); 5165 } 5166 5167 void EmptyDecl::anchor() {} 5168 5169 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 5170 return new (C, DC) EmptyDecl(DC, L); 5171 } 5172 5173 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5174 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 5175 } 5176 5177 //===----------------------------------------------------------------------===// 5178 // ImportDecl Implementation 5179 //===----------------------------------------------------------------------===// 5180 5181 /// Retrieve the number of module identifiers needed to name the given 5182 /// module. 5183 static unsigned getNumModuleIdentifiers(Module *Mod) { 5184 unsigned Result = 1; 5185 while (Mod->Parent) { 5186 Mod = Mod->Parent; 5187 ++Result; 5188 } 5189 return Result; 5190 } 5191 5192 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5193 Module *Imported, 5194 ArrayRef<SourceLocation> IdentifierLocs) 5195 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5196 NextLocalImportAndComplete(nullptr, true) { 5197 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 5198 auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5199 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 5200 StoredLocs); 5201 } 5202 5203 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 5204 Module *Imported, SourceLocation EndLoc) 5205 : Decl(Import, DC, StartLoc), ImportedModule(Imported), 5206 NextLocalImportAndComplete(nullptr, false) { 5207 *getTrailingObjects<SourceLocation>() = EndLoc; 5208 } 5209 5210 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 5211 SourceLocation StartLoc, Module *Imported, 5212 ArrayRef<SourceLocation> IdentifierLocs) { 5213 return new (C, DC, 5214 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 5215 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 5216 } 5217 5218 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 5219 SourceLocation StartLoc, 5220 Module *Imported, 5221 SourceLocation EndLoc) { 5222 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 5223 ImportDecl(DC, StartLoc, Imported, EndLoc); 5224 Import->setImplicit(); 5225 return Import; 5226 } 5227 5228 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 5229 unsigned NumLocations) { 5230 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 5231 ImportDecl(EmptyShell()); 5232 } 5233 5234 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 5235 if (!isImportComplete()) 5236 return None; 5237 5238 const auto *StoredLocs = getTrailingObjects<SourceLocation>(); 5239 return llvm::makeArrayRef(StoredLocs, 5240 getNumModuleIdentifiers(getImportedModule())); 5241 } 5242 5243 SourceRange ImportDecl::getSourceRange() const { 5244 if (!isImportComplete()) 5245 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 5246 5247 return SourceRange(getLocation(), getIdentifierLocs().back()); 5248 } 5249 5250 //===----------------------------------------------------------------------===// 5251 // ExportDecl Implementation 5252 //===----------------------------------------------------------------------===// 5253 5254 void ExportDecl::anchor() {} 5255 5256 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC, 5257 SourceLocation ExportLoc) { 5258 return new (C, DC) ExportDecl(DC, ExportLoc); 5259 } 5260 5261 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 5262 return new (C, ID) ExportDecl(nullptr, SourceLocation()); 5263 } 5264