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