Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/AST/Decl.cpp
Warning:line 3997, 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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Decl.cpp -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -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-16/lib/clang/16.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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/AST/Decl.cpp

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

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/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?\""
, "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