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