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