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