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

source code of clang/lib/AST/Decl.cpp