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