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