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