Bug Summary

File:clang/lib/AST/Decl.cpp
Warning:line 3890, column 5
Storage provided to placement new is only 0 bytes, whereas the allocated type requires 32 bytes

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Decl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/Decl.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/Decl.cpp

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

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/Support/TrailingObjects.h

1//===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
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/// \file
10/// This header defines support for implementing classes that have
11/// some trailing object (or arrays of objects) appended to them. The
12/// main purpose is to make it obvious where this idiom is being used,
13/// and to make the usage more idiomatic and more difficult to get
14/// wrong.
15///
16/// The TrailingObject template abstracts away the reinterpret_cast,
17/// pointer arithmetic, and size calculations used for the allocation
18/// and access of appended arrays of objects, and takes care that they
19/// are all allocated at their required alignment. Additionally, it
20/// ensures that the base type is final -- deriving from a class that
21/// expects data appended immediately after it is typically not safe.
22///
23/// Users are expected to derive from this template, and provide
24/// numTrailingObjects implementations for each trailing type except
25/// the last, e.g. like this sample:
26///
27/// \code
28/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
29/// friend TrailingObjects;
30///
31/// unsigned NumInts, NumDoubles;
32/// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
33/// };
34/// \endcode
35///
36/// You can access the appended arrays via 'getTrailingObjects', and
37/// determine the size needed for allocation via
38/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
39///
40/// All the methods implemented by this class are are intended for use
41/// by the implementation of the class, not as part of its interface
42/// (thus, private inheritance is suggested).
43///
44//===----------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
47#define LLVM_SUPPORT_TRAILINGOBJECTS_H
48
49#include "llvm/Support/AlignOf.h"
50#include "llvm/Support/Alignment.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/type_traits.h"
54#include <new>
55#include <type_traits>
56
57namespace llvm {
58
59namespace trailing_objects_internal {
60/// Helper template to calculate the max alignment requirement for a set of
61/// objects.
62template <typename First, typename... Rest> class AlignmentCalcHelper {
63private:
64 enum {
65 FirstAlignment = alignof(First),
66 RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
67 };
68
69public:
70 enum {
71 Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
72 };
73};
74
75template <typename First> class AlignmentCalcHelper<First> {
76public:
77 enum { Alignment = alignof(First) };
78};
79
80/// The base class for TrailingObjects* classes.
81class TrailingObjectsBase {
82protected:
83 /// OverloadToken's purpose is to allow specifying function overloads
84 /// for different types, without actually taking the types as
85 /// parameters. (Necessary because member function templates cannot
86 /// be specialized, so overloads must be used instead of
87 /// specialization.)
88 template <typename T> struct OverloadToken {};
89};
90
91// Just a little helper for transforming a type pack into the same
92// number of a different type. e.g.:
93// ExtractSecondType<Foo..., int>::type
94template <typename Ty1, typename Ty2> struct ExtractSecondType {
95 typedef Ty2 type;
96};
97
98// TrailingObjectsImpl is somewhat complicated, because it is a
99// recursively inheriting template, in order to handle the template
100// varargs. Each level of inheritance picks off a single trailing type
101// then recurses on the rest. The "Align", "BaseTy", and
102// "TopTrailingObj" arguments are passed through unchanged through the
103// recursion. "PrevTy" is, at each level, the type handled by the
104// level right above it.
105
106template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
107 typename... MoreTys>
108class TrailingObjectsImpl {
109 // The main template definition is never used -- the two
110 // specializations cover all possibilities.
111};
112
113template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
114 typename NextTy, typename... MoreTys>
115class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
116 MoreTys...>
117 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
118 MoreTys...> {
119
120 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
121 ParentType;
122
123 struct RequiresRealignment {
124 static const bool value = alignof(PrevTy) < alignof(NextTy);
125 };
126
127 static constexpr bool requiresRealignment() {
128 return RequiresRealignment::value;
129 }
130
131protected:
132 // Ensure the inherited getTrailingObjectsImpl is not hidden.
133 using ParentType::getTrailingObjectsImpl;
134
135 // These two functions are helper functions for
136 // TrailingObjects::getTrailingObjects. They recurse to the left --
137 // the result for each type in the list of trailing types depends on
138 // the result of calling the function on the type to the
139 // left. However, the function for the type to the left is
140 // implemented by a *subclass* of this class, so we invoke it via
141 // the TopTrailingObj, which is, via the
142 // curiously-recurring-template-pattern, the most-derived type in
143 // this recursion, and thus, contains all the overloads.
144 static const NextTy *
145 getTrailingObjectsImpl(const BaseTy *Obj,
146 TrailingObjectsBase::OverloadToken<NextTy>) {
147 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
148 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
149 TopTrailingObj::callNumTrailingObjects(
150 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
151
152 if (requiresRealignment())
153 return reinterpret_cast<const NextTy *>(
154 alignAddr(Ptr, Align::Of<NextTy>()));
155 else
156 return reinterpret_cast<const NextTy *>(Ptr);
157 }
158
159 static NextTy *
160 getTrailingObjectsImpl(BaseTy *Obj,
161 TrailingObjectsBase::OverloadToken<NextTy>) {
162 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
10
'Ptr' initialized here
163 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
9
Passing value via 1st parameter 'Obj'
164 TopTrailingObj::callNumTrailingObjects(
165 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
166
167 if (requiresRealignment())
11
Taking false branch
168 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
169 else
170 return reinterpret_cast<NextTy *>(Ptr);
12
Returning pointer (loaded from 'Ptr')
171 }
172
173 // Helper function for TrailingObjects::additionalSizeToAlloc: this
174 // function recurses to superclasses, each of which requires one
175 // fewer size_t argument, and adds its own size.
176 static constexpr size_t additionalSizeToAllocImpl(
177 size_t SizeSoFar, size_t Count1,
178 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
179 return ParentType::additionalSizeToAllocImpl(
180 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
181 : SizeSoFar) +
182 sizeof(NextTy) * Count1,
183 MoreCounts...);
184 }
185};
186
187// The base case of the TrailingObjectsImpl inheritance recursion,
188// when there's no more trailing types.
189template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
190class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
191 : public TrailingObjectsBase {
192protected:
193 // This is a dummy method, only here so the "using" doesn't fail --
194 // it will never be called, because this function recurses backwards
195 // up the inheritance chain to subclasses.
196 static void getTrailingObjectsImpl();
197
198 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
199 return SizeSoFar;
200 }
201
202 template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
203};
204
205} // end namespace trailing_objects_internal
206
207// Finally, the main type defined in this file, the one intended for users...
208
209/// See the file comment for details on the usage of the
210/// TrailingObjects type.
211template <typename BaseTy, typename... TrailingTys>
212class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
213 trailing_objects_internal::AlignmentCalcHelper<
214 TrailingTys...>::Alignment,
215 BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
216 BaseTy, TrailingTys...> {
217
218 template <int A, typename B, typename T, typename P, typename... M>
219 friend class trailing_objects_internal::TrailingObjectsImpl;
220
221 template <typename... Tys> class Foo {};
222
223 typedef trailing_objects_internal::TrailingObjectsImpl<
224 trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
225 BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
226 ParentType;
227 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
228
229 using ParentType::getTrailingObjectsImpl;
230
231 // This function contains only a static_assert BaseTy is final. The
232 // static_assert must be in a function, and not at class-level
233 // because BaseTy isn't complete at class instantiation time, but
234 // will be by the time this function is instantiated.
235 static void verifyTrailingObjectsAssertions() {
236 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
237 }
238
239 // These two methods are the base of the recursion for this method.
240 static const BaseTy *
241 getTrailingObjectsImpl(const BaseTy *Obj,
242 TrailingObjectsBase::OverloadToken<BaseTy>) {
243 return Obj;
244 }
245
246 static BaseTy *
247 getTrailingObjectsImpl(BaseTy *Obj,
248 TrailingObjectsBase::OverloadToken<BaseTy>) {
249 return Obj;
250 }
251
252 // callNumTrailingObjects simply calls numTrailingObjects on the
253 // provided Obj -- except when the type being queried is BaseTy
254 // itself. There is always only one of the base object, so that case
255 // is handled here. (An additional benefit of indirecting through
256 // this function is that consumers only say "friend
257 // TrailingObjects", and thus, only this class itself can call the
258 // numTrailingObjects function.)
259 static size_t
260 callNumTrailingObjects(const BaseTy *Obj,
261 TrailingObjectsBase::OverloadToken<BaseTy>) {
262 return 1;
263 }
264
265 template <typename T>
266 static size_t callNumTrailingObjects(const BaseTy *Obj,
267 TrailingObjectsBase::OverloadToken<T>) {
268 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
269 }
270
271public:
272 // Make this (privately inherited) member public.
273#ifndef _MSC_VER
274 using ParentType::OverloadToken;
275#else
276 // An MSVC bug prevents the above from working, (last tested at CL version
277 // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
278 template <typename T>
279 using OverloadToken = typename ParentType::template OverloadToken<T>;
280#endif
281
282 /// Returns a pointer to the trailing object array of the given type
283 /// (which must be one of those specified in the class template). The
284 /// array may have zero or more elements in it.
285 template <typename T> const T *getTrailingObjects() const {
286 verifyTrailingObjectsAssertions();
287 // Forwards to an impl function with overloads, since member
288 // function templates can't be specialized.
289 return this->getTrailingObjectsImpl(
290 static_cast<const BaseTy *>(this),
291 TrailingObjectsBase::OverloadToken<T>());
292 }
293
294 /// Returns a pointer to the trailing object array of the given type
295 /// (which must be one of those specified in the class template). The
296 /// array may have zero or more elements in it.
297 template <typename T> T *getTrailingObjects() {
298 verifyTrailingObjectsAssertions();
299 // Forwards to an impl function with overloads, since member
300 // function templates can't be specialized.
301 return this->getTrailingObjectsImpl(
8
Calling 'TrailingObjectsImpl::getTrailingObjectsImpl'
13
Returning from 'TrailingObjectsImpl::getTrailingObjectsImpl'
14
Returning pointer
302 static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
7
Passing value via 1st parameter 'Obj'
303 }
304
305 /// Returns the size of the trailing data, if an object were
306 /// allocated with the given counts (The counts are in the same order
307 /// as the template arguments). This does not include the size of the
308 /// base object. The template arguments must be the same as those
309 /// used in the class; they are supplied here redundantly only so
310 /// that it's clear what the counts are counting in callers.
311 template <typename... Tys>
312 static constexpr std::enable_if_t<
313 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
314 additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
315 TrailingTys, size_t>::type... Counts) {
316 return ParentType::additionalSizeToAllocImpl(0, Counts...);
317 }
318
319 /// Returns the total size of an object if it were allocated with the
320 /// given trailing object counts. This is the same as
321 /// additionalSizeToAlloc, except it *does* include the size of the base
322 /// object.
323 template <typename... Tys>
324 static constexpr std::enable_if_t<
325 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
326 totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
327 TrailingTys, size_t>::type... Counts) {
328 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
329 }
330
331 TrailingObjects() = default;
332 TrailingObjects(const TrailingObjects &) = delete;
333 TrailingObjects(TrailingObjects &&) = delete;
334 TrailingObjects &operator=(const TrailingObjects &) = delete;
335 TrailingObjects &operator=(TrailingObjects &&) = delete;
336
337 /// A type where its ::with_counts template member has a ::type member
338 /// suitable for use as uninitialized storage for an object with the given
339 /// trailing object counts. The template arguments are similar to those
340 /// of additionalSizeToAlloc.
341 ///
342 /// Use with FixedSizeStorageOwner, e.g.:
343 ///
344 /// \code{.cpp}
345 ///
346 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
347 /// MyObj::FixedSizeStorageOwner
348 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
349 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
350 ///
351 /// \endcode
352 template <typename... Tys> struct FixedSizeStorage {
353 template <size_t... Counts> struct with_counts {
354 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
355 struct type {
356 alignas(BaseTy) char buffer[Size];
357 };
358 };
359 };
360
361 /// A type that acts as the owner for an object placed into fixed storage.
362 class FixedSizeStorageOwner {
363 public:
364 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
365 ~FixedSizeStorageOwner() {
366 assert(p && "FixedSizeStorageOwner owns null?")(static_cast <bool> (p && "FixedSizeStorageOwner owns null?"
) ? void (0) : __assert_fail ("p && \"FixedSizeStorageOwner owns null?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/Support/TrailingObjects.h"
, 366, __extension__ __PRETTY_FUNCTION__))
;
367 p->~BaseTy();
368 }
369
370 BaseTy *get() { return p; }
371 const BaseTy *get() const { return p; }
372
373 private:
374 FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
375 FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
376 FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
377 FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
378
379 BaseTy *const p;
380 };
381};
382
383} // end namespace llvm
384
385#endif