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