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