clang 19.0.0git
Decl.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/Attr.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ODRHash.h"
36#include "clang/AST/Stmt.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/TypeLoc.h"
42#include "clang/Basic/LLVM.h"
44#include "clang/Basic/Linkage.h"
45#include "clang/Basic/Module.h"
55#include "llvm/ADT/APSInt.h"
56#include "llvm/ADT/ArrayRef.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/StringSwitch.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/raw_ostream.h"
64#include "llvm/TargetParser/Triple.h"
65#include <algorithm>
66#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <type_traits>
74
75using namespace clang;
76
79}
80
81void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
82 SourceLocation Loc = this->Loc;
83 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
84 if (Loc.isValid()) {
85 Loc.print(OS, Context.getSourceManager());
86 OS << ": ";
87 }
88 OS << Message;
89
90 if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {
91 OS << " '";
92 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
93 OS << "'";
94 }
95
96 OS << '\n';
97}
98
99// Defined here so that it can be inlined into its direct callers.
100bool Decl::isOutOfLine() const {
102}
103
104TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
105 : Decl(TranslationUnit, nullptr, SourceLocation()),
106 DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
107
108//===----------------------------------------------------------------------===//
109// NamedDecl Implementation
110//===----------------------------------------------------------------------===//
111
112// Visibility rules aren't rigorously externally specified, but here
113// are the basic principles behind what we implement:
114//
115// 1. An explicit visibility attribute is generally a direct expression
116// of the user's intent and should be honored. Only the innermost
117// visibility attribute applies. If no visibility attribute applies,
118// global visibility settings are considered.
119//
120// 2. There is one caveat to the above: on or in a template pattern,
121// an explicit visibility attribute is just a default rule, and
122// visibility can be decreased by the visibility of template
123// arguments. But this, too, has an exception: an attribute on an
124// explicit specialization or instantiation causes all the visibility
125// restrictions of the template arguments to be ignored.
126//
127// 3. A variable that does not otherwise have explicit visibility can
128// be restricted by the visibility of its type.
129//
130// 4. A visibility restriction is explicit if it comes from an
131// attribute (or something like it), not a global visibility setting.
132// When emitting a reference to an external symbol, visibility
133// restrictions are ignored unless they are explicit.
134//
135// 5. When computing the visibility of a non-type, including a
136// non-type member of a class, only non-type visibility restrictions
137// are considered: the 'visibility' attribute, global value-visibility
138// settings, and a few special cases like __private_extern.
139//
140// 6. When computing the visibility of a type, including a type member
141// of a class, only type visibility restrictions are considered:
142// the 'type_visibility' attribute and global type-visibility settings.
143// However, a 'visibility' attribute counts as a 'type_visibility'
144// attribute on any declaration that only has the former.
145//
146// The visibility of a "secondary" entity, like a template argument,
147// is computed using the kind of that entity, not the kind of the
148// primary entity for which we are computing visibility. For example,
149// the visibility of a specialization of either of these templates:
150// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
151// template <class T, bool (&compare)(T, X)> class matcher;
152// is restricted according to the type visibility of the argument 'T',
153// the type visibility of 'bool(&)(T,X)', and the value visibility of
154// the argument function 'compare'. That 'has_match' is a value
155// and 'matcher' is a type only matters when looking for attributes
156// and settings from the immediate context.
157
158/// Does this computation kind permit us to consider additional
159/// visibility settings from attributes and the like?
161 return computation.IgnoreExplicitVisibility;
162}
163
164/// Given an LVComputationKind, return one of the same type/value sort
165/// that records that it already has explicit visibility.
168 Kind.IgnoreExplicitVisibility = true;
169 return Kind;
170}
171
172static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
173 LVComputationKind kind) {
174 assert(!kind.IgnoreExplicitVisibility &&
175 "asking for explicit visibility when we shouldn't be");
176 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
177}
178
179/// Is the given declaration a "type" or a "value" for the purposes of
180/// visibility computation?
181static bool usesTypeVisibility(const NamedDecl *D) {
182 return isa<TypeDecl>(D) ||
183 isa<ClassTemplateDecl>(D) ||
184 isa<ObjCInterfaceDecl>(D);
185}
186
187/// Does the given declaration have member specialization information,
188/// and if so, is it an explicit specialization?
189template <class T>
190static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>
192 if (const MemberSpecializationInfo *member =
193 D->getMemberSpecializationInfo()) {
194 return member->isExplicitSpecialization();
195 }
196 return false;
197}
198
199/// For templates, this question is easier: a member template can't be
200/// explicitly instantiated, so there's a single bit indicating whether
201/// or not this is an explicit member specialization.
203 return D->isMemberSpecialization();
204}
205
206/// Given a visibility attribute, return the explicit visibility
207/// associated with it.
208template <class T>
209static Visibility getVisibilityFromAttr(const T *attr) {
210 switch (attr->getVisibility()) {
211 case T::Default:
212 return DefaultVisibility;
213 case T::Hidden:
214 return HiddenVisibility;
215 case T::Protected:
216 return ProtectedVisibility;
217 }
218 llvm_unreachable("bad visibility kind");
219}
220
221/// Return the explicit visibility of the given declaration.
222static std::optional<Visibility>
224 // If we're ultimately computing the visibility of a type, look for
225 // a 'type_visibility' attribute before looking for 'visibility'.
226 if (kind == NamedDecl::VisibilityForType) {
227 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
228 return getVisibilityFromAttr(A);
229 }
230 }
231
232 // If this declaration has an explicit visibility attribute, use it.
233 if (const auto *A = D->getAttr<VisibilityAttr>()) {
234 return getVisibilityFromAttr(A);
235 }
236
237 return std::nullopt;
238}
239
240LinkageInfo LinkageComputer::getLVForType(const Type &T,
241 LVComputationKind computation) {
242 if (computation.IgnoreAllVisibility)
243 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
245}
246
247/// Get the most restrictive linkage for the types in the given
248/// template parameter list. For visibility purposes, template
249/// parameters are part of the signature of a template.
250LinkageInfo LinkageComputer::getLVForTemplateParameterList(
251 const TemplateParameterList *Params, LVComputationKind computation) {
252 LinkageInfo LV;
253 for (const NamedDecl *P : *Params) {
254 // Template type parameters are the most common and never
255 // contribute to visibility, pack or not.
256 if (isa<TemplateTypeParmDecl>(P))
257 continue;
258
259 // Non-type template parameters can be restricted by the value type, e.g.
260 // template <enum X> class A { ... };
261 // We have to be careful here, though, because we can be dealing with
262 // dependent types.
263 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
264 // Handle the non-pack case first.
265 if (!NTTP->isExpandedParameterPack()) {
266 if (!NTTP->getType()->isDependentType()) {
267 LV.merge(getLVForType(*NTTP->getType(), computation));
268 }
269 continue;
270 }
271
272 // Look at all the types in an expanded pack.
273 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
274 QualType type = NTTP->getExpansionType(i);
275 if (!type->isDependentType())
277 }
278 continue;
279 }
280
281 // Template template parameters can be restricted by their
282 // template parameters, recursively.
283 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
284
285 // Handle the non-pack case first.
286 if (!TTP->isExpandedParameterPack()) {
287 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
288 computation));
289 continue;
290 }
291
292 // Look at all expansions in an expanded pack.
293 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
294 i != n; ++i) {
295 LV.merge(getLVForTemplateParameterList(
296 TTP->getExpansionTemplateParameters(i), computation));
297 }
298 }
299
300 return LV;
301}
302
303static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
304 const Decl *Ret = nullptr;
305 const DeclContext *DC = D->getDeclContext();
306 while (DC->getDeclKind() != Decl::TranslationUnit) {
307 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
308 Ret = cast<Decl>(DC);
309 DC = DC->getParent();
310 }
311 return Ret;
312}
313
314/// Get the most restrictive linkage for the types and
315/// declarations in the given template argument list.
316///
317/// Note that we don't take an LVComputationKind because we always
318/// want to honor the visibility of template arguments in the same way.
320LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
321 LVComputationKind computation) {
322 LinkageInfo LV;
323
324 for (const TemplateArgument &Arg : Args) {
325 switch (Arg.getKind()) {
329 continue;
330
332 LV.merge(getLVForType(*Arg.getAsType(), computation));
333 continue;
334
336 const NamedDecl *ND = Arg.getAsDecl();
337 assert(!usesTypeVisibility(ND));
338 LV.merge(getLVForDecl(ND, computation));
339 continue;
340 }
341
343 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
344 continue;
345
347 LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));
348 continue;
349
352 if (TemplateDecl *Template =
353 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
354 LV.merge(getLVForDecl(Template, computation));
355 continue;
356
358 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
359 continue;
360 }
361 llvm_unreachable("bad template argument kind");
362 }
363
364 return LV;
365}
366
368LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
369 LVComputationKind computation) {
370 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
371}
372
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.)
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,
395 LVComputationKind computation) {
396 bool considerVisibility =
398
399 FunctionTemplateDecl *temp = specInfo->getTemplate();
400 // Merge information from the template declaration.
401 LinkageInfo tempLV = getLVForDecl(temp, computation);
402 // The linkage of the specialization should be consistent with the
403 // template declaration.
404 LV.setLinkage(tempLV.getLinkage());
405
406 // Merge information from the template parameters.
407 LinkageInfo paramsLV =
408 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
409 LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
410
411 // Merge information from the template arguments.
412 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
413 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
414 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
415}
416
417/// Does the given declaration have a direct visibility attribute
418/// that would match the given rules?
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?
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.
454 return true;
455
456 // This is the 'member thereof' check.
457 if (spec->isExplicitSpecialization() &&
458 hasExplicitVisibilityAlready(computation))
459 return false;
460
461 return !hasDirectVisibilityAttribute(spec, computation);
462}
463
464/// Merge in template-related linkage and visibility for the given
465/// class template specialization.
466void LinkageComputer::mergeTemplateLV(
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.
474 // Merge information from the template declaration.
475 LinkageInfo tempLV = getLVForDecl(temp, computation);
476 // The linkage of the specialization should be consistent with the
477 // template declaration.
478 LV.setLinkage(tempLV.getLinkage());
479
480 LinkageInfo paramsLV =
481 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
482 LV.mergeMaybeWithVisibility(paramsLV,
483 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(templateArgs, computation);
490 if (considerVisibility)
491 LV.mergeVisibility(argsLV);
492 LV.mergeExternalVisibility(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.
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).
507 return true;
508
509 // An explicit variable specialization is an independent, top-level
510 // declaration. As such, if it has an explicit visibility attribute,
511 // that must directly express the user's intent, and we should honor
512 // it.
513 if (spec->isExplicitSpecialization() &&
514 hasExplicitVisibilityAlready(computation))
515 return false;
516
517 return !hasDirectVisibilityAttribute(spec, computation);
518}
519
520/// Merge in template-related linkage and visibility for the given
521/// variable template specialization. As usual, follow class template
522/// specialization logic up to initialization.
523void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
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.
531 LinkageInfo tempLV =
532 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
533 LV.mergeMaybeWithVisibility(tempLV,
534 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(templateArgs, computation);
541 if (considerVisibility)
542 LV.mergeVisibility(argsLV);
543 LV.mergeExternalVisibility(argsLV);
544}
545
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>(D);
553 if (!FD)
554 return false;
555
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.
571 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
572}
573
574template <typename T> static bool isFirstInExternCContext(T *D) {
575 const T *First = D->getFirstDecl();
576 return First->isInExternCContext();
577}
578
579static bool isSingleLineLanguageLinkage(const Decl &D) {
580 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
581 if (!SD->hasBraces())
582 return true;
583 return false;
584}
585
587 if (auto *M = D->getOwningModule())
588 return M->isInterfaceOrPartition();
589 return false;
590}
591
593 return LinkageInfo::external();
594}
595
597 if (auto *TD = dyn_cast<TemplateDecl>(D))
598 D = TD->getTemplatedDecl();
599 if (D) {
600 if (auto *VD = dyn_cast<VarDecl>(D))
601 return VD->getStorageClass();
602 if (auto *FD = dyn_cast<FunctionDecl>(D))
603 return FD->getStorageClass();
604 }
605 return SC_None;
606}
607
609LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
610 LVComputationKind computation,
611 bool IgnoreVarTypeLinkage) {
613 "Not a name having namespace scope");
614 ASTContext &Context = D->getASTContext();
615
616 // C++ [basic.link]p3:
617 // A name having namespace scope (3.3.6) has internal linkage if it
618 // is the name of
619
621 // - a variable, variable template, function, or function template
622 // that is explicitly declared static; or
623 // (This bullet corresponds to C99 6.2.2p3.)
624 return LinkageInfo::internal();
625 }
626
627 if (const auto *Var = dyn_cast<VarDecl>(D)) {
628 // - a non-template variable of non-volatile const-qualified type, unless
629 // - it is explicitly declared extern, or
630 // - it is declared in the purview of a module interface unit
631 // (outside the private-module-fragment, if any) or module partition, or
632 // - it is inline, or
633 // - it was previously declared and the prior declaration did not have
634 // internal linkage
635 // (There is no equivalent in C99.)
636 if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
637 !Var->getType().isVolatileQualified() && !Var->isInline() &&
639 !isa<VarTemplateSpecializationDecl>(Var) &&
640 !Var->getDescribedVarTemplate()) {
641 const VarDecl *PrevVar = Var->getPreviousDecl();
642 if (PrevVar)
643 return getLVForDecl(PrevVar, computation);
644
645 if (Var->getStorageClass() != SC_Extern &&
646 Var->getStorageClass() != SC_PrivateExtern &&
648 return LinkageInfo::internal();
649 }
650
651 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
652 PrevVar = PrevVar->getPreviousDecl()) {
653 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
654 Var->getStorageClass() == SC_None)
655 return getDeclLinkageAndVisibility(PrevVar);
656 // Explicitly declared static.
657 if (PrevVar->getStorageClass() == SC_Static)
658 return LinkageInfo::internal();
659 }
660 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
661 // - a data member of an anonymous union.
662 const VarDecl *VD = IFD->getVarDecl();
663 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
664 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
665 }
666 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
667
668 // FIXME: This gives internal linkage to names that should have no linkage
669 // (those not covered by [basic.link]p6).
670 if (D->isInAnonymousNamespace()) {
671 const auto *Var = dyn_cast<VarDecl>(D);
672 const auto *Func = dyn_cast<FunctionDecl>(D);
673 // FIXME: The check for extern "C" here is not justified by the standard
674 // wording, but we retain it from the pre-DR1113 model to avoid breaking
675 // code.
676 //
677 // C++11 [basic.link]p4:
678 // An unnamed namespace or a namespace declared directly or indirectly
679 // within an unnamed namespace has internal linkage.
680 if ((!Var || !isFirstInExternCContext(Var)) &&
682 return LinkageInfo::internal();
683 }
684
685 // Set up the defaults.
686
687 // C99 6.2.2p5:
688 // If the declaration of an identifier for an object has file
689 // scope and no storage-class specifier, its linkage is
690 // external.
692
693 if (!hasExplicitVisibilityAlready(computation)) {
694 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
695 LV.mergeVisibility(*Vis, true);
696 } else {
697 // If we're declared in a namespace with a visibility attribute,
698 // use that namespace's visibility, and it still counts as explicit.
699 for (const DeclContext *DC = D->getDeclContext();
700 !isa<TranslationUnitDecl>(DC);
701 DC = DC->getParent()) {
702 const auto *ND = dyn_cast<NamespaceDecl>(DC);
703 if (!ND) continue;
704 if (std::optional<Visibility> Vis =
705 getExplicitVisibility(ND, computation)) {
706 LV.mergeVisibility(*Vis, true);
707 break;
708 }
709 }
710 }
711
712 // Add in global settings if the above didn't give us direct visibility.
713 if (!LV.isVisibilityExplicit()) {
714 // Use global type/value visibility as appropriate.
715 Visibility globalVisibility =
716 computation.isValueVisibility()
717 ? Context.getLangOpts().getValueVisibilityMode()
718 : Context.getLangOpts().getTypeVisibilityMode();
719 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
720
721 // If we're paying attention to global visibility, apply
722 // -finline-visibility-hidden if this is an inline method.
724 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
725 }
726 }
727
728 // C++ [basic.link]p4:
729
730 // A name having namespace scope that has not been given internal linkage
731 // above and that is the name of
732 // [...bullets...]
733 // has its linkage determined as follows:
734 // - if the enclosing namespace has internal linkage, the name has
735 // internal linkage; [handled above]
736 // - otherwise, if the declaration of the name is attached to a named
737 // module and is not exported, the name has module linkage;
738 // - otherwise, the name has external linkage.
739 // LV is currently set up to handle the last two bullets.
740 //
741 // The bullets are:
742
743 // - a variable; or
744 if (const auto *Var = dyn_cast<VarDecl>(D)) {
745 // GCC applies the following optimization to variables and static
746 // data members, but not to functions:
747 //
748 // Modify the variable's LV by the LV of its type unless this is
749 // C or extern "C". This follows from [basic.link]p9:
750 // A type without linkage shall not be used as the type of a
751 // variable or function with external linkage unless
752 // - the entity has C language linkage, or
753 // - the entity is declared within an unnamed namespace, or
754 // - the entity is not used or is defined in the same
755 // translation unit.
756 // and [basic.link]p10:
757 // ...the types specified by all declarations referring to a
758 // given variable or function shall be identical...
759 // C does not have an equivalent rule.
760 //
761 // Ignore this if we've got an explicit attribute; the user
762 // probably knows what they're doing.
763 //
764 // Note that we don't want to make the variable non-external
765 // because of this, but unique-external linkage suits us.
766
767 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
768 !IgnoreVarTypeLinkage) {
769 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
770 if (!isExternallyVisible(TypeLV.getLinkage()))
772 if (!LV.isVisibilityExplicit())
773 LV.mergeVisibility(TypeLV);
774 }
775
776 if (Var->getStorageClass() == SC_PrivateExtern)
778
779 // Note that Sema::MergeVarDecl already takes care of implementing
780 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
781 // to do it here.
782
783 // As per function and class template specializations (below),
784 // consider LV for the template and template arguments. We're at file
785 // scope, so we do not need to worry about nested specializations.
786 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
787 mergeTemplateLV(LV, spec, computation);
788 }
789
790 // - a function; or
791 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
792 // In theory, we can modify the function's LV by the LV of its
793 // type unless it has C linkage (see comment above about variables
794 // for justification). In practice, GCC doesn't do this, so it's
795 // just too painful to make work.
796
797 if (Function->getStorageClass() == SC_PrivateExtern)
799
800 // OpenMP target declare device functions are not callable from the host so
801 // they should not be exported from the device image. This applies to all
802 // functions as the host-callable kernel functions are emitted at codegen.
803 if (Context.getLangOpts().OpenMP &&
804 Context.getLangOpts().OpenMPIsTargetDevice &&
805 ((Context.getTargetInfo().getTriple().isAMDGPU() ||
806 Context.getTargetInfo().getTriple().isNVPTX()) ||
807 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
808 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
809
810 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
811 // merging storage classes and visibility attributes, so we don't have to
812 // look at previous decls in here.
813
814 // In C++, then if the type of the function uses a type with
815 // unique-external linkage, it's not legally usable from outside
816 // this translation unit. However, we should use the C linkage
817 // rules instead for extern "C" declarations.
818 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
819 // Only look at the type-as-written. Otherwise, deducing the return type
820 // of a function could change its linkage.
821 QualType TypeAsWritten = Function->getType();
822 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
823 TypeAsWritten = TSI->getType();
824 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
826 }
827
828 // Consider LV from the template and the template arguments.
829 // We're at file scope, so we do not need to worry about nested
830 // specializations.
832 = Function->getTemplateSpecializationInfo()) {
833 mergeTemplateLV(LV, Function, specInfo, computation);
834 }
835
836 // - a named class (Clause 9), or an unnamed class defined in a
837 // typedef declaration in which the class has the typedef name
838 // for linkage purposes (7.1.3); or
839 // - a named enumeration (7.2), or an unnamed enumeration
840 // defined in a typedef declaration in which the enumeration
841 // has the typedef name for linkage purposes (7.1.3); or
842 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
843 // Unnamed tags have no linkage.
844 if (!Tag->hasNameForLinkage())
845 return LinkageInfo::none();
846
847 // If this is a class template specialization, consider the
848 // linkage of the template and template arguments. We're at file
849 // scope, so we do not need to worry about nested specializations.
850 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
851 mergeTemplateLV(LV, spec, computation);
852 }
853
854 // FIXME: This is not part of the C++ standard any more.
855 // - an enumerator belonging to an enumeration with external linkage; or
856 } else if (isa<EnumConstantDecl>(D)) {
857 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
858 computation);
859 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
860 return LinkageInfo::none();
861 LV.merge(EnumLV);
862
863 // - a template
864 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
865 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
866 LinkageInfo tempLV =
867 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
868 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
869
870 // An unnamed namespace or a namespace declared directly or indirectly
871 // within an unnamed namespace has internal linkage. All other namespaces
872 // have external linkage.
873 //
874 // We handled names in anonymous namespaces above.
875 } else if (isa<NamespaceDecl>(D)) {
876 return LV;
877
878 // By extension, we assign external linkage to Objective-C
879 // interfaces.
880 } else if (isa<ObjCInterfaceDecl>(D)) {
881 // fallout
882
883 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
884 // A typedef declaration has linkage if it gives a type a name for
885 // linkage purposes.
886 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
887 return LinkageInfo::none();
888
889 } else if (isa<MSGuidDecl>(D)) {
890 // A GUID behaves like an inline variable with external linkage. Fall
891 // through.
892
893 // Everything not covered here has no linkage.
894 } else {
895 return LinkageInfo::none();
896 }
897
898 // If we ended up with non-externally-visible linkage, visibility should
899 // always be default.
901 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
902
903 return LV;
904}
905
907LinkageComputer::getLVForClassMember(const NamedDecl *D,
908 LVComputationKind computation,
909 bool IgnoreVarTypeLinkage) {
910 // Only certain class members have linkage. Note that fields don't
911 // really have linkage, but it's convenient to say they do for the
912 // purposes of calculating linkage of pointer-to-data-member
913 // template arguments.
914 //
915 // Templates also don't officially have linkage, but since we ignore
916 // the C++ standard and look at template arguments when determining
917 // linkage and visibility of a template specialization, we might hit
918 // a template template argument that way. If we do, we need to
919 // consider its linkage.
920 if (!(isa<CXXMethodDecl>(D) ||
921 isa<VarDecl>(D) ||
922 isa<FieldDecl>(D) ||
923 isa<IndirectFieldDecl>(D) ||
924 isa<TagDecl>(D) ||
925 isa<TemplateDecl>(D)))
926 return LinkageInfo::none();
927
928 LinkageInfo LV;
929
930 // If we have an explicit visibility attribute, merge that in.
931 if (!hasExplicitVisibilityAlready(computation)) {
932 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
933 LV.mergeVisibility(*Vis, true);
934 // If we're paying attention to global visibility, apply
935 // -finline-visibility-hidden if this is an inline method.
936 //
937 // Note that we do this before merging information about
938 // the class visibility.
940 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
941 }
942
943 // If this class member has an explicit visibility attribute, the only
944 // thing that can change its visibility is the template arguments, so
945 // only look for them when processing the class.
946 LVComputationKind classComputation = computation;
947 if (LV.isVisibilityExplicit())
948 classComputation = withExplicitVisibilityAlready(computation);
949
950 LinkageInfo classLV =
951 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
952 // The member has the same linkage as the class. If that's not externally
953 // visible, we don't need to compute anything about the linkage.
954 // FIXME: If we're only computing linkage, can we bail out here?
955 if (!isExternallyVisible(classLV.getLinkage()))
956 return classLV;
957
958
959 // Otherwise, don't merge in classLV yet, because in certain cases
960 // we need to completely ignore the visibility from it.
961
962 // Specifically, if this decl exists and has an explicit attribute.
963 const NamedDecl *explicitSpecSuppressor = nullptr;
964
965 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
966 // Only look at the type-as-written. Otherwise, deducing the return type
967 // of a function could change its linkage.
968 QualType TypeAsWritten = MD->getType();
969 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
970 TypeAsWritten = TSI->getType();
971 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
973
974 // If this is a method template specialization, use the linkage for
975 // the template parameters and arguments.
977 = MD->getTemplateSpecializationInfo()) {
978 mergeTemplateLV(LV, MD, spec, computation);
979 if (spec->isExplicitSpecialization()) {
980 explicitSpecSuppressor = MD;
981 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
982 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
983 }
984 } else if (isExplicitMemberSpecialization(MD)) {
985 explicitSpecSuppressor = MD;
986 }
987
988 // OpenMP target declare device functions are not callable from the host so
989 // they should not be exported from the device image. This applies to all
990 // functions as the host-callable kernel functions are emitted at codegen.
991 ASTContext &Context = D->getASTContext();
992 if (Context.getLangOpts().OpenMP &&
993 Context.getLangOpts().OpenMPIsTargetDevice &&
994 ((Context.getTargetInfo().getTriple().isAMDGPU() ||
995 Context.getTargetInfo().getTriple().isNVPTX()) ||
996 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
997 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
998
999 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1000 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1001 mergeTemplateLV(LV, spec, computation);
1002 if (spec->isExplicitSpecialization()) {
1003 explicitSpecSuppressor = spec;
1004 } else {
1005 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1007 explicitSpecSuppressor = temp->getTemplatedDecl();
1008 }
1009 }
1010 } else if (isExplicitMemberSpecialization(RD)) {
1011 explicitSpecSuppressor = RD;
1012 }
1013
1014 // Static data members.
1015 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1016 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1017 mergeTemplateLV(LV, spec, computation);
1018
1019 // Modify the variable's linkage by its type, but ignore the
1020 // type's visibility unless it's a definition.
1021 if (!IgnoreVarTypeLinkage) {
1022 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1023 // FIXME: If the type's linkage is not externally visible, we can
1024 // give this static data member UniqueExternalLinkage.
1025 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1026 LV.mergeVisibility(typeLV);
1027 LV.mergeExternalVisibility(typeLV);
1028 }
1029
1031 explicitSpecSuppressor = VD;
1032 }
1033
1034 // Template members.
1035 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1036 bool considerVisibility =
1037 (!LV.isVisibilityExplicit() &&
1038 !classLV.isVisibilityExplicit() &&
1039 !hasExplicitVisibilityAlready(computation));
1040 LinkageInfo tempLV =
1041 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1042 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1043
1044 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1045 if (isExplicitMemberSpecialization(redeclTemp)) {
1046 explicitSpecSuppressor = temp->getTemplatedDecl();
1047 }
1048 }
1049 }
1050
1051 // We should never be looking for an attribute directly on a template.
1052 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1053
1054 // If this member is an explicit member specialization, and it has
1055 // an explicit attribute, ignore visibility from the parent.
1056 bool considerClassVisibility = true;
1057 if (explicitSpecSuppressor &&
1058 // optimization: hasDVA() is true only with explicit visibility.
1059 LV.isVisibilityExplicit() &&
1060 classLV.getVisibility() != DefaultVisibility &&
1061 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1062 considerClassVisibility = false;
1063 }
1064
1065 // Finally, merge in information from the class.
1066 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1067 return LV;
1068}
1069
1070void NamedDecl::anchor() {}
1071
1073 if (!hasCachedLinkage())
1074 return true;
1075
1078 .getLinkage();
1079 return L == getCachedLinkage();
1080}
1081
1082bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {
1083 // [C++2c] [basic.scope.scope]/p5
1084 // A declaration is name-independent if its name is _ and it declares
1085 // - a variable with automatic storage duration,
1086 // - a structured binding not inhabiting a namespace scope,
1087 // - the variable introduced by an init-capture
1088 // - or a non-static data member.
1089
1090 if (!LangOpts.CPlusPlus || !getIdentifier() ||
1091 !getIdentifier()->isPlaceholder())
1092 return false;
1093 if (isa<FieldDecl>(this))
1094 return true;
1095 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {
1097 !getDeclContext()->isRecord())
1098 return false;
1099 const VarDecl *VD = IFD->getVarDecl();
1100 return !VD || VD->getStorageDuration() == SD_Automatic;
1101 }
1102 // and it declares a variable with automatic storage duration
1103 if (const auto *VD = dyn_cast<VarDecl>(this)) {
1104 if (isa<ParmVarDecl>(VD))
1105 return false;
1106 if (VD->isInitCapture())
1107 return true;
1109 }
1110 if (const auto *BD = dyn_cast<BindingDecl>(this);
1112 const VarDecl *VD = BD->getHoldingVar();
1114 }
1115 return false;
1116}
1117
1119NamedDecl::isReserved(const LangOptions &LangOpts) const {
1120 const IdentifierInfo *II = getIdentifier();
1121
1122 // This triggers at least for CXXLiteralIdentifiers, which we already checked
1123 // at lexing time.
1124 if (!II)
1126
1127 ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1128 if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1129 // This name is only reserved at global scope. Check if this declaration
1130 // conflicts with a global scope declaration.
1131 if (isa<ParmVarDecl>(this) || isTemplateParameter())
1133
1134 // C++ [dcl.link]/7:
1135 // Two declarations [conflict] if [...] one declares a function or
1136 // variable with C language linkage, and the other declares [...] a
1137 // variable that belongs to the global scope.
1138 //
1139 // Therefore names that are reserved at global scope are also reserved as
1140 // names of variables and functions with C language linkage.
1142 if (DC->isTranslationUnit())
1143 return Status;
1144 if (auto *VD = dyn_cast<VarDecl>(this))
1145 if (VD->isExternC())
1147 if (auto *FD = dyn_cast<FunctionDecl>(this))
1148 if (FD->isExternC())
1151 }
1152
1153 return Status;
1154}
1155
1157 StringRef name = getName();
1158 if (name.empty()) return SFF_None;
1159
1160 if (name.front() == 'C')
1161 if (name == "CFStringCreateWithFormat" ||
1162 name == "CFStringCreateWithFormatAndArguments" ||
1163 name == "CFStringAppendFormat" ||
1164 name == "CFStringAppendFormatAndArguments")
1165 return SFF_CFString;
1166 return SFF_None;
1167}
1168
1170 // We don't care about visibility here, so ask for the cheapest
1171 // possible visibility analysis.
1172 return LinkageComputer{}
1174 .getLinkage();
1175}
1176
1177/// Determine whether D is attached to a named module.
1178static bool isInNamedModule(const NamedDecl *D) {
1179 if (auto *M = D->getOwningModule())
1180 return M->isNamedModule();
1181 return false;
1182}
1183
1185 // FIXME: Handle isModulePrivate.
1186 switch (D->getModuleOwnershipKind()) {
1190 return false;
1193 return isInNamedModule(D);
1194 }
1195 llvm_unreachable("unexpected module ownership kind");
1196}
1197
1198/// Get the linkage from a semantic point of view. Entities in
1199/// anonymous namespaces are external (in c++98).
1201 Linkage InternalLinkage = getLinkageInternal();
1202
1203 // C++ [basic.link]p4.8:
1204 // - if the declaration of the name is attached to a named module and is not
1205 // exported
1206 // the name has module linkage;
1207 //
1208 // [basic.namespace.general]/p2
1209 // A namespace is never attached to a named module and never has a name with
1210 // module linkage.
1211 if (isInNamedModule(this) && InternalLinkage == Linkage::External &&
1213 cast<NamedDecl>(this->getCanonicalDecl())) &&
1214 !isa<NamespaceDecl>(this))
1215 InternalLinkage = Linkage::Module;
1216
1217 return clang::getFormalLinkage(InternalLinkage);
1218}
1219
1222}
1223
1224static std::optional<Visibility>
1227 bool IsMostRecent) {
1228 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1229
1230 // Check the declaration itself first.
1231 if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1232 return V;
1233
1234 // If this is a member class of a specialization of a class template
1235 // and the corresponding decl has explicit visibility, use that.
1236 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1237 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1238 if (InstantiatedFrom)
1239 return getVisibilityOf(InstantiatedFrom, kind);
1240 }
1241
1242 // If there wasn't explicit visibility there, and this is a
1243 // specialization of a class template, check for visibility
1244 // on the pattern.
1245 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1246 // Walk all the template decl till this point to see if there are
1247 // explicit visibility attributes.
1248 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1249 while (TD != nullptr) {
1250 auto Vis = getVisibilityOf(TD, kind);
1251 if (Vis != std::nullopt)
1252 return Vis;
1253 TD = TD->getPreviousDecl();
1254 }
1255 return std::nullopt;
1256 }
1257
1258 // Use the most recent declaration.
1259 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1260 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1261 if (MostRecent != ND)
1262 return getExplicitVisibilityAux(MostRecent, kind, true);
1263 }
1264
1265 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1266 if (Var->isStaticDataMember()) {
1267 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1268 if (InstantiatedFrom)
1269 return getVisibilityOf(InstantiatedFrom, kind);
1270 }
1271
1272 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1273 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1274 kind);
1275
1276 return std::nullopt;
1277 }
1278 // Also handle function template specializations.
1279 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1280 // If the function is a specialization of a template with an
1281 // explicit visibility attribute, use that.
1282 if (FunctionTemplateSpecializationInfo *templateInfo
1284 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1285 kind);
1286
1287 // If the function is a member of a specialization of a class template
1288 // and the corresponding decl has explicit visibility, use that.
1289 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1290 if (InstantiatedFrom)
1291 return getVisibilityOf(InstantiatedFrom, kind);
1292
1293 return std::nullopt;
1294 }
1295
1296 // The visibility of a template is stored in the templated decl.
1297 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1298 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1299
1300 return std::nullopt;
1301}
1302
1303std::optional<Visibility>
1305 return getExplicitVisibilityAux(this, kind, false);
1306}
1307
1308LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1309 Decl *ContextDecl,
1310 LVComputationKind computation) {
1311 // This lambda has its linkage/visibility determined by its owner.
1312 const NamedDecl *Owner;
1313 if (!ContextDecl)
1314 Owner = dyn_cast<NamedDecl>(DC);
1315 else if (isa<ParmVarDecl>(ContextDecl))
1316 Owner =
1317 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1318 else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1319 // Replace with the concept's owning decl, which is either a namespace or a
1320 // TU, so this needs a dyn_cast.
1321 Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1322 } else {
1323 Owner = cast<NamedDecl>(ContextDecl);
1324 }
1325
1326 if (!Owner)
1327 return LinkageInfo::none();
1328
1329 // If the owner has a deduced type, we need to skip querying the linkage and
1330 // visibility of that type, because it might involve this closure type. The
1331 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1332 // than NoLinkage when we don't strictly need to, which is benign.
1333 auto *VD = dyn_cast<VarDecl>(Owner);
1334 LinkageInfo OwnerLV =
1335 VD && VD->getType()->getContainedDeducedType()
1336 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1337 : getLVForDecl(Owner, computation);
1338
1339 // A lambda never formally has linkage. But if the owner is externally
1340 // visible, then the lambda is too. We apply the same rules to blocks.
1341 if (!isExternallyVisible(OwnerLV.getLinkage()))
1342 return LinkageInfo::none();
1344 OwnerLV.isVisibilityExplicit());
1345}
1346
1347LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1348 LVComputationKind computation) {
1349 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1350 if (Function->isInAnonymousNamespace() &&
1352 return LinkageInfo::internal();
1353
1354 // This is a "void f();" which got merged with a file static.
1355 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1356 return LinkageInfo::internal();
1357
1358 LinkageInfo LV;
1359 if (!hasExplicitVisibilityAlready(computation)) {
1360 if (std::optional<Visibility> Vis =
1361 getExplicitVisibility(Function, computation))
1362 LV.mergeVisibility(*Vis, true);
1363 }
1364
1365 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1366 // merging storage classes and visibility attributes, so we don't have to
1367 // look at previous decls in here.
1368
1369 return LV;
1370 }
1371
1372 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1373 if (Var->hasExternalStorage()) {
1374 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1375 return LinkageInfo::internal();
1376
1377 LinkageInfo LV;
1378 if (Var->getStorageClass() == SC_PrivateExtern)
1380 else if (!hasExplicitVisibilityAlready(computation)) {
1381 if (std::optional<Visibility> Vis =
1382 getExplicitVisibility(Var, computation))
1383 LV.mergeVisibility(*Vis, true);
1384 }
1385
1386 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1387 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1388 if (PrevLV.getLinkage() != Linkage::Invalid)
1389 LV.setLinkage(PrevLV.getLinkage());
1390 LV.mergeVisibility(PrevLV);
1391 }
1392
1393 return LV;
1394 }
1395
1396 if (!Var->isStaticLocal())
1397 return LinkageInfo::none();
1398 }
1399
1400 ASTContext &Context = D->getASTContext();
1401 if (!Context.getLangOpts().CPlusPlus)
1402 return LinkageInfo::none();
1403
1404 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1405 if (!OuterD || OuterD->isInvalidDecl())
1406 return LinkageInfo::none();
1407
1408 LinkageInfo LV;
1409 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1410 if (!BD->getBlockManglingNumber())
1411 return LinkageInfo::none();
1412
1413 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1414 BD->getBlockManglingContextDecl(), computation);
1415 } else {
1416 const auto *FD = cast<FunctionDecl>(OuterD);
1417 if (!FD->isInlined() &&
1418 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1419 return LinkageInfo::none();
1420
1421 // If a function is hidden by -fvisibility-inlines-hidden option and
1422 // is not explicitly attributed as a hidden function,
1423 // we should not make static local variables in the function hidden.
1424 LV = getLVForDecl(FD, computation);
1425 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1426 !LV.isVisibilityExplicit() &&
1427 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1428 assert(cast<VarDecl>(D)->isStaticLocal());
1429 // If this was an implicitly hidden inline method, check again for
1430 // explicit visibility on the parent class, and use that for static locals
1431 // if present.
1432 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1433 LV = getLVForDecl(MD->getParent(), computation);
1434 if (!LV.isVisibilityExplicit()) {
1435 Visibility globalVisibility =
1436 computation.isValueVisibility()
1437 ? Context.getLangOpts().getValueVisibilityMode()
1438 : Context.getLangOpts().getTypeVisibilityMode();
1439 return LinkageInfo(Linkage::VisibleNone, globalVisibility,
1440 /*visibilityExplicit=*/false);
1441 }
1442 }
1443 }
1445 return LinkageInfo::none();
1448}
1449
1451 LVComputationKind computation,
1452 bool IgnoreVarTypeLinkage) {
1453 // Internal_linkage attribute overrides other considerations.
1454 if (D->hasAttr<InternalLinkageAttr>())
1455 return LinkageInfo::internal();
1456
1457 // Objective-C: treat all Objective-C declarations as having external
1458 // linkage.
1459 switch (D->getKind()) {
1460 default:
1461 break;
1462
1463 // Per C++ [basic.link]p2, only the names of objects, references,
1464 // functions, types, templates, namespaces, and values ever have linkage.
1465 //
1466 // Note that the name of a typedef, namespace alias, using declaration,
1467 // and so on are not the name of the corresponding type, namespace, or
1468 // declaration, so they do *not* have linkage.
1469 case Decl::ImplicitParam:
1470 case Decl::Label:
1471 case Decl::NamespaceAlias:
1472 case Decl::ParmVar:
1473 case Decl::Using:
1474 case Decl::UsingEnum:
1475 case Decl::UsingShadow:
1476 case Decl::UsingDirective:
1477 return LinkageInfo::none();
1478
1479 case Decl::EnumConstant:
1480 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1481 if (D->getASTContext().getLangOpts().CPlusPlus)
1482 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1484
1485 case Decl::Typedef:
1486 case Decl::TypeAlias:
1487 // A typedef declaration has linkage if it gives a type a name for
1488 // linkage purposes.
1489 if (!cast<TypedefNameDecl>(D)
1490 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1491 return LinkageInfo::none();
1492 break;
1493
1494 case Decl::TemplateTemplateParm: // count these as external
1495 case Decl::NonTypeTemplateParm:
1496 case Decl::ObjCAtDefsField:
1497 case Decl::ObjCCategory:
1498 case Decl::ObjCCategoryImpl:
1499 case Decl::ObjCCompatibleAlias:
1500 case Decl::ObjCImplementation:
1501 case Decl::ObjCMethod:
1502 case Decl::ObjCProperty:
1503 case Decl::ObjCPropertyImpl:
1504 case Decl::ObjCProtocol:
1505 return getExternalLinkageFor(D);
1506
1507 case Decl::CXXRecord: {
1508 const auto *Record = cast<CXXRecordDecl>(D);
1509 if (Record->isLambda()) {
1510 if (Record->hasKnownLambdaInternalLinkage() ||
1511 !Record->getLambdaManglingNumber()) {
1512 // This lambda has no mangling number, so it's internal.
1513 return LinkageInfo::internal();
1514 }
1515
1516 return getLVForClosure(
1517 Record->getDeclContext()->getRedeclContext(),
1518 Record->getLambdaContextDecl(), computation);
1519 }
1520
1521 break;
1522 }
1523
1524 case Decl::TemplateParamObject: {
1525 // The template parameter object can be referenced from anywhere its type
1526 // and value can be referenced.
1527 auto *TPO = cast<TemplateParamObjectDecl>(D);
1528 LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1529 LV.merge(getLVForValue(TPO->getValue(), computation));
1530 return LV;
1531 }
1532 }
1533
1534 // Handle linkage for namespace-scope names.
1536 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1537
1538 // C++ [basic.link]p5:
1539 // In addition, a member function, static data member, a named
1540 // class or enumeration of class scope, or an unnamed class or
1541 // enumeration defined in a class-scope typedef declaration such
1542 // that the class or enumeration has the typedef name for linkage
1543 // purposes (7.1.3), has external linkage if the name of the class
1544 // has external linkage.
1545 if (D->getDeclContext()->isRecord())
1546 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1547
1548 // C++ [basic.link]p6:
1549 // The name of a function declared in block scope and the name of
1550 // an object declared by a block scope extern declaration have
1551 // linkage. If there is a visible declaration of an entity with
1552 // linkage having the same name and type, ignoring entities
1553 // declared outside the innermost enclosing namespace scope, the
1554 // block scope declaration declares that same entity and receives
1555 // the linkage of the previous declaration. If there is more than
1556 // one such matching entity, the program is ill-formed. Otherwise,
1557 // if no matching entity is found, the block scope entity receives
1558 // external linkage.
1560 return getLVForLocalDecl(D, computation);
1561
1562 // C++ [basic.link]p6:
1563 // Names not covered by these rules have no linkage.
1564 return LinkageInfo::none();
1565}
1566
1567/// getLVForDecl - Get the linkage and visibility for the given declaration.
1569 LVComputationKind computation) {
1570 // Internal_linkage attribute overrides other considerations.
1571 if (D->hasAttr<InternalLinkageAttr>())
1572 return LinkageInfo::internal();
1573
1574 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1575 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1576
1577 if (std::optional<LinkageInfo> LI = lookup(D, computation))
1578 return *LI;
1579
1580 LinkageInfo LV = computeLVForDecl(D, computation);
1581 if (D->hasCachedLinkage())
1582 assert(D->getCachedLinkage() == LV.getLinkage());
1583
1585 cache(D, computation, LV);
1586
1587#ifndef NDEBUG
1588 // In C (because of gnu inline) and in c++ with microsoft extensions an
1589 // static can follow an extern, so we can have two decls with different
1590 // linkages.
1591 const LangOptions &Opts = D->getASTContext().getLangOpts();
1592 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1593 return LV;
1594
1595 // We have just computed the linkage for this decl. By induction we know
1596 // that all other computed linkages match, check that the one we just
1597 // computed also does.
1598 NamedDecl *Old = nullptr;
1599 for (auto *I : D->redecls()) {
1600 auto *T = cast<NamedDecl>(I);
1601 if (T == D)
1602 continue;
1603 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1604 Old = T;
1605 break;
1606 }
1607 }
1608 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1609#endif
1610
1611 return LV;
1612}
1613
1618 LVComputationKind CK(EK);
1619 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1620 ? CK.forLinkageOnly()
1621 : CK);
1622}
1623
1624Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1625 if (isa<NamespaceDecl>(this))
1626 // Namespaces never have module linkage. It is the entities within them
1627 // that [may] do.
1628 return nullptr;
1629
1630 Module *M = getOwningModule();
1631 if (!M)
1632 return nullptr;
1633
1634 switch (M->Kind) {
1636 // Module map modules have no special linkage semantics.
1637 return nullptr;
1638
1643 return M;
1644
1648 // External linkage declarations in the global module have no owning module
1649 // for linkage purposes. But internal linkage declarations in the global
1650 // module fragment of a particular module are owned by that module for
1651 // linkage purposes.
1652 // FIXME: p1815 removes the need for this distinction -- there are no
1653 // internal linkage declarations that need to be referred to from outside
1654 // this TU.
1655 if (IgnoreLinkage)
1656 return nullptr;
1657 bool InternalLinkage;
1658 if (auto *ND = dyn_cast<NamedDecl>(this))
1659 InternalLinkage = !ND->hasExternalFormalLinkage();
1660 else
1661 InternalLinkage = isInAnonymousNamespace();
1662 return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : M->Parent
1663 : nullptr;
1664 }
1665
1667 // The private module fragment is part of its containing module for linkage
1668 // purposes.
1669 return M->Parent;
1670 }
1671
1672 llvm_unreachable("unknown module kind");
1673}
1674
1675void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1676 Name.print(OS, Policy);
1677}
1678
1679void NamedDecl::printName(raw_ostream &OS) const {
1680 printName(OS, getASTContext().getPrintingPolicy());
1681}
1682
1684 std::string QualName;
1685 llvm::raw_string_ostream OS(QualName);
1686 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1687 return QualName;
1688}
1689
1690void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1691 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1692}
1693
1695 const PrintingPolicy &P) const {
1697 // We do not print '(anonymous)' for function parameters without name.
1698 printName(OS, P);
1699 return;
1700 }
1702 if (getDeclName())
1703 OS << *this;
1704 else {
1705 // Give the printName override a chance to pick a different name before we
1706 // fall back to "(anonymous)".
1707 SmallString<64> NameBuffer;
1708 llvm::raw_svector_ostream NameOS(NameBuffer);
1709 printName(NameOS, P);
1710 if (NameBuffer.empty())
1711 OS << "(anonymous)";
1712 else
1713 OS << NameBuffer;
1714 }
1715}
1716
1717void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1718 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1719}
1720
1722 const PrintingPolicy &P) const {
1723 const DeclContext *Ctx = getDeclContext();
1724
1725 // For ObjC methods and properties, look through categories and use the
1726 // interface as context.
1727 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1728 if (auto *ID = MD->getClassInterface())
1729 Ctx = ID;
1730 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1731 if (auto *MD = PD->getGetterMethodDecl())
1732 if (auto *ID = MD->getClassInterface())
1733 Ctx = ID;
1734 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1735 if (auto *CI = ID->getContainingInterface())
1736 Ctx = CI;
1737 }
1738
1739 if (Ctx->isFunctionOrMethod())
1740 return;
1741
1742 using ContextsTy = SmallVector<const DeclContext *, 8>;
1743 ContextsTy Contexts;
1744
1745 // Collect named contexts.
1746 DeclarationName NameInScope = getDeclName();
1747 for (; Ctx; Ctx = Ctx->getParent()) {
1748 // Suppress anonymous namespace if requested.
1749 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1750 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1751 continue;
1752
1753 // Suppress inline namespace if it doesn't make the result ambiguous.
1754 if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1755 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1756 continue;
1757
1758 // Skip non-named contexts such as linkage specifications and ExportDecls.
1759 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1760 if (!ND)
1761 continue;
1762
1763 Contexts.push_back(Ctx);
1764 NameInScope = ND->getDeclName();
1765 }
1766
1767 for (const DeclContext *DC : llvm::reverse(Contexts)) {
1768 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1769 OS << Spec->getName();
1770 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1772 OS, TemplateArgs.asArray(), P,
1773 Spec->getSpecializedTemplate()->getTemplateParameters());
1774 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1775 if (ND->isAnonymousNamespace()) {
1776 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1777 : "(anonymous namespace)");
1778 }
1779 else
1780 OS << *ND;
1781 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1782 if (!RD->getIdentifier())
1783 OS << "(anonymous " << RD->getKindName() << ')';
1784 else
1785 OS << *RD;
1786 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1787 const FunctionProtoType *FT = nullptr;
1788 if (FD->hasWrittenPrototype())
1789 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1790
1791 OS << *FD << '(';
1792 if (FT) {
1793 unsigned NumParams = FD->getNumParams();
1794 for (unsigned i = 0; i < NumParams; ++i) {
1795 if (i)
1796 OS << ", ";
1797 OS << FD->getParamDecl(i)->getType().stream(P);
1798 }
1799
1800 if (FT->isVariadic()) {
1801 if (NumParams > 0)
1802 OS << ", ";
1803 OS << "...";
1804 }
1805 }
1806 OS << ')';
1807 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1808 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1809 // enumerator is declared in the scope that immediately contains
1810 // the enum-specifier. Each scoped enumerator is declared in the
1811 // scope of the enumeration.
1812 // For the case of unscoped enumerator, do not include in the qualified
1813 // name any information about its enum enclosing scope, as its visibility
1814 // is global.
1815 if (ED->isScoped())
1816 OS << *ED;
1817 else
1818 continue;
1819 } else {
1820 OS << *cast<NamedDecl>(DC);
1821 }
1822 OS << "::";
1823 }
1824}
1825
1827 const PrintingPolicy &Policy,
1828 bool Qualified) const {
1829 if (Qualified)
1830 printQualifiedName(OS, Policy);
1831 else
1832 printName(OS, Policy);
1833}
1834
1835template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1836 return true;
1837}
1838static bool isRedeclarableImpl(...) { return false; }
1840 switch (K) {
1841#define DECL(Type, Base) \
1842 case Decl::Type: \
1843 return isRedeclarableImpl((Type##Decl *)nullptr);
1844#define ABSTRACT_DECL(DECL)
1845#include "clang/AST/DeclNodes.inc"
1846 }
1847 llvm_unreachable("unknown decl kind");
1848}
1849
1851 bool IsKnownNewer) const {
1852 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1853
1854 // Never replace one imported declaration with another; we need both results
1855 // when re-exporting.
1856 if (OldD->isFromASTFile() && isFromASTFile())
1857 return false;
1858
1859 // A kind mismatch implies that the declaration is not replaced.
1860 if (OldD->getKind() != getKind())
1861 return false;
1862
1863 // For method declarations, we never replace. (Why?)
1864 if (isa<ObjCMethodDecl>(this))
1865 return false;
1866
1867 // For parameters, pick the newer one. This is either an error or (in
1868 // Objective-C) permitted as an extension.
1869 if (isa<ParmVarDecl>(this))
1870 return true;
1871
1872 // Inline namespaces can give us two declarations with the same
1873 // name and kind in the same scope but different contexts; we should
1874 // keep both declarations in this case.
1875 if (!this->getDeclContext()->getRedeclContext()->Equals(
1876 OldD->getDeclContext()->getRedeclContext()))
1877 return false;
1878
1879 // Using declarations can be replaced if they import the same name from the
1880 // same context.
1881 if (const auto *UD = dyn_cast<UsingDecl>(this)) {
1882 ASTContext &Context = getASTContext();
1883 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1885 cast<UsingDecl>(OldD)->getQualifier());
1886 }
1887 if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1888 ASTContext &Context = getASTContext();
1889 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1891 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1892 }
1893
1894 if (isRedeclarable(getKind())) {
1895 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1896 return false;
1897
1898 if (IsKnownNewer)
1899 return true;
1900
1901 // Check whether this is actually newer than OldD. We want to keep the
1902 // newer declaration. This loop will usually only iterate once, because
1903 // OldD is usually the previous declaration.
1904 for (const auto *D : redecls()) {
1905 if (D == OldD)
1906 break;
1907
1908 // If we reach the canonical declaration, then OldD is not actually older
1909 // than this one.
1910 //
1911 // FIXME: In this case, we should not add this decl to the lookup table.
1912 if (D->isCanonicalDecl())
1913 return false;
1914 }
1915
1916 // It's a newer declaration of the same kind of declaration in the same
1917 // scope: we want this decl instead of the existing one.
1918 return true;
1919 }
1920
1921 // In all other cases, we need to keep both declarations in case they have
1922 // different visibility. Any attempt to use the name will result in an
1923 // ambiguity if more than one is visible.
1924 return false;
1925}
1926
1928 switch (getFormalLinkage()) {
1929 case Linkage::Invalid:
1930 llvm_unreachable("Linkage hasn't been computed!");
1931 case Linkage::None:
1932 return false;
1933 case Linkage::Internal:
1934 return true;
1937 llvm_unreachable("Non-formal linkage is not allowed here!");
1938 case Linkage::Module:
1939 case Linkage::External:
1940 return true;
1941 }
1942 llvm_unreachable("Unhandled Linkage enum");
1943}
1944
1945NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1946 NamedDecl *ND = this;
1947 if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1948 ND = UD->getTargetDecl();
1949
1950 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1951 return AD->getClassInterface();
1952
1953 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1954 return AD->getNamespace();
1955
1956 return ND;
1957}
1958
1960 if (!isCXXClassMember())
1961 return false;
1962
1963 const NamedDecl *D = this;
1964 if (isa<UsingShadowDecl>(D))
1965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1966
1967 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1968 return true;
1969 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))
1970 return MD->isInstance();
1971 return false;
1972}
1973
1974//===----------------------------------------------------------------------===//
1975// DeclaratorDecl Implementation
1976//===----------------------------------------------------------------------===//
1977
1978template <typename DeclT>
1980 if (decl->getNumTemplateParameterLists() > 0)
1981 return decl->getTemplateParameterList(0)->getTemplateLoc();
1982 return decl->getInnerLocStart();
1983}
1984
1987 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1988 return SourceLocation();
1989}
1990
1993 if (TSI) return TSI->getTypeLoc().getEndLoc();
1994 return SourceLocation();
1995}
1996
1998 if (QualifierLoc) {
1999 // Make sure the extended decl info is allocated.
2000 if (!hasExtInfo()) {
2001 // Save (non-extended) type source info pointer.
2002 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2003 // Allocate external info struct.
2004 DeclInfo = new (getASTContext()) ExtInfo;
2005 // Restore savedTInfo into (extended) decl info.
2006 getExtInfo()->TInfo = savedTInfo;
2007 }
2008 // Set qualifier info.
2009 getExtInfo()->QualifierLoc = QualifierLoc;
2010 } else if (hasExtInfo()) {
2011 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2012 getExtInfo()->QualifierLoc = QualifierLoc;
2013 }
2014}
2015
2017 assert(TrailingRequiresClause);
2018 // Make sure the extended decl info is allocated.
2019 if (!hasExtInfo()) {
2020 // Save (non-extended) type source info pointer.
2021 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2022 // Allocate external info struct.
2023 DeclInfo = new (getASTContext()) ExtInfo;
2024 // Restore savedTInfo into (extended) decl info.
2025 getExtInfo()->TInfo = savedTInfo;
2026 }
2027 // Set requires clause info.
2028 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
2029}
2030
2033 assert(!TPLists.empty());
2034 // Make sure the extended decl info is allocated.
2035 if (!hasExtInfo()) {
2036 // Save (non-extended) type source info pointer.
2037 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2038 // Allocate external info struct.
2039 DeclInfo = new (getASTContext()) ExtInfo;
2040 // Restore savedTInfo into (extended) decl info.
2041 getExtInfo()->TInfo = savedTInfo;
2042 }
2043 // Set the template parameter lists info.
2044 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
2045}
2046
2048 return getTemplateOrInnerLocStart(this);
2049}
2050
2051// Helper function: returns true if QT is or contains a type
2052// having a postfix component.
2053static bool typeIsPostfix(QualType QT) {
2054 while (true) {
2055 const Type* T = QT.getTypePtr();
2056 switch (T->getTypeClass()) {
2057 default:
2058 return false;
2059 case Type::Pointer:
2060 QT = cast<PointerType>(T)->getPointeeType();
2061 break;
2062 case Type::BlockPointer:
2063 QT = cast<BlockPointerType>(T)->getPointeeType();
2064 break;
2065 case Type::MemberPointer:
2066 QT = cast<MemberPointerType>(T)->getPointeeType();
2067 break;
2068 case Type::LValueReference:
2069 case Type::RValueReference:
2070 QT = cast<ReferenceType>(T)->getPointeeType();
2071 break;
2072 case Type::PackExpansion:
2073 QT = cast<PackExpansionType>(T)->getPattern();
2074 break;
2075 case Type::Paren:
2076 case Type::ConstantArray:
2077 case Type::DependentSizedArray:
2078 case Type::IncompleteArray:
2079 case Type::VariableArray:
2080 case Type::FunctionProto:
2081 case Type::FunctionNoProto:
2082 return true;
2083 }
2084 }
2085}
2086
2088 SourceLocation RangeEnd = getLocation();
2089 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2090 // If the declaration has no name or the type extends past the name take the
2091 // end location of the type.
2092 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2093 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2094 }
2095 return SourceRange(getOuterLocStart(), RangeEnd);
2096}
2097
2100 // Free previous template parameters (if any).
2101 if (NumTemplParamLists > 0) {
2102 Context.Deallocate(TemplParamLists);
2103 TemplParamLists = nullptr;
2105 }
2106 // Set info on matched template parameter lists (if any).
2107 if (!TPLists.empty()) {
2108 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2109 NumTemplParamLists = TPLists.size();
2110 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2111 }
2112}
2113
2114//===----------------------------------------------------------------------===//
2115// VarDecl Implementation
2116//===----------------------------------------------------------------------===//
2117
2119 switch (SC) {
2120 case SC_None: break;
2121 case SC_Auto: return "auto";
2122 case SC_Extern: return "extern";
2123 case SC_PrivateExtern: return "__private_extern__";
2124 case SC_Register: return "register";
2125 case SC_Static: return "static";
2126 }
2127
2128 llvm_unreachable("Invalid storage class");
2129}
2130
2132 SourceLocation StartLoc, SourceLocation IdLoc,
2133 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2134 StorageClass SC)
2135 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2137 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2138 "VarDeclBitfields too large!");
2139 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2140 "ParmVarDeclBitfields too large!");
2141 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2142 "NonParmVarDeclBitfields too large!");
2143 AllBits = 0;
2144 VarDeclBits.SClass = SC;
2145 // Everything else is implicitly initialized to false.
2146}
2147
2149 SourceLocation IdL, const IdentifierInfo *Id,
2151 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2152}
2153
2155 return new (C, ID)
2156 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2157 QualType(), nullptr, SC_None);
2158}
2159
2161 assert(isLegalForVariable(SC));
2162 VarDeclBits.SClass = SC;
2163}
2164
2166 switch (VarDeclBits.TSCSpec) {
2167 case TSCS_unspecified:
2168 if (!hasAttr<ThreadAttr>() &&
2169 !(getASTContext().getLangOpts().OpenMPUseTLS &&
2170 getASTContext().getTargetInfo().isTLSSupported() &&
2171 hasAttr<OMPThreadPrivateDeclAttr>()))
2172 return TLS_None;
2173 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2175 hasAttr<OMPThreadPrivateDeclAttr>())
2176 ? TLS_Dynamic
2177 : TLS_Static;
2178 case TSCS___thread: // Fall through.
2179 case TSCS__Thread_local:
2180 return TLS_Static;
2181 case TSCS_thread_local:
2182 return TLS_Dynamic;
2183 }
2184 llvm_unreachable("Unknown thread storage class specifier!");
2185}
2186
2188 if (const Expr *Init = getInit()) {
2189 SourceLocation InitEnd = Init->getEndLoc();
2190 // If Init is implicit, ignore its source range and fallback on
2191 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2192 if (InitEnd.isValid() && InitEnd != getLocation())
2193 return SourceRange(getOuterLocStart(), InitEnd);
2194 }
2196}
2197
2198template<typename T>
2200 // C++ [dcl.link]p1: All function types, function names with external linkage,
2201 // and variable names with external linkage have a language linkage.
2202 if (!D.hasExternalFormalLinkage())
2203 return NoLanguageLinkage;
2204
2205 // Language linkage is a C++ concept, but saying that everything else in C has
2206 // C language linkage fits the implementation nicely.
2207 if (!D.getASTContext().getLangOpts().CPlusPlus)
2208 return CLanguageLinkage;
2209
2210 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2211 // language linkage of the names of class members and the function type of
2212 // class member functions.
2213 const DeclContext *DC = D.getDeclContext();
2214 if (DC->isRecord())
2215 return CXXLanguageLinkage;
2216
2217 // If the first decl is in an extern "C" context, any other redeclaration
2218 // will have C language linkage. If the first one is not in an extern "C"
2219 // context, we would have reported an error for any other decl being in one.
2221 return CLanguageLinkage;
2222 return CXXLanguageLinkage;
2223}
2224
2225template<typename T>
2226static bool isDeclExternC(const T &D) {
2227 // Since the context is ignored for class members, they can only have C++
2228 // language linkage or no language linkage.
2229 const DeclContext *DC = D.getDeclContext();
2230 if (DC->isRecord()) {
2231 assert(D.getASTContext().getLangOpts().CPlusPlus);
2232 return false;
2233 }
2234
2235 return D.getLanguageLinkage() == CLanguageLinkage;
2236}
2237
2239 return getDeclLanguageLinkage(*this);
2240}
2241
2243 return isDeclExternC(*this);
2244}
2245
2248}
2249
2252}
2253
2255
2259 return DeclarationOnly;
2260
2261 // C++ [basic.def]p2:
2262 // A declaration is a definition unless [...] it contains the 'extern'
2263 // specifier or a linkage-specification and neither an initializer [...],
2264 // it declares a non-inline static data member in a class declaration [...],
2265 // it declares a static data member outside a class definition and the variable
2266 // was defined within the class with the constexpr specifier [...],
2267 // C++1y [temp.expl.spec]p15:
2268 // An explicit specialization of a static data member or an explicit
2269 // specialization of a static data member template is a definition if the
2270 // declaration includes an initializer; otherwise, it is a declaration.
2271 //
2272 // FIXME: How do you declare (but not define) a partial specialization of
2273 // a static data member template outside the containing class?
2274 if (isStaticDataMember()) {
2275 if (isOutOfLine() &&
2276 !(getCanonicalDecl()->isInline() &&
2278 (hasInit() ||
2279 // If the first declaration is out-of-line, this may be an
2280 // instantiation of an out-of-line partial specialization of a variable
2281 // template for which we have not yet instantiated the initializer.
2286 isa<VarTemplatePartialSpecializationDecl>(this)))
2287 return Definition;
2288 if (!isOutOfLine() && isInline())
2289 return Definition;
2290 return DeclarationOnly;
2291 }
2292 // C99 6.7p5:
2293 // A definition of an identifier is a declaration for that identifier that
2294 // [...] causes storage to be reserved for that object.
2295 // Note: that applies for all non-file-scope objects.
2296 // C99 6.9.2p1:
2297 // If the declaration of an identifier for an object has file scope and an
2298 // initializer, the declaration is an external definition for the identifier
2299 if (hasInit())
2300 return Definition;
2301
2302 if (hasDefiningAttr())
2303 return Definition;
2304
2305 if (const auto *SAA = getAttr<SelectAnyAttr>())
2306 if (!SAA->isInherited())
2307 return Definition;
2308
2309 // A variable template specialization (other than a static data member
2310 // template or an explicit specialization) is a declaration until we
2311 // instantiate its initializer.
2312 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2313 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2314 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2315 !VTSD->IsCompleteDefinition)
2316 return DeclarationOnly;
2317 }
2318
2319 if (hasExternalStorage())
2320 return DeclarationOnly;
2321
2322 // [dcl.link] p7:
2323 // A declaration directly contained in a linkage-specification is treated
2324 // as if it contains the extern specifier for the purpose of determining
2325 // the linkage of the declared name and whether it is a definition.
2326 if (isSingleLineLanguageLinkage(*this))
2327 return DeclarationOnly;
2328
2329 // C99 6.9.2p2:
2330 // A declaration of an object that has file scope without an initializer,
2331 // and without a storage class specifier or the scs 'static', constitutes
2332 // a tentative definition.
2333 // No such thing in C++.
2334 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2335 return TentativeDefinition;
2336
2337 // What's left is (in C, block-scope) declarations without initializers or
2338 // external storage. These are definitions.
2339 return Definition;
2340}
2341
2345 return nullptr;
2346
2347 VarDecl *LastTentative = nullptr;
2348
2349 // Loop through the declaration chain, starting with the most recent.
2351 Decl = Decl->getPreviousDecl()) {
2352 Kind = Decl->isThisDeclarationADefinition();
2353 if (Kind == Definition)
2354 return nullptr;
2355 // Record the first (most recent) TentativeDefinition that is encountered.
2356 if (Kind == TentativeDefinition && !LastTentative)
2357 LastTentative = Decl;
2358 }
2359
2360 return LastTentative;
2361}
2362
2365 for (auto *I : First->redecls()) {
2366 if (I->isThisDeclarationADefinition(C) == Definition)
2367 return I;
2368 }
2369 return nullptr;
2370}
2371
2374
2375 const VarDecl *First = getFirstDecl();
2376 for (auto *I : First->redecls()) {
2377 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2378 if (Kind == Definition)
2379 break;
2380 }
2381
2382 return Kind;
2383}
2384
2385const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2386 for (auto *I : redecls()) {
2387 if (auto Expr = I->getInit()) {
2388 D = I;
2389 return Expr;
2390 }
2391 }
2392 return nullptr;
2393}
2394
2395bool VarDecl::hasInit() const {
2396 if (auto *P = dyn_cast<ParmVarDecl>(this))
2397 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2398 return false;
2399
2400 return !Init.isNull();
2401}
2402
2404 if (!hasInit())
2405 return nullptr;
2406
2407 if (auto *S = Init.dyn_cast<Stmt *>())
2408 return cast<Expr>(S);
2409
2410 auto *Eval = getEvaluatedStmt();
2411 return cast<Expr>(Eval->Value.isOffset()
2412 ? Eval->Value.get(getASTContext().getExternalSource())
2413 : Eval->Value.get(nullptr));
2414}
2415
2417 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2418 return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2419
2420 return Init.getAddrOfPtr1();
2421}
2422
2424 VarDecl *Def = nullptr;
2425 for (auto *I : redecls()) {
2426 if (I->hasInit())
2427 return I;
2428
2429 if (I->isThisDeclarationADefinition()) {
2430 if (isStaticDataMember())
2431 return I;
2432 Def = I;
2433 }
2434 }
2435 return Def;
2436}
2437
2439 if (Decl::isOutOfLine())
2440 return true;
2441
2442 if (!isStaticDataMember())
2443 return false;
2444
2445 // If this static data member was instantiated from a static data member of
2446 // a class template, check whether that static data member was defined
2447 // out-of-line.
2449 return VD->isOutOfLine();
2450
2451 return false;
2452}
2453
2455 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2456 Eval->~EvaluatedStmt();
2457 getASTContext().Deallocate(Eval);
2458 }
2459
2460 Init = I;
2461}
2462
2464 const LangOptions &Lang = C.getLangOpts();
2465
2466 // OpenCL permits const integral variables to be used in constant
2467 // expressions, like in C++98.
2468 if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2469 return false;
2470
2471 // Function parameters are never usable in constant expressions.
2472 if (isa<ParmVarDecl>(this))
2473 return false;
2474
2475 // The values of weak variables are never usable in constant expressions.
2476 if (isWeak())
2477 return false;
2478
2479 // In C++11, any variable of reference type can be used in a constant
2480 // expression if it is initialized by a constant expression.
2481 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2482 return true;
2483
2484 // Only const objects can be used in constant expressions in C++. C++98 does
2485 // not require the variable to be non-volatile, but we consider this to be a
2486 // defect.
2487 if (!getType().isConstant(C) || getType().isVolatileQualified())
2488 return false;
2489
2490 // In C++, but not in C, const, non-volatile variables of integral or
2491 // enumeration types can be used in constant expressions.
2492 if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2493 return true;
2494
2495 // C23 6.6p7: An identifier that is:
2496 // ...
2497 // - declared with storage-class specifier constexpr and has an object type,
2498 // is a named constant, ... such a named constant is a constant expression
2499 // with the type and value of the declared object.
2500 // Additionally, in C++11, non-volatile constexpr variables can be used in
2501 // constant expressions.
2502 return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2503}
2504
2506 // C++2a [expr.const]p3:
2507 // A variable is usable in constant expressions after its initializing
2508 // declaration is encountered...
2509 const VarDecl *DefVD = nullptr;
2510 const Expr *Init = getAnyInitializer(DefVD);
2511 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2512 return false;
2513 // ... if it is a constexpr variable, or it is of reference type or of
2514 // const-qualified integral or enumeration type, ...
2515 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2516 return false;
2517 // ... and its initializer is a constant initializer.
2518 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2519 return false;
2520 // C++98 [expr.const]p1:
2521 // An integral constant-expression can involve only [...] const variables
2522 // or static data members of integral or enumeration types initialized with
2523 // [integer] constant expressions (dcl.init)
2524 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2525 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2526 return false;
2527 return true;
2528}
2529
2530/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2531/// form, which contains extra information on the evaluated value of the
2532/// initializer.
2534 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2535 if (!Eval) {
2536 // Note: EvaluatedStmt contains an APValue, which usually holds
2537 // resources not allocated from the ASTContext. We need to do some
2538 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2539 // where we can detect whether there's anything to clean up or not.
2540 Eval = new (getASTContext()) EvaluatedStmt;
2541 Eval->Value = Init.get<Stmt *>();
2542 Init = Eval;
2543 }
2544 return Eval;
2545}
2546
2548 return Init.dyn_cast<EvaluatedStmt *>();
2549}
2550
2553 return evaluateValueImpl(Notes, hasConstantInitialization());
2554}
2555
2556APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2557 bool IsConstantInitialization) const {
2559
2560 const auto *Init = getInit();
2561 assert(!Init->isValueDependent());
2562
2563 // We only produce notes indicating why an initializer is non-constant the
2564 // first time it is evaluated. FIXME: The notes won't always be emitted the
2565 // first time we try evaluation, so might not be produced at all.
2566 if (Eval->WasEvaluated)
2567 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2568
2569 if (Eval->IsEvaluating) {
2570 // FIXME: Produce a diagnostic for self-initialization.
2571 return nullptr;
2572 }
2573
2574 Eval->IsEvaluating = true;
2575
2576 ASTContext &Ctx = getASTContext();
2577 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2578 IsConstantInitialization);
2579
2580 // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2581 // a constant initializer if we produced notes. In that case, we can't keep
2582 // the result, because it may only be correct under the assumption that the
2583 // initializer is a constant context.
2584 if (IsConstantInitialization &&
2585 (Ctx.getLangOpts().CPlusPlus ||
2586 (isConstexpr() && Ctx.getLangOpts().C23)) &&
2587 !Notes.empty())
2588 Result = false;
2589
2590 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2591 // or that it's empty (so that there's nothing to clean up) if evaluation
2592 // failed.
2593 if (!Result)
2594 Eval->Evaluated = APValue();
2595 else if (Eval->Evaluated.needsCleanup())
2596 Ctx.addDestruction(&Eval->Evaluated);
2597
2598 Eval->IsEvaluating = false;
2599 Eval->WasEvaluated = true;
2600
2601 return Result ? &Eval->Evaluated : nullptr;
2602}
2603
2605 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2606 if (Eval->WasEvaluated)
2607 return &Eval->Evaluated;
2608
2609 return nullptr;
2610}
2611
2612bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2613 const Expr *Init = getInit();
2614 assert(Init && "no initializer");
2615
2617 if (!Eval->CheckedForICEInit) {
2618 Eval->CheckedForICEInit = true;
2619 Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2620 }
2621 return Eval->HasICEInit;
2622}
2623
2625 // In C, all globals (and only globals) have constant initialization.
2627 return true;
2628
2629 // In C++, it depends on whether the evaluation at the point of definition
2630 // was evaluatable as a constant initializer.
2631 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2632 return Eval->HasConstantInitialization;
2633
2634 return false;
2635}
2636
2640 // If we ask for the value before we know whether we have a constant
2641 // initializer, we can compute the wrong value (for example, due to
2642 // std::is_constant_evaluated()).
2643 assert(!Eval->WasEvaluated &&
2644 "already evaluated var value before checking for constant init");
2645 assert((getASTContext().getLangOpts().CPlusPlus ||
2647 "only meaningful in C++/C23");
2648
2649 assert(!getInit()->isValueDependent());
2650
2651 // Evaluate the initializer to check whether it's a constant expression.
2653 evaluateValueImpl(Notes, true) && Notes.empty();
2654
2655 // If evaluation as a constant initializer failed, allow re-evaluation as a
2656 // non-constant initializer if we later find we want the value.
2657 if (!Eval->HasConstantInitialization)
2658 Eval->WasEvaluated = false;
2659
2660 return Eval->HasConstantInitialization;
2661}
2662
2664 return isa<PackExpansionType>(getType());
2665}
2666
2667template<typename DeclT>
2668static DeclT *getDefinitionOrSelf(DeclT *D) {
2669 assert(D);
2670 if (auto *Def = D->getDefinition())
2671 return Def;
2672 return D;
2673}
2674
2676 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2677}
2678
2680 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2681}
2682
2684 QualType T = getType();
2685 return T->isDependentType() || T->isUndeducedType() ||
2686 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2687 return AA->isAlignmentDependent();
2688 });
2689}
2690
2692 const VarDecl *VD = this;
2693
2694 // If this is an instantiated member, walk back to the template from which
2695 // it was instantiated.
2697 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2699 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2700 VD = NewVD;
2701 }
2702 }
2703
2704 // If it's an instantiated variable template specialization, find the
2705 // template or partial specialization from which it was instantiated.
2706 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2707 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2708 auto From = VDTemplSpec->getInstantiatedFrom();
2709 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2710 while (!VTD->isMemberSpecialization()) {
2711 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2712 if (!NewVTD)
2713 break;
2714 VTD = NewVTD;
2715 }
2716 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2717 }
2718 if (auto *VTPSD =
2719 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2720 while (!VTPSD->isMemberSpecialization()) {
2721 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2722 if (!NewVTPSD)
2723 break;
2724 VTPSD = NewVTPSD;
2725 }
2726 return getDefinitionOrSelf<VarDecl>(VTPSD);
2727 }
2728 }
2729 }
2730
2731 // If this is the pattern of a variable template, find where it was
2732 // instantiated from. FIXME: Is this necessary?
2733 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2734 while (!VarTemplate->isMemberSpecialization()) {
2735 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2736 if (!NewVT)
2737 break;
2738 VarTemplate = NewVT;
2739 }
2740
2741 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2742 }
2743
2744 if (VD == this)
2745 return nullptr;
2746 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2747}
2748
2751 return cast<VarDecl>(MSI->getInstantiatedFrom());
2752
2753 return nullptr;
2754}
2755
2757 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2758 return Spec->getSpecializationKind();
2759
2761 return MSI->getTemplateSpecializationKind();
2762
2763 return TSK_Undeclared;
2764}
2765
2769 return MSI->getTemplateSpecializationKind();
2770
2771 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2772 return Spec->getSpecializationKind();
2773
2774 return TSK_Undeclared;
2775}
2776
2778 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2779 return Spec->getPointOfInstantiation();
2780
2782 return MSI->getPointOfInstantiation();
2783
2784 return SourceLocation();
2785}
2786
2789 .dyn_cast<VarTemplateDecl *>();
2790}
2791
2794}
2795
2797 const auto &LangOpts = getASTContext().getLangOpts();
2798 // In CUDA mode without relocatable device code, variables of form 'extern
2799 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2800 // memory pool. These are never undefined variables, even if they appear
2801 // inside of an anon namespace or static function.
2802 //
2803 // With CUDA relocatable device code enabled, these variables don't get
2804 // special handling; they're treated like regular extern variables.
2805 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2806 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2807 isa<IncompleteArrayType>(getType()))
2808 return true;
2809
2810 return hasDefinition();
2811}
2812
2813bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2814 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2815 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2816 !hasAttr<AlwaysDestroyAttr>()));
2817}
2818
2821 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2822 if (Eval->HasConstantDestruction)
2823 return QualType::DK_none;
2824
2825 if (isNoDestroy(Ctx))
2826 return QualType::DK_none;
2827
2828 return getType().isDestructedType();
2829}
2830
2832 assert(hasInit() && "Expect initializer to check for flexible array init");
2833 auto *Ty = getType()->getAs<RecordType>();
2834 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2835 return false;
2836 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2837 if (!List)
2838 return false;
2839 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2840 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2841 if (!InitTy)
2842 return false;
2843 return !InitTy->isZeroSize();
2844}
2845
2847 assert(hasInit() && "Expect initializer to check for flexible array init");
2848 auto *Ty = getType()->getAs<RecordType>();
2849 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2850 return CharUnits::Zero();
2851 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2852 if (!List || List->getNumInits() == 0)
2853 return CharUnits::Zero();
2854 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2855 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2856 if (!InitTy)
2857 return CharUnits::Zero();
2858 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2859 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2860 CharUnits FlexibleArrayOffset =
2862 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2863 return CharUnits::Zero();
2864 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2865}
2866
2868 if (isStaticDataMember())
2869 // FIXME: Remove ?
2870 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2872 .dyn_cast<MemberSpecializationInfo *>();
2873 return nullptr;
2874}
2875
2877 SourceLocation PointOfInstantiation) {
2878 assert((isa<VarTemplateSpecializationDecl>(this) ||
2880 "not a variable or static data member template specialization");
2881
2883 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2884 Spec->setSpecializationKind(TSK);
2885 if (TSK != TSK_ExplicitSpecialization &&
2886 PointOfInstantiation.isValid() &&
2887 Spec->getPointOfInstantiation().isInvalid()) {
2888 Spec->setPointOfInstantiation(PointOfInstantiation);
2890 L->InstantiationRequested(this);
2891 }
2893 MSI->setTemplateSpecializationKind(TSK);
2894 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2895 MSI->getPointOfInstantiation().isInvalid()) {
2896 MSI->setPointOfInstantiation(PointOfInstantiation);
2898 L->InstantiationRequested(this);
2899 }
2900 }
2901}
2902
2903void
2906 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2907 "Previous template or instantiation?");
2909}
2910
2911//===----------------------------------------------------------------------===//
2912// ParmVarDecl Implementation
2913//===----------------------------------------------------------------------===//
2914
2916 SourceLocation StartLoc, SourceLocation IdLoc,
2917 const IdentifierInfo *Id, QualType T,
2918 TypeSourceInfo *TInfo, StorageClass S,
2919 Expr *DefArg) {
2920 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2921 S, DefArg);
2922}
2923
2926 QualType T = TSI ? TSI->getType() : getType();
2927 if (const auto *DT = dyn_cast<DecayedType>(T))
2928 return DT->getOriginalType();
2929 return T;
2930}
2931
2933 return new (C, ID)
2934 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2935 nullptr, QualType(), nullptr, SC_None, nullptr);
2936}
2937
2939 if (!hasInheritedDefaultArg()) {
2940 SourceRange ArgRange = getDefaultArgRange();
2941 if (ArgRange.isValid())
2942 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2943 }
2944
2945 // DeclaratorDecl considers the range of postfix types as overlapping with the
2946 // declaration name, but this is not the case with parameters in ObjC methods.
2947 if (isa<ObjCMethodDecl>(getDeclContext()))
2949
2951}
2952
2954 // ns_consumed only affects code generation in ARC
2955 if (hasAttr<NSConsumedAttr>())
2956 return getASTContext().getLangOpts().ObjCAutoRefCount;
2957
2958 // FIXME: isParamDestroyedInCallee() should probably imply
2959 // isDestructedType()
2960 const auto *RT = getType()->getAs<RecordType>();
2961 if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2963 return true;
2964
2965 return false;
2966}
2967
2969 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2970 assert(!hasUninstantiatedDefaultArg() &&
2971 "Default argument is not yet instantiated!");
2972
2973 Expr *Arg = getInit();
2974 if (auto *E = dyn_cast_if_present<FullExpr>(Arg))
2975 return E->getSubExpr();
2976
2977 return Arg;
2978}
2979
2981 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2982 Init = defarg;
2983}
2984
2986 switch (ParmVarDeclBits.DefaultArgKind) {
2987 case DAK_None:
2988 case DAK_Unparsed:
2989 // Nothing we can do here.
2990 return SourceRange();
2991
2992 case DAK_Uninstantiated:
2994
2995 case DAK_Normal:
2996 if (const Expr *E = getInit())
2997 return E->getSourceRange();
2998
2999 // Missing an actual expression, may be invalid.
3000 return SourceRange();
3001 }
3002 llvm_unreachable("Invalid default argument kind.");
3003}
3004
3006 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
3007 Init = arg;
3008}
3009
3011 assert(hasUninstantiatedDefaultArg() &&
3012 "Wrong kind of initialization expression!");
3013 return cast_if_present<Expr>(Init.get<Stmt *>());
3014}
3015
3017 // FIXME: We should just return false for DAK_None here once callers are
3018 // prepared for the case that we encountered an invalid default argument and
3019 // were unable to even build an invalid expression.
3021 !Init.isNull();
3022}
3023
3024void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3025 getASTContext().setParameterIndex(this, parameterIndex);
3026 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3027}
3028
3029unsigned ParmVarDecl::getParameterIndexLarge() const {
3030 return getASTContext().getParameterIndex(this);
3031}
3032
3033//===----------------------------------------------------------------------===//
3034// FunctionDecl Implementation
3035//===----------------------------------------------------------------------===//
3036
3038 SourceLocation StartLoc,
3039 const DeclarationNameInfo &NameInfo, QualType T,
3040 TypeSourceInfo *TInfo, StorageClass S,
3041 bool UsesFPIntrin, bool isInlineSpecified,
3042 ConstexprSpecKind ConstexprKind,
3043 Expr *TrailingRequiresClause)
3044 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3045 StartLoc),
3046 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3047 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3048 assert(T.isNull() || T->isFunctionType());
3049 FunctionDeclBits.SClass = S;
3051 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3052 FunctionDeclBits.IsVirtualAsWritten = false;
3053 FunctionDeclBits.IsPureVirtual = false;
3054 FunctionDeclBits.HasInheritedPrototype = false;
3055 FunctionDeclBits.HasWrittenPrototype = true;
3056 FunctionDeclBits.IsDeleted = false;
3057 FunctionDeclBits.IsTrivial = false;
3058 FunctionDeclBits.IsTrivialForCall = false;
3059 FunctionDeclBits.IsDefaulted = false;
3060 FunctionDeclBits.IsExplicitlyDefaulted = false;
3061 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3062 FunctionDeclBits.IsIneligibleOrNotSelected = false;
3063 FunctionDeclBits.HasImplicitReturnZero = false;
3064 FunctionDeclBits.IsLateTemplateParsed = false;
3065 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3066 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3067 FunctionDeclBits.InstantiationIsPending = false;
3068 FunctionDeclBits.UsesSEHTry = false;
3069 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3070 FunctionDeclBits.HasSkippedBody = false;
3071 FunctionDeclBits.WillHaveBody = false;
3072 FunctionDeclBits.IsMultiVersion = false;
3073 FunctionDeclBits.DeductionCandidateKind =
3074 static_cast<unsigned char>(DeductionCandidate::Normal);
3075 FunctionDeclBits.HasODRHash = false;
3076 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3077 if (TrailingRequiresClause)
3078 setTrailingRequiresClause(TrailingRequiresClause);
3079}
3080
3082 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3085 if (TemplateArgs)
3086 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3087}
3088
3090 if (const auto *FT = getType()->getAs<FunctionProtoType>())
3091 return FT->isVariadic();
3092 return false;
3093}
3094
3097 ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3098 StringLiteral *DeletedMessage) {
3099 static constexpr size_t Alignment =
3100 std::max({alignof(DefaultedOrDeletedFunctionInfo),
3101 alignof(DeclAccessPair), alignof(StringLiteral *)});
3102 size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3103 Lookups.size(), DeletedMessage != nullptr);
3104
3106 new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;
3107 Info->NumLookups = Lookups.size();
3108 Info->HasDeletedMessage = DeletedMessage != nullptr;
3109
3110 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3111 Info->getTrailingObjects<DeclAccessPair>());
3112 if (DeletedMessage)
3113 *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3114 return Info;
3115}
3116
3119 assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3120 assert(!Body && "can't replace function body with defaulted function info");
3121
3122 FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3124}
3125
3127 FunctionDeclBits.IsDeleted = D;
3128
3129 if (Message) {
3130 assert(isDeletedAsWritten() && "Function must be deleted");
3131 if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3133 else
3135 getASTContext(), /*Lookups=*/{}, Message));
3136 }
3137}
3138
3140 StringLiteral *Message) {
3141 // We should never get here with the DefaultedOrDeletedInfo populated, but
3142 // no space allocated for the deleted message, since that would require
3143 // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3144 // an already existing DefaultedOrDeletedFunctionInfo.
3145 assert(HasDeletedMessage &&
3146 "No space to store a delete message in this DefaultedOrDeletedInfo");
3147 *getTrailingObjects<StringLiteral *>() = Message;
3148}
3149
3152 return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3153 : nullptr;
3154}
3155
3157 for (const auto *I : redecls()) {
3158 if (I->doesThisDeclarationHaveABody()) {
3159 Definition = I;
3160 return true;
3161 }
3162 }
3163
3164 return false;
3165}
3166
3168 const Stmt *S = getBody();
3169 if (!S) {
3170 // Since we don't have a body for this function, we don't know if it's
3171 // trivial or not.
3172 return false;
3173 }
3174
3175 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3176 return true;
3177 return false;
3178}
3179
3181 if (!getFriendObjectKind())
3182 return false;
3183
3184 // Check for a friend function instantiated from a friend function
3185 // definition in a templated class.
3186 if (const FunctionDecl *InstantiatedFrom =
3188 return InstantiatedFrom->getFriendObjectKind() &&
3189 InstantiatedFrom->isThisDeclarationADefinition();
3190
3191 // Check for a friend function template instantiated from a friend
3192 // function template definition in a templated class.
3193 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3194 if (const FunctionTemplateDecl *InstantiatedFrom =
3196 return InstantiatedFrom->getFriendObjectKind() &&
3197 InstantiatedFrom->isThisDeclarationADefinition();
3198 }
3199
3200 return false;
3201}
3202
3204 bool CheckForPendingFriendDefinition) const {
3205 for (const FunctionDecl *FD : redecls()) {
3206 if (FD->isThisDeclarationADefinition()) {
3207 Definition = FD;
3208 return true;
3209 }
3210
3211 // If this is a friend function defined in a class template, it does not
3212 // have a body until it is used, nevertheless it is a definition, see
3213 // [temp.inst]p2:
3214 //
3215 // ... for the purpose of determining whether an instantiated redeclaration
3216 // is valid according to [basic.def.odr] and [class.mem], a declaration that
3217 // corresponds to a definition in the template is considered to be a
3218 // definition.
3219 //
3220 // The following code must produce redefinition error:
3221 //
3222 // template<typename T> struct C20 { friend void func_20() {} };
3223 // C20<int> c20i;
3224 // void func_20() {}
3225 //
3226 if (CheckForPendingFriendDefinition &&
3227 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3228 Definition = FD;
3229 return true;
3230 }
3231 }
3232
3233 return false;
3234}
3235
3237 if (!hasBody(Definition))
3238 return nullptr;
3239
3240 assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3241 "definition should not have a body");
3242 if (Definition->Body)
3243 return Definition->Body.get(getASTContext().getExternalSource());
3244
3245 return nullptr;
3246}
3247
3249 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3250 Body = LazyDeclStmtPtr(B);
3251 if (B)
3252 EndRangeLoc = B->getEndLoc();
3253}
3254
3256 FunctionDeclBits.IsPureVirtual = P;
3257 if (P)
3258 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3259 Parent->markedVirtualFunctionPure();
3260}
3261
3262template<std::size_t Len>
3263static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3264 const IdentifierInfo *II = ND->getIdentifier();
3265 return II && II->isStr(Str);
3266}
3267
3269 // C++23 [expr.const]/p17
3270 // An immediate-escalating function is
3271 // - the call operator of a lambda that is not declared with the consteval
3272 // specifier,
3273 if (isLambdaCallOperator(this) && !isConsteval())
3274 return true;
3275 // - a defaulted special member function that is not declared with the
3276 // consteval specifier,
3277 if (isDefaulted() && !isConsteval())
3278 return true;
3279 // - a function that results from the instantiation of a templated entity
3280 // defined with the constexpr specifier.
3282 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3284 return true;
3285 return false;
3286}
3287
3289 // C++23 [expr.const]/p18
3290 // An immediate function is a function or constructor that is
3291 // - declared with the consteval specifier
3292 if (isConsteval())
3293 return true;
3294 // - an immediate-escalating function F whose function body contains an
3295 // immediate-escalating expression
3297 return true;
3298
3299 if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3300 MD && MD->isLambdaStaticInvoker())
3301 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3302
3303 return false;
3304}
3305
3307 const TranslationUnitDecl *tunit =
3308 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3309 return tunit &&
3310 !tunit->getASTContext().getLangOpts().Freestanding &&
3311 isNamed(this, "main");
3312}
3313
3315 const TranslationUnitDecl *TUnit =
3316 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3317 if (!TUnit)
3318 return false;
3319
3320 // Even though we aren't really targeting MSVCRT if we are freestanding,
3321 // semantic analysis for these functions remains the same.
3322
3323 // MSVCRT entry points only exist on MSVCRT targets.
3324 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3325 return false;
3326
3327 // Nameless functions like constructors cannot be entry points.
3328 if (!getIdentifier())
3329 return false;
3330
3331 return llvm::StringSwitch<bool>(getName())
3332 .Cases("main", // an ANSI console app
3333 "wmain", // a Unicode console App
3334 "WinMain", // an ANSI GUI app
3335 "wWinMain", // a Unicode GUI app
3336 "DllMain", // a DLL
3337 true)
3338 .Default(false);
3339}
3340
3342 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3343 return false;
3344 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3345 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3346 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3347 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3348 return false;
3349
3351 return false;
3352
3353 const auto *proto = getType()->castAs<FunctionProtoType>();
3354 if (proto->getNumParams() != 2 || proto->isVariadic())
3355 return false;
3356
3357 const ASTContext &Context =
3358 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3359 ->getASTContext();
3360
3361 // The result type and first argument type are constant across all
3362 // these operators. The second argument must be exactly void*.
3363 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3364}
3365
3367 std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3368 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3369 return false;
3370 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3371 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3372 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3373 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3374 return false;
3375
3376 if (isa<CXXRecordDecl>(getDeclContext()))
3377 return false;
3378
3379 // This can only fail for an invalid 'operator new' declaration.
3381 return false;
3382
3383 const auto *FPT = getType()->castAs<FunctionProtoType>();
3384 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())
3385 return false;
3386
3387 // If this is a single-parameter function, it must be a replaceable global
3388 // allocation or deallocation function.
3389 if (FPT->getNumParams() == 1)
3390 return true;
3391
3392 unsigned Params = 1;
3393 QualType Ty = FPT->getParamType(Params);
3394 const ASTContext &Ctx = getASTContext();
3395
3396 auto Consume = [&] {
3397 ++Params;
3398 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3399 };
3400
3401 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3402 bool IsSizedDelete = false;
3403 if (Ctx.getLangOpts().SizedDeallocation &&
3404 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3405 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3406 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3407 IsSizedDelete = true;
3408 Consume();
3409 }
3410
3411 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3412 // new/delete.
3413 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3414 Consume();
3415 if (AlignmentParam)
3416 *AlignmentParam = Params;
3417 }
3418
3419 // If this is not a sized delete, the next parameter can be a
3420 // 'const std::nothrow_t&'.
3421 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3422 Ty = Ty->getPointeeType();
3424 return false;
3425 if (Ty->isNothrowT()) {
3426 if (IsNothrow)
3427 *IsNothrow = true;
3428 Consume();
3429 }
3430 }
3431
3432 // Finally, recognize the not yet standard versions of new that take a
3433 // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3434 // tcmalloc (see
3435 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3436 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3437 QualType T = Ty;
3438 while (const auto *TD = T->getAs<TypedefType>())
3439 T = TD->getDecl()->getUnderlyingType();
3440 const IdentifierInfo *II =
3441 T->castAs<EnumType>()->getDecl()->getIdentifier();
3442 if (II && II->isStr("__hot_cold_t"))
3443 Consume();
3444 }
3445
3446 return Params == FPT->getNumParams();
3447}
3448
3450 if (!getBuiltinID())
3451 return false;
3452
3453 const FunctionDecl *Definition;
3454 if (!hasBody(Definition))
3455 return false;
3456
3457 if (!Definition->isInlineSpecified() ||
3458 !Definition->hasAttr<AlwaysInlineAttr>())
3459 return false;
3460
3461 ASTContext &Context = getASTContext();
3462 switch (Context.GetGVALinkageForFunction(Definition)) {
3463 case GVA_Internal:
3464 case GVA_DiscardableODR:
3465 case GVA_StrongODR:
3466 return false;
3468 case GVA_StrongExternal:
3469 return true;
3470 }
3471 llvm_unreachable("Unknown GVALinkage");
3472}
3473
3475 // C++ P0722:
3476 // Within a class C, a single object deallocation function with signature
3477 // (T, std::destroying_delete_t, <more params>)
3478 // is a destroying operator delete.
3479 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3480 getNumParams() < 2)
3481 return false;
3482
3483 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3484 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3485 RD->getIdentifier()->isStr("destroying_delete_t");
3486}
3487
3489 return getDeclLanguageLinkage(*this);
3490}
3491
3493 return isDeclExternC(*this);
3494}
3495
3497 if (hasAttr<OpenCLKernelAttr>())
3498 return true;
3500}
3501
3504}
3505
3507 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3508 return Method->isStatic();
3509
3511 return false;
3512
3513 for (const DeclContext *DC = getDeclContext();
3514 DC->isNamespace();
3515 DC = DC->getParent()) {
3516 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3517 if (!Namespace->getDeclName())
3518 return false;
3519 }
3520 }
3521
3522 return true;
3523}
3524
3526 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3527 hasAttr<C11NoReturnAttr>())
3528 return true;
3529
3530 if (auto *FnTy = getType()->getAs<FunctionType>())
3531 return FnTy->getNoReturnAttr();
3532
3533 return false;
3534}
3535
3537 // C++20 [temp.friend]p9:
3538 // A non-template friend declaration with a requires-clause [or]
3539 // a friend function template with a constraint that depends on a template
3540 // parameter from an enclosing template [...] does not declare the same
3541 // function or function template as a declaration in any other scope.
3542
3543 // If this isn't a friend then it's not a member-like constrained friend.
3544 if (!getFriendObjectKind()) {
3545 return false;
3546 }
3547
3549 // If these friends don't have constraints, they aren't constrained, and
3550 // thus don't fall under temp.friend p9. Else the simple presence of a
3551 // constraint makes them unique.
3553 }
3554
3556}
3557
3559 if (hasAttr<TargetAttr>())
3561 if (hasAttr<TargetVersionAttr>())
3563 if (hasAttr<CPUDispatchAttr>())
3565 if (hasAttr<CPUSpecificAttr>())
3567 if (hasAttr<TargetClonesAttr>())
3570}
3571
3573 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3574}
3575
3577 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3578}
3579
3581 return isMultiVersion() &&
3582 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3583}
3584
3586 if (!isMultiVersion())
3587 return false;
3588 if (hasAttr<TargetAttr>())
3589 return getAttr<TargetAttr>()->isDefaultVersion();
3590 return hasAttr<TargetVersionAttr>() &&
3591 getAttr<TargetVersionAttr>()->isDefaultVersion();
3592}
3593
3595 return isMultiVersion() && hasAttr<TargetClonesAttr>();
3596}
3597
3599 return isMultiVersion() && hasAttr<TargetVersionAttr>();
3600}
3601
3602void
3605
3607 FunctionTemplateDecl *PrevFunTmpl
3608 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3609 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3610 FunTmpl->setPreviousDecl(PrevFunTmpl);
3611 }
3612
3613 if (PrevDecl && PrevDecl->isInlined())
3614 setImplicitlyInline(true);
3615}
3616
3618
3619/// Returns a value indicating whether this function corresponds to a builtin
3620/// function.
3621///
3622/// The function corresponds to a built-in function if it is declared at
3623/// translation scope or within an extern "C" block and its name matches with
3624/// the name of a builtin. The returned value will be 0 for functions that do
3625/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3626/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3627/// value.
3628///
3629/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3630/// functions as their wrapped builtins. This shouldn't be done in general, but
3631/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3632unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3633 unsigned BuiltinID = 0;
3634
3635 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3636 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3637 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3638 BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3639 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3640 BuiltinID = A->getID();
3641 }
3642
3643 if (!BuiltinID)
3644 return 0;
3645
3646 // If the function is marked "overloadable", it has a different mangled name
3647 // and is not the C library function.
3648 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3649 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3650 return 0;
3651
3652 const ASTContext &Context = getASTContext();
3653 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3654 return BuiltinID;
3655
3656 // This function has the name of a known C library
3657 // function. Determine whether it actually refers to the C library
3658 // function or whether it just has the same name.
3659
3660 // If this is a static function, it's not a builtin.
3661 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3662 return 0;
3663
3664 // OpenCL v1.2 s6.9.f - The library functions defined in
3665 // the C99 standard headers are not available.
3666 if (Context.getLangOpts().OpenCL &&
3667 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3668 return 0;
3669
3670 // CUDA does not have device-side standard library. printf and malloc are the
3671 // only special cases that are supported by device-side runtime.
3672 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3673 !hasAttr<CUDAHostAttr>() &&
3674 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3675 return 0;
3676
3677 // As AMDGCN implementation of OpenMP does not have a device-side standard
3678 // library, none of the predefined library functions except printf and malloc
3679 // should be treated as a builtin i.e. 0 should be returned for them.
3680 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3681 Context.getLangOpts().OpenMPIsTargetDevice &&
3682 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3683 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3684 return 0;
3685
3686 return BuiltinID;
3687}
3688
3689/// getNumParams - Return the number of parameters this function must have
3690/// based on its FunctionType. This is the length of the ParamInfo array
3691/// after it has been created.
3693 const auto *FPT = getType()->getAs<FunctionProtoType>();
3694 return FPT ? FPT->getNumParams() : 0;
3695}
3696
3697void FunctionDecl::setParams(ASTContext &C,
3698 ArrayRef<ParmVarDecl *> NewParamInfo) {
3699 assert(!ParamInfo && "Already has param info!");
3700 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3701
3702 // Zero params -> null pointer.
3703 if (!NewParamInfo.empty()) {
3704 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3705 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3706 }
3707}
3708
3709/// getMinRequiredArguments - Returns the minimum number of arguments
3710/// needed to call this function. This may be fewer than the number of
3711/// function parameters, if some of the parameters have default
3712/// arguments (in C++) or are parameter packs (C++11).
3715 return getNumParams();
3716
3717 // Note that it is possible for a parameter with no default argument to
3718 // follow a parameter with a default argument.
3719 unsigned NumRequiredArgs = 0;
3720 unsigned MinParamsSoFar = 0;
3721 for (auto *Param : parameters()) {
3722 if (!Param->isParameterPack()) {
3723 ++MinParamsSoFar;
3724 if (!Param->hasDefaultArg())
3725 NumRequiredArgs = MinParamsSoFar;
3726 }
3727 }
3728 return NumRequiredArgs;
3729}
3730
3733}
3734
3736 return getNumParams() -
3737 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3738}
3739
3741 return getMinRequiredArguments() -
3742 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3743}
3744
3746 return getNumParams() == 1 ||
3747 (getNumParams() > 1 &&
3748 llvm::all_of(llvm::drop_begin(parameters()),
3749 [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3750}
3751
3752/// The combination of the extern and inline keywords under MSVC forces
3753/// the function to be required.
3754///
3755/// Note: This function assumes that we will only get called when isInlined()
3756/// would return true for this FunctionDecl.
3758 assert(isInlined() && "expected to get called on an inlined function!");
3759
3760 const ASTContext &Context = getASTContext();
3761 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3762 !hasAttr<DLLExportAttr>())
3763 return false;
3764
3765 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3766 FD = FD->getPreviousDecl())
3767 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3768 return true;
3769
3770 return false;
3771}
3772
3773static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3774 if (Redecl->getStorageClass() != SC_Extern)
3775 return false;
3776
3777 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3778 FD = FD->getPreviousDecl())
3779 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3780 return false;
3781
3782 return true;
3783}
3784
3785static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3786 // Only consider file-scope declarations in this test.
3787 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3788 return false;
3789
3790 // Only consider explicit declarations; the presence of a builtin for a
3791 // libcall shouldn't affect whether a definition is externally visible.
3792 if (Redecl->isImplicit())
3793 return false;
3794
3795 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3796 return true; // Not an inline definition
3797
3798 return false;
3799}
3800
3801/// For a function declaration in C or C++, determine whether this
3802/// declaration causes the definition to be externally visible.
3803///
3804/// For instance, this determines if adding the current declaration to the set
3805/// of redeclarations of the given functions causes
3806/// isInlineDefinitionExternallyVisible to change from false to true.
3808 assert(!doesThisDeclarationHaveABody() &&
3809 "Must have a declaration without a body.");
3810
3811 const ASTContext &Context = getASTContext();
3812
3813 if (Context.getLangOpts().MSVCCompat) {
3814 const FunctionDecl *Definition;
3815 if (hasBody(Definition) && Definition->isInlined() &&
3816 redeclForcesDefMSVC(this))
3817 return true;
3818 }
3819
3820 if (Context.getLangOpts().CPlusPlus)
3821 return false;
3822
3823 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3824 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3825 // an externally visible definition.
3826 //
3827 // FIXME: What happens if gnu_inline gets added on after the first
3828 // declaration?
3830 return false;
3831
3832 const FunctionDecl *Prev = this;
3833 bool FoundBody = false;
3834 while ((Prev = Prev->getPreviousDecl())) {
3835 FoundBody |= Prev->doesThisDeclarationHaveABody();
3836
3837 if (Prev->doesThisDeclarationHaveABody()) {
3838 // If it's not the case that both 'inline' and 'extern' are
3839 // specified on the definition, then it is always externally visible.
3840 if (!Prev->isInlineSpecified() ||
3841 Prev->getStorageClass() != SC_Extern)
3842 return false;
3843 } else if (Prev->isInlineSpecified() &&
3844 Prev->getStorageClass() != SC_Extern) {
3845 return false;
3846 }
3847 }
3848 return FoundBody;
3849 }
3850
3851 // C99 6.7.4p6:
3852 // [...] If all of the file scope declarations for a function in a
3853 // translation unit include the inline function specifier without extern,
3854 // then the definition in that translation unit is an inline definition.
3856 return false;
3857 const FunctionDecl *Prev = this;
3858 bool FoundBody = false;
3859 while ((Prev = Prev->getPreviousDecl())) {
3860 FoundBody |= Prev->doesThisDeclarationHaveABody();
3861 if (RedeclForcesDefC99(Prev))
3862 return false;
3863 }
3864 return FoundBody;
3865}
3866
3868 const TypeSourceInfo *TSI = getTypeSourceInfo();
3869 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3870 : FunctionTypeLoc();
3871}
3872
3875 if (!FTL)
3876 return SourceRange();
3877
3878 // Skip self-referential return types.
3880 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3881 SourceLocation Boundary = getNameInfo().getBeginLoc();
3882 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3883 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3884 return SourceRange();
3885
3886 return RTRange;
3887}
3888
3890 unsigned NP = getNumParams();
3891 SourceLocation EllipsisLoc = getEllipsisLoc();
3892
3893 if (NP == 0 && EllipsisLoc.isInvalid())
3894 return SourceRange();
3895
3897 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3898 SourceLocation End = EllipsisLoc.isValid()
3899 ? EllipsisLoc
3900 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3901
3902 return SourceRange(Begin, End);
3903}
3904
3907 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3908}
3909
3910/// For an inline function definition in C, or for a gnu_inline function
3911/// in C++, determine whether the definition will be externally visible.
3912///
3913/// Inline function definitions are always available for inlining optimizations.
3914/// However, depending on the language dialect, declaration specifiers, and
3915/// attributes, the definition of an inline function may or may not be
3916/// "externally" visible to other translation units in the program.
3917///
3918/// In C99, inline definitions are not externally visible by default. However,
3919/// if even one of the global-scope declarations is marked "extern inline", the
3920/// inline definition becomes externally visible (C99 6.7.4p6).
3921///
3922/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3923/// definition, we use the GNU semantics for inline, which are nearly the
3924/// opposite of C99 semantics. In particular, "inline" by itself will create
3925/// an externally visible symbol, but "extern inline" will not create an
3926/// externally visible symbol.
3929 hasAttr<AliasAttr>()) &&
3930 "Must be a function definition");
3931 assert(isInlined() && "Function must be inline");
3932 ASTContext &Context = getASTContext();
3933
3934 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3935 // Note: If you change the logic here, please change
3936 // doesDeclarationForceExternallyVisibleDefinition as well.
3937 //
3938 // If it's not the case that both 'inline' and 'extern' are
3939 // specified on the definition, then this inline definition is
3940 // externally visible.
3941 if (Context.getLangOpts().CPlusPlus)
3942 return false;
3944 return true;
3945
3946 // If any declaration is 'inline' but not 'extern', then this definition
3947 // is externally visible.
3948 for (auto *Redecl : redecls()) {
3949 if (Redecl->isInlineSpecified() &&
3950 Redecl->getStorageClass() != SC_Extern)
3951 return true;
3952 }
3953
3954 return false;
3955 }
3956
3957 // The rest of this function is C-only.
3958 assert(!Context.getLangOpts().CPlusPlus &&
3959 "should not use C inline rules in C++");
3960
3961 // C99 6.7.4p6:
3962 // [...] If all of the file scope declarations for a function in a
3963 // translation unit include the inline function specifier without extern,
3964 // then the definition in that translation unit is an inline definition.
3965 for (auto *Redecl : redecls()) {
3966 if (RedeclForcesDefC99(Redecl))
3967 return true;
3968 }
3969
3970 // C99 6.7.4p6:
3971 // An inline definition does not provide an external definition for the
3972 // function, and does not forbid an external definition in another
3973 // translation unit.
3974 return false;
3975}
3976
3977/// getOverloadedOperator - Which C++ overloaded operator this
3978/// function represents, if any.
3980 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3982 return OO_None;
3983}
3984
3985/// getLiteralIdentifier - The literal suffix identifier this function
3986/// represents, if any.
3990 return nullptr;
3991}
3992
3994 if (TemplateOrSpecialization.isNull())
3995 return TK_NonTemplate;
3996 if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {
3997 if (isa<FunctionDecl>(ND))
3999 assert(isa<FunctionTemplateDecl>(ND) &&
4000 "No other valid types in NamedDecl");
4001 return TK_FunctionTemplate;
4002 }
4003 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
4005 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
4007 if (TemplateOrSpecialization.is
4010
4011 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4012}
4013
4016 return cast<FunctionDecl>(Info->getInstantiatedFrom());
4017
4018 return nullptr;
4019}
4020
4022 if (auto *MSI =
4023 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4024 return MSI;
4025 if (auto *FTSI = TemplateOrSpecialization
4026 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4027 return FTSI->getMemberSpecializationInfo();
4028 return nullptr;
4029}
4030
4031void
4032FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4033 FunctionDecl *FD,
4035 assert(TemplateOrSpecialization.isNull() &&
4036 "Member function is already a specialization");
4038 = new (C) MemberSpecializationInfo(FD, TSK);
4039 TemplateOrSpecialization = Info;
4040}
4041
4043 return dyn_cast_if_present<FunctionTemplateDecl>(
4044 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4045}
4046
4048 FunctionTemplateDecl *Template) {
4049 assert(TemplateOrSpecialization.isNull() &&
4050 "Member function is already a specialization");
4051 TemplateOrSpecialization = Template;
4052}
4053
4055 return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() ||
4056 TemplateOrSpecialization
4057 .is<DependentFunctionTemplateSpecializationInfo *>();
4058}
4059
4061 assert(TemplateOrSpecialization.isNull() &&
4062 "Function is already a specialization");
4063 TemplateOrSpecialization = FD;
4064}
4065
4067 return dyn_cast_if_present<FunctionDecl>(
4068 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4069}
4070
4072 // If the function is invalid, it can't be implicitly instantiated.
4073 if (isInvalidDecl())
4074 return false;
4075
4077 case TSK_Undeclared:
4080 return false;
4081
4083 return true;
4084
4086 // Handled below.
4087 break;
4088 }
4089
4090 // Find the actual template from which we will instantiate.
4091 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4092 bool HasPattern = false;
4093 if (PatternDecl)
4094 HasPattern = PatternDecl->hasBody(PatternDecl);
4095
4096 // C++0x [temp.explicit]p9:
4097 // Except for inline functions, other explicit instantiation declarations
4098 // have the effect of suppressing the implicit instantiation of the entity
4099 // to which they refer.
4100 if (!HasPattern || !PatternDecl)
4101 return true;
4102
4103 return PatternDecl->isInlined();
4104}
4105
4107 // FIXME: Remove this, it's not clear what it means. (Which template
4108 // specialization kind?)
4110}
4111
4114 // If this is a generic lambda call operator specialization, its
4115 // instantiation pattern is always its primary template's pattern
4116 // even if its primary template was instantiated from another
4117 // member template (which happens with nested generic lambdas).
4118 // Since a lambda's call operator's body is transformed eagerly,
4119 // we don't have to go hunting for a prototype definition template
4120 // (i.e. instantiated-from-member-template) to use as an instantiation
4121 // pattern.
4122
4124 dyn_cast<CXXMethodDecl>(this))) {
4125 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4126 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
4127 }
4128
4129 // Check for a declaration of this function that was instantiated from a
4130 // friend definition.
4131 const FunctionDecl *FD = nullptr;
4132 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4133 FD = this;
4134
4136 if (ForDefinition &&
4138 return nullptr;
4139 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4140 }
4141
4142 if (ForDefinition &&
4144 return nullptr;
4145
4146 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4147 // If we hit a point where the user provided a specialization of this
4148 // template, we're done looking.
4149 while (!ForDefinition || !Primary->isMemberSpecialization()) {
4150 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4151 if (!NewPrimary)
4152 break;
4153 Primary = NewPrimary;
4154 }
4155
4156 return getDefinitionOrSelf(Primary->getTemplatedDecl());
4157 }
4158
4159 return nullptr;
4160}
4161
4164 = TemplateOrSpecialization
4165 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4166 return Info->getTemplate();
4167 }
4168 return nullptr;
4169}
4170
4173 return TemplateOrSpecialization
4175}
4176
4180 = TemplateOrSpecialization
4181 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4182 return Info->TemplateArguments;
4183 }
4184 return nullptr;
4185}
4186
4190 = TemplateOrSpecialization
4191 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4192 return Info->TemplateArgumentsAsWritten;
4193 }
4195 TemplateOrSpecialization
4196 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) {
4197 return Info->TemplateArgumentsAsWritten;
4198 }
4199 return nullptr;
4200}
4201
4202void FunctionDecl::setFunctionTemplateSpecialization(
4203 ASTContext &C, FunctionTemplateDecl *Template,
4204 TemplateArgumentList *TemplateArgs, void *InsertPos,
4206 const TemplateArgumentListInfo *TemplateArgsAsWritten,
4207 SourceLocation PointOfInstantiation) {
4208 assert((TemplateOrSpecialization.isNull() ||
4209 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
4210 "Member function is already a specialization");
4211 assert(TSK != TSK_Undeclared &&
4212 "Must specify the type of function template specialization");
4213 assert((TemplateOrSpecialization.isNull() ||
4216 "Member specialization must be an explicit specialization");
4219 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4220 PointOfInstantiation,
4221 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
4222 TemplateOrSpecialization = Info;
4223 Template->addSpecialization(Info, InsertPos);
4224}
4225
4227 ASTContext &Context, const UnresolvedSetImpl &Templates,
4228 const TemplateArgumentListInfo *TemplateArgs) {
4229 assert(TemplateOrSpecialization.isNull());
4232 TemplateArgs);
4233 TemplateOrSpecialization = Info;
4234}
4235
4238 return TemplateOrSpecialization
4240}
4241
4244 ASTContext &Context, const UnresolvedSetImpl &Candidates,
4245 const TemplateArgumentListInfo *TArgs) {
4246 const auto *TArgsWritten =
4247 TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4248 return new (Context.Allocate(
4249 totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4250 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4251}
4252
4253DependentFunctionTemplateSpecializationInfo::
4254 DependentFunctionTemplateSpecializationInfo(
4255 const UnresolvedSetImpl &Candidates,
4256 const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4257 : NumCandidates(Candidates.size()),
4258 TemplateArgumentsAsWritten(TemplateArgsWritten) {
4259 std::transform(Candidates.begin(), Candidates.end(),
4260 getTrailingObjects<FunctionTemplateDecl *>(),
4261 [](NamedDecl *ND) {
4262 return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());
4263 });
4264}
4265
4267 // For a function template specialization, query the specialization
4268 // information object.
4270 TemplateOrSpecialization
4271 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4272 return FTSInfo->getTemplateSpecializationKind();
4273
4274 if (MemberSpecializationInfo *MSInfo =
4275 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4276 return MSInfo->getTemplateSpecializationKind();
4277
4278 // A dependent function template specialization is an explicit specialization,
4279 // except when it's a friend declaration.
4280 if (TemplateOrSpecialization
4281 .is<DependentFunctionTemplateSpecializationInfo *>() &&
4284
4285 return TSK_Undeclared;
4286}
4287
4290 // This is the same as getTemplateSpecializationKind(), except that for a
4291 // function that is both a function template specialization and a member
4292 // specialization, we prefer the member specialization information. Eg:
4293 //
4294 // template<typename T> struct A {
4295 // template<typename U> void f() {}
4296 // template<> void f<int>() {}
4297 // };
4298 //
4299 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4300 // template specialization; both getTemplateSpecializationKind() and
4301 // getTemplateSpecializationKindForInstantiation() will return
4302 // TSK_ExplicitSpecialization.
4303 //
4304 // For A<int>::f<int>():
4305 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4306 // * getTemplateSpecializationKindForInstantiation() will return
4307 // TSK_ImplicitInstantiation
4308 //
4309 // This reflects the facts that A<int>::f<int> is an explicit specialization
4310 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4311 // from A::f<int> if a definition is needed.
4313 TemplateOrSpecialization
4314 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4315 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4316 return MSInfo->getTemplateSpecializationKind();
4317 return FTSInfo->getTemplateSpecializationKind();
4318 }
4319
4320 if (MemberSpecializationInfo *MSInfo =
4321 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4322 return MSInfo->getTemplateSpecializationKind();
4323
4324 if (TemplateOrSpecialization
4325 .is<DependentFunctionTemplateSpecializationInfo *>() &&
4328
4329 return TSK_Undeclared;
4330}
4331
4332void
4334 SourceLocation PointOfInstantiation) {
4336 = TemplateOrSpecialization.dyn_cast<
4338 FTSInfo->setTemplateSpecializationKind(TSK);
4339 if (TSK != TSK_ExplicitSpecialization &&
4340 PointOfInstantiation.isValid() &&
4341 FTSInfo->getPointOfInstantiation().isInvalid()) {
4342 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4344 L->InstantiationRequested(this);
4345 }
4346 } else if (MemberSpecializationInfo *MSInfo
4347 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4348 MSInfo->setTemplateSpecializationKind(TSK);
4349 if (TSK != TSK_ExplicitSpecialization &&
4350 PointOfInstantiation.isValid() &&
4351 MSInfo->getPointOfInstantiation().isInvalid()) {
4352 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4354 L->InstantiationRequested(this);
4355 }
4356 } else
4357 llvm_unreachable("Function cannot have a template specialization kind");
4358}
4359
4362 = TemplateOrSpecialization.dyn_cast<
4364 return FTSInfo->getPointOfInstantiation();
4365 if (MemberSpecializationInfo *MSInfo =
4366 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4367 return MSInfo->getPointOfInstantiation();
4368
4369 return SourceLocation();
4370}
4371
4373 if (Decl::isOutOfLine())
4374 return true;
4375
4376 // If this function was instantiated from a member function of a
4377 // class template, check whether that member function was defined out-of-line.
4379 const FunctionDecl *Definition;
4380 if (FD->hasBody(Definition))
4381 return Definition->isOutOfLine();
4382 }
4383
4384 // If this function was instantiated from a function template,
4385 // check whether that function template was defined out-of-line.
4386 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4387 const FunctionDecl *Definition;
4388 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4389 return Definition->isOutOfLine();
4390 }
4391
4392 return false;
4393}
4394
4396 return SourceRange(getOuterLocStart(), EndRangeLoc);
4397}
4398
4400 IdentifierInfo *FnInfo = getIdentifier();
4401
4402 if (!FnInfo)
4403 return 0;
4404
4405 // Builtin handling.
4406 switch (getBuiltinID()) {
4407 case Builtin::BI__builtin_memset:
4408 case Builtin::BI__builtin___memset_chk:
4409 case Builtin::BImemset:
4410 return Builtin::BImemset;
4411
4412 case Builtin::BI__builtin_memcpy:
4413 case Builtin::BI__builtin___memcpy_chk:
4414 case Builtin::BImemcpy:
4415 return Builtin::BImemcpy;
4416
4417 case Builtin::BI__builtin_mempcpy:
4418 case Builtin::BI__builtin___mempcpy_chk:
4419 case Builtin::BImempcpy:
4420 return Builtin::BImempcpy;
4421
4422 case Builtin::BI__builtin_memmove:
4423 case Builtin::BI__builtin___memmove_chk:
4424 case Builtin::BImemmove:
4425 return Builtin::BImemmove;
4426
4427 case Builtin::BIstrlcpy:
4428 case Builtin::BI__builtin___strlcpy_chk:
4429 return Builtin::BIstrlcpy;
4430
4431 case Builtin::BIstrlcat:
4432 case Builtin::BI__builtin___strlcat_chk:
4433 return Builtin::BIstrlcat;
4434
4435 case Builtin::BI__builtin_memcmp:
4436 case Builtin::BImemcmp:
4437 return Builtin::BImemcmp;
4438
4439 case Builtin::BI__builtin_bcmp:
4440 case Builtin::BIbcmp:
4441 return Builtin::BIbcmp;
4442
4443 case Builtin::BI__builtin_strncpy:
4444 case Builtin::BI__builtin___strncpy_chk:
4445 case Builtin::BIstrncpy:
4446 return Builtin::BIstrncpy;
4447
4448 case Builtin::BI__builtin_strncmp:
4449 case Builtin::BIstrncmp:
4450 return Builtin::BIstrncmp;
4451
4452 case Builtin::BI__builtin_strncasecmp:
4453 case Builtin::BIstrncasecmp:
4454 return Builtin::BIstrncasecmp;
4455
4456 case Builtin::BI__builtin_strncat:
4457 case Builtin::BI__builtin___strncat_chk:
4458 case Builtin::BIstrncat:
4459 return Builtin::BIstrncat;
4460
4461 case Builtin::BI__builtin_strndup:
4462 case Builtin::BIstrndup:
4463 return Builtin::BIstrndup;
4464
4465 case Builtin::BI__builtin_strlen:
4466 case Builtin::BIstrlen:
4467 return Builtin::BIstrlen;
4468
4469 case Builtin::BI__builtin_bzero:
4470 case Builtin::BIbzero:
4471 return Builtin::BIbzero;
4472
4473 case Builtin::BI__builtin_bcopy:
4474 case Builtin::BIbcopy:
4475 return Builtin::BIbcopy;
4476
4477 case Builtin::BIfree:
4478 return Builtin::BIfree;
4479
4480 default:
4481 if (isExternC()) {
4482 if (FnInfo->isStr("memset"))
4483 return Builtin::BImemset;
4484 if (FnInfo->isStr("memcpy"))
4485 return Builtin::BImemcpy;
4486 if (FnInfo->isStr("mempcpy"))
4487 return Builtin::BImempcpy;
4488 if (FnInfo->isStr("memmove"))
4489 return Builtin::BImemmove;
4490 if (FnInfo->isStr("memcmp"))
4491 return Builtin::BImemcmp;
4492 if (FnInfo->isStr("bcmp"))
4493 return Builtin::BIbcmp;
4494 if (FnInfo->isStr("strncpy"))
4495 return Builtin::BIstrncpy;
4496 if (FnInfo->isStr("strncmp"))
4497 return Builtin::BIstrncmp;
4498 if (FnInfo->isStr("strncasecmp"))
4499 return Builtin::BIstrncasecmp;
4500 if (FnInfo->isStr("strncat"))
4501 return Builtin::BIstrncat;
4502 if (FnInfo->isStr("strndup"))
4503 return Builtin::BIstrndup;
4504 if (FnInfo->isStr("strlen"))
4505 return Builtin::BIstrlen;
4506 if (FnInfo->isStr("bzero"))
4507 return Builtin::BIbzero;
4508 if (FnInfo->isStr("bcopy"))
4509 return Builtin::BIbcopy;
4510 } else if (isInStdNamespace()) {
4511 if (FnInfo->isStr("free"))
4512 return Builtin::BIfree;
4513 }
4514 break;
4515 }
4516 return 0;
4517}
4518
4520 assert(hasODRHash());
4521 return ODRHash;
4522}
4523
4525 if (hasODRHash())
4526 return ODRHash;
4527
4528 if (auto *FT = getInstantiatedFromMemberFunction()) {
4529 setHasODRHash(true);
4530 ODRHash = FT->getODRHash();
4531 return ODRHash;
4532 }
4533
4534 class ODRHash Hash;
4535 Hash.AddFunctionDecl(this);
4536 setHasODRHash(true);
4537 ODRHash = Hash.CalculateHash();
4538 return ODRHash;
4539}
4540
4541//===----------------------------------------------------------------------===//
4542// FieldDecl Implementation
4543//===----------------------------------------------------------------------===//
4544
4546 SourceLocation StartLoc, SourceLocation IdLoc,
4547 const IdentifierInfo *Id, QualType T,
4548 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4549 InClassInitStyle InitStyle) {
4550 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4551 BW, Mutable, InitStyle);
4552}
4553
4555 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4556 SourceLocation(), nullptr, QualType(), nullptr,
4557 nullptr, false, ICIS_NoInit);
4558}
4559
4561 if (!isImplicit() || getDeclName())
4562 return false;
4563
4564 if (const auto *Record = getType()->getAs<RecordType>())
4565 return Record->getDecl()->isAnonymousStructOrUnion();
4566
4567 return false;
4568}
4569
4571 if (!hasInClassInitializer())
4572 return nullptr;
4573
4574 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4575 return cast_if_present<Expr>(
4576 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4577 : InitPtr.get(nullptr));
4578}
4579
4581 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4582}
4583
4584void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4586 if (BitField)
4587 InitAndBitWidth->Init = NewInit;
4588 else
4589 Init = NewInit;
4590}
4591
4592unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4593 assert(isBitField() && "not a bitfield");
4594 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4595}
4596
4599 getBitWidthValue(Ctx) == 0;
4600}
4601
4602bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4603 if (isZeroLengthBitField(Ctx))
4604 return true;
4605
4606 // C++2a [intro.object]p7:
4607 // An object has nonzero size if it
4608 // -- is not a potentially-overlapping subobject, or
4609 if (!hasAttr<NoUniqueAddressAttr>())
4610 return false;
4611
4612 // -- is not of class type, or
4613 const auto *RT = getType()->getAs<RecordType>();
4614 if (!RT)
4615 return false;
4616 const RecordDecl *RD = RT->getDecl()->getDefinition();
4617 if (!RD) {
4618 assert(isInvalidDecl() && "valid field has incomplete type");
4619 return false;
4620 }
4621
4622 // -- [has] virtual member functions or virtual base classes, or
4623 // -- has subobjects of nonzero size or bit-fields of nonzero length
4624 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4625 if (!CXXRD->isEmpty())
4626 return false;
4627
4628 // Otherwise, [...] the circumstances under which the object has zero size
4629 // are implementation-defined.
4630 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4631 return true;
4632
4633 // MS ABI: has nonzero size if it is a class type with class type fields,
4634 // whether or not they have nonzero size
4635 return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4636 return Field->getType()->getAs<RecordType>();
4637 });
4638}
4639
4641 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4642}
4643
4645 const FieldDecl *Canonical = getCanonicalDecl();
4646 if (Canonical != this)
4647 return Canonical->getFieldIndex();
4648
4649 if (CachedFieldIndex) return CachedFieldIndex - 1;
4650
4651 unsigned Index = 0;
4652 const RecordDecl *RD = getParent()->getDefinition();
4653 assert(RD && "requested index for field of struct with no definition");
4654
4655 for (auto *Field : RD->fields()) {
4656 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4657 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4658 "overflow in field numbering");
4659 ++Index;
4660 }
4661
4662 assert(CachedFieldIndex && "failed to find field in parent");
4663 return CachedFieldIndex - 1;
4664}
4665
4667 const Expr *FinalExpr = getInClassInitializer();
4668 if (!FinalExpr)
4669 FinalExpr = getBitWidth();
4670 if (FinalExpr)
4671 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4673}
4674
4676 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4677 "capturing type in non-lambda or captured record.");
4678 assert(StorageKind == ISK_NoInit && !BitField &&
4679 "bit-field or field with default member initializer cannot capture "
4680 "VLA type");
4681 StorageKind = ISK_CapturedVLAType;
4682 CapturedVLAType = VLAType;
4683}
4684
4685void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4686 // Print unnamed members using name of their type.
4688 this->getType().print(OS, Policy);
4689 return;
4690 }
4691 // Otherwise, do the normal printing.
4692 DeclaratorDecl::printName(OS, Policy);
4693}
4694
4695//===----------------------------------------------------------------------===//
4696// TagDecl Implementation
4697//===----------------------------------------------------------------------===//
4698
4700 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4701 SourceLocation StartL)
4702 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4703 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4704 assert((DK != Enum || TK == TagTypeKind::Enum) &&
4705 "EnumDecl not matched with TagTypeKind::Enum");
4706 setPreviousDecl(PrevDecl);
4707 setTagKind(TK);
4708 setCompleteDefinition(false);
4709 setBeingDefined(false);
4711 setFreeStanding(false);
4713 TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4714}
4715
4717 return getTemplateOrInnerLocStart(this);
4718}
4719
4721 SourceLocation RBraceLoc = BraceRange.getEnd();
4722 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4723 return SourceRange(getOuterLocStart(), E);
4724}
4725
4727
4729 TypedefNameDeclOrQualifier = TDD;
4730 if (const Type *T = getTypeForDecl()) {
4731 (void)T;
4732 assert(T->isLinkageValid());
4733 }
4734 assert(isLinkageValid());
4735}
4736
4738 setBeingDefined(true);
4739
4740 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4741 struct CXXRecordDecl::DefinitionData *Data =
4742 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4743 for (auto *I : redecls())
4744 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4745 }
4746}
4747
4749 assert((!isa<CXXRecordDecl>(this) ||
4750 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4751 "definition completed but not started");
4752
4754 setBeingDefined(false);
4755
4757 L->CompletedTagDefinition(this);
4758}
4759
4762 return const_cast<TagDecl *>(this);
4763
4764 // If it's possible for us to have an out-of-date definition, check now.
4765 if (mayHaveOutOfDateDef()) {
4766 if (IdentifierInfo *II = getIdentifier()) {
4767 if (II->isOutOfDate()) {
4768 updateOutOfDate(*II);
4769 }
4770 }
4771 }
4772
4773 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4774 return CXXRD->getDefinition();
4775
4776 for (auto *R : redecls())
4777 if (R->isCompleteDefinition())
4778 return R;
4779
4780 return nullptr;
4781}
4782
4784 if (QualifierLoc) {
4785 // Make sure the extended qualifier info is allocated.
4786 if (!hasExtInfo())
4787 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4788 // Set qualifier info.
4789 getExtInfo()->QualifierLoc = QualifierLoc;
4790 } else {
4791 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4792 if (hasExtInfo()) {
4793 if (getExtInfo()->NumTemplParamLists == 0) {
4794 getASTContext().Deallocate(getExtInfo());
4795 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4796 }
4797 else
4798 getExtInfo()->QualifierLoc = QualifierLoc;
4799 }
4800 }
4801}
4802
4803void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4805 // If the name is supposed to have an identifier but does not have one, then
4806 // the tag is anonymous and we should print it differently.
4807 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4808 // If the caller wanted to print a qualified name, they've already printed
4809 // the scope. And if the caller doesn't want that, the scope information
4810 // is already printed as part of the type.
4811 PrintingPolicy Copy(Policy);
4812 Copy.SuppressScope = true;
4814 return;
4815 }
4816 // Otherwise, do the normal printing.
4817 Name.print(OS, Policy);
4818}
4819
4822 assert(!TPLists.empty());
4823 // Make sure the extended decl info is allocated.
4824 if (!hasExtInfo())
4825 // Allocate external info struct.
4826 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4827 // Set the template parameter lists info.
4828 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4829}
4830
4831//===----------------------------------------------------------------------===//
4832// EnumDecl Implementation
4833//===----------------------------------------------------------------------===//
4834
4835EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4836 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4837 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4838 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4839 assert(Scoped || !ScopedUsingClassTag);
4840 IntegerType = nullptr;
4841 setNumPositiveBits(0);
4842 setNumNegativeBits(0);
4843 setScoped(Scoped);
4844 setScopedUsingClassTag(ScopedUsingClassTag);
4845 setFixed(Fixed);
4846 setHasODRHash(false);
4847 ODRHash = 0;
4848}
4849
4850void EnumDecl::anchor() {}
4851
4853 SourceLocation StartLoc, SourceLocation IdLoc,
4855 EnumDecl *PrevDecl, bool IsScoped,
4856 bool IsScopedUsingClassTag, bool IsFixed) {
4857 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4858 IsScoped, IsScopedUsingClassTag, IsFixed);
4859 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4860 C.getTypeDeclType(Enum, PrevDecl);
4861 return Enum;
4862}
4863
4865 EnumDecl *Enum =
4866 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4867 nullptr, nullptr, false, false, false);
4868 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4869 return Enum;
4870}
4871
4873 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4874 return TI->getTypeLoc().getSourceRange();
4875 return SourceRange();
4876}
4877
4879 QualType NewPromotionType,
4880 unsigned NumPositiveBits,
4881 unsigned NumNegativeBits) {
4882 assert(!isCompleteDefinition() && "Cannot redefine enums!");
4883 if (!IntegerType)
4884 IntegerType = NewType.getTypePtr();
4885 PromotionType = NewPromotionType;
4886 setNumPositiveBits(NumPositiveBits);
4887 setNumNegativeBits(NumNegativeBits);
4889}
4890
4892 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4893 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4894 return true;
4895}
4896
4898 return isClosed() && hasAttr<FlagEnumAttr>();
4899}
4900
4902 return isClosed() && !hasAttr<FlagEnumAttr>();
4903}
4904
4907 return MSI->getTemplateSpecializationKind();
4908
4909 return TSK_Undeclared;
4910}
4911
4913 SourceLocation PointOfInstantiation) {
4915 assert(MSI && "Not an instantiated member enumeration?");
4917 if (TSK != TSK_ExplicitSpecialization &&
4918 PointOfInstantiation.isValid() &&
4920 MSI->setPointOfInstantiation(PointOfInstantiation);
4921}
4922
4925 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4927 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4928 ED = NewED;
4929 return getDefinitionOrSelf(ED);
4930 }
4931 }
4932
4934 "couldn't find pattern for enum instantiation");
4935 return nullptr;
4936}
4937
4939 if (SpecializationInfo)
4940 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4941
4942 return nullptr;
4943}
4944
4945void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4947 assert(!SpecializationInfo && "Member enum is already a specialization");
4948 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4949}
4950
4952 if (hasODRHash())
4953 return ODRHash;
4954
4955 class ODRHash Hash;
4956 Hash.AddEnumDecl(this);
4957 setHasODRHash(true);
4958 ODRHash = Hash.CalculateHash();
4959 return ODRHash;
4960}
4961
4963 auto Res = TagDecl::getSourceRange();
4964 // Set end-point to enum-base, e.g. enum foo : ^bar
4965 if (auto *TSI = getIntegerTypeSourceInfo()) {
4966 // TagDecl doesn't know about the enum base.
4967 if (!getBraceRange().getEnd().isValid())
4968 Res.setEnd(TSI->getTypeLoc().getEndLoc());
4969 }
4970 return Res;
4971}
4972
4973void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
4974 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
4975 unsigned NumNegativeBits = getNumNegativeBits();
4976 unsigned NumPositiveBits = getNumPositiveBits();
4977
4978 if (NumNegativeBits) {
4979 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
4980 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
4981 Min = -Max;
4982 } else {
4983 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
4984 Min = llvm::APInt::getZero(Bitwidth);
4985 }
4986}
4987
4988//===----------------------------------------------------------------------===//
4989// RecordDecl Implementation
4990//===----------------------------------------------------------------------===//
4991
4993 DeclContext *DC, SourceLocation StartLoc,
4995 RecordDecl *PrevDecl)
4996 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4997 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5000 setHasObjectMember(false);
5001 setHasVolatileMember(false);
5011 setIsRandomized(false);
5012 setODRHash(0);
5013}
5014
5016 SourceLocation StartLoc, SourceLocation IdLoc,
5017 IdentifierInfo *Id, RecordDecl* PrevDecl) {
5018 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
5019 StartLoc, IdLoc, Id, PrevDecl);
5020 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5021
5022 C.getTypeDeclType(R, PrevDecl);
5023 return R;
5024}
5025