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 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
4074 SourceLocation Boundary = getNameInfo().getBeginLoc();
4075 if (RTRange.isInvalid() || Boundary.isInvalid())
4076 return SourceRange();
4077
4078 return RTRange;
4079}
4080
4082 unsigned NP = getNumParams();
4083 SourceLocation EllipsisLoc = getEllipsisLoc();
4084
4085 if (NP == 0 && EllipsisLoc.isInvalid())
4086 return SourceRange();
4087
4088 SourceLocation Begin =
4089 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
4090 SourceLocation End = EllipsisLoc.isValid()
4091 ? EllipsisLoc
4092 : ParamInfo[NP - 1]->getSourceRange().getEnd();
4093
4094 return SourceRange(Begin, End);
4095}
4096
4101
4102/// For an inline function definition in C, or for a gnu_inline function
4103/// in C++, determine whether the definition will be externally visible.
4104///
4105/// Inline function definitions are always available for inlining optimizations.
4106/// However, depending on the language dialect, declaration specifiers, and
4107/// attributes, the definition of an inline function may or may not be
4108/// "externally" visible to other translation units in the program.
4109///
4110/// In C99, inline definitions are not externally visible by default. However,
4111/// if even one of the global-scope declarations is marked "extern inline", the
4112/// inline definition becomes externally visible (C99 6.7.4p6).
4113///
4114/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
4115/// definition, we use the GNU semantics for inline, which are nearly the
4116/// opposite of C99 semantics. In particular, "inline" by itself will create
4117/// an externally visible symbol, but "extern inline" will not create an
4118/// externally visible symbol.
4121 hasAttr<AliasAttr>()) &&
4122 "Must be a function definition");
4123 assert(isInlined() && "Function must be inline");
4124 ASTContext &Context = getASTContext();
4125
4126 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
4127 // Note: If you change the logic here, please change
4128 // doesDeclarationForceExternallyVisibleDefinition as well.
4129 //
4130 // If it's not the case that both 'inline' and 'extern' are
4131 // specified on the definition, then this inline definition is
4132 // externally visible.
4133 if (Context.getLangOpts().CPlusPlus)
4134 return false;
4136 return true;
4137
4138 // If any declaration is 'inline' but not 'extern', then this definition
4139 // is externally visible.
4140 for (auto *Redecl : redecls()) {
4141 if (Redecl->isInlineSpecified() &&
4142 Redecl->getStorageClass() != SC_Extern)
4143 return true;
4144 }
4145
4146 return false;
4147 }
4148
4149 // The rest of this function is C-only.
4150 assert(!Context.getLangOpts().CPlusPlus &&
4151 "should not use C inline rules in C++");
4152
4153 // C99 6.7.4p6:
4154 // [...] If all of the file scope declarations for a function in a
4155 // translation unit include the inline function specifier without extern,
4156 // then the definition in that translation unit is an inline definition.
4157 for (auto *Redecl : redecls()) {
4158 if (RedeclForcesDefC99(Redecl))
4159 return true;
4160 }
4161
4162 // C99 6.7.4p6:
4163 // An inline definition does not provide an external definition for the
4164 // function, and does not forbid an external definition in another
4165 // translation unit.
4166 return false;
4167}
4168
4169/// getOverloadedOperator - Which C++ overloaded operator this
4170/// function represents, if any.
4176
4177/// getLiteralIdentifier - The literal suffix identifier this function
4178/// represents, if any.
4182 return nullptr;
4183}
4184
4186 if (TemplateOrSpecialization.isNull())
4187 return TK_NonTemplate;
4188 if (const auto *ND = dyn_cast<NamedDecl *>(TemplateOrSpecialization)) {
4189 if (isa<FunctionDecl>(ND))
4191 assert(isa<FunctionTemplateDecl>(ND) &&
4192 "No other valid types in NamedDecl");
4193 return TK_FunctionTemplate;
4194 }
4195 if (isa<MemberSpecializationInfo *>(TemplateOrSpecialization))
4197 if (isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization))
4200 TemplateOrSpecialization))
4202
4203 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4204}
4205
4208 return cast<FunctionDecl>(Info->getInstantiatedFrom());
4209
4210 return nullptr;
4211}
4212
4214 if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>(
4215 TemplateOrSpecialization))
4216 return MSI;
4217 if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4218 TemplateOrSpecialization))
4219 return FTSI->getMemberSpecializationInfo();
4220 return nullptr;
4221}
4222
4223void
4224FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4225 FunctionDecl *FD,
4227 assert(TemplateOrSpecialization.isNull() &&
4228 "Member function is already a specialization");
4230 = new (C) MemberSpecializationInfo(FD, TSK);
4231 TemplateOrSpecialization = Info;
4232}
4233
4235 return dyn_cast_if_present<FunctionTemplateDecl>(
4236 dyn_cast_if_present<NamedDecl *>(TemplateOrSpecialization));
4237}
4238
4241 assert(TemplateOrSpecialization.isNull() &&
4242 "Member function is already a specialization");
4243 TemplateOrSpecialization = Template;
4244}
4245
4247 return isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization) ||
4249 TemplateOrSpecialization);
4250}
4251
4253 assert(TemplateOrSpecialization.isNull() &&
4254 "Function is already a specialization");
4255 TemplateOrSpecialization = FD;
4256}
4257
4259 return dyn_cast_if_present<FunctionDecl>(
4260 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4261}
4262
4264 // If the function is invalid, it can't be implicitly instantiated.
4265 if (isInvalidDecl())
4266 return false;
4267
4269 case TSK_Undeclared:
4272 return false;
4273
4275 return true;
4276
4278 // Handled below.
4279 break;
4280 }
4281
4282 // Find the actual template from which we will instantiate.
4283 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4284 bool HasPattern = false;
4285 if (PatternDecl)
4286 HasPattern = PatternDecl->hasBody(PatternDecl);
4287
4288 // C++0x [temp.explicit]p9:
4289 // Except for inline functions, other explicit instantiation declarations
4290 // have the effect of suppressing the implicit instantiation of the entity
4291 // to which they refer.
4292 if (!HasPattern || !PatternDecl)
4293 return true;
4294
4295 return PatternDecl->isInlined();
4296}
4297
4299 // FIXME: Remove this, it's not clear what it means. (Which template
4300 // specialization kind?)
4302}
4303
4306 // If this is a generic lambda call operator specialization, its
4307 // instantiation pattern is always its primary template's pattern
4308 // even if its primary template was instantiated from another
4309 // member template (which happens with nested generic lambdas).
4310 // Since a lambda's call operator's body is transformed eagerly,
4311 // we don't have to go hunting for a prototype definition template
4312 // (i.e. instantiated-from-member-template) to use as an instantiation
4313 // pattern.
4314
4316 dyn_cast<CXXMethodDecl>(this))) {
4317 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4319 }
4320
4321 // Check for a declaration of this function that was instantiated from a
4322 // friend definition.
4323 const FunctionDecl *FD = nullptr;
4324 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4325 FD = this;
4326
4328 if (ForDefinition &&
4330 return nullptr;
4332 }
4333
4334 if (ForDefinition &&
4336 return nullptr;
4337
4338 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4339 // If we hit a point where the user provided a specialization of this
4340 // template, we're done looking.
4341 while (!ForDefinition || !Primary->isMemberSpecialization()) {
4342 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4343 if (!NewPrimary)
4344 break;
4345 Primary = NewPrimary;
4346 }
4347
4348 return Primary->getTemplatedDecl();
4349 }
4350
4351 return nullptr;
4352}
4353
4356 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4357 TemplateOrSpecialization)) {
4358 return Info->getTemplate();
4359 }
4360 return nullptr;
4361}
4362
4365 return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4366 TemplateOrSpecialization);
4367}
4368
4372 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4373 TemplateOrSpecialization)) {
4374 return Info->TemplateArguments;
4375 }
4376 return nullptr;
4377}
4378
4382 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4383 TemplateOrSpecialization)) {
4384 return Info->TemplateArgumentsAsWritten;
4385 }
4387 dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4388 TemplateOrSpecialization)) {
4389 return Info->TemplateArgumentsAsWritten;
4390 }
4391 return nullptr;
4392}
4393
4394void FunctionDecl::setFunctionTemplateSpecialization(
4396 TemplateArgumentList *TemplateArgs, llvm::FoldingSetInsertToken InsertToken,
4398 const TemplateArgumentListInfo *TemplateArgsAsWritten,
4399 SourceLocation PointOfInstantiation) {
4400 assert((TemplateOrSpecialization.isNull() ||
4401 isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) &&
4402 "Member function is already a specialization");
4403 assert(TSK != TSK_Undeclared &&
4404 "Must specify the type of function template specialization");
4405 assert((TemplateOrSpecialization.isNull() ||
4408 "Member specialization must be an explicit specialization");
4411 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4412 PointOfInstantiation,
4413 dyn_cast_if_present<MemberSpecializationInfo *>(
4414 TemplateOrSpecialization));
4415 TemplateOrSpecialization = Info;
4416 Template->addSpecialization(Info, InsertToken);
4417}
4418
4420 ASTContext &Context, const UnresolvedSetImpl &Templates,
4421 const TemplateArgumentListInfo *TemplateArgs) {
4422 assert(TemplateOrSpecialization.isNull());
4425 TemplateArgs);
4426 TemplateOrSpecialization = Info;
4427}
4428
4431 return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4432 TemplateOrSpecialization);
4433}
4434
4437 ASTContext &Context, const UnresolvedSetImpl &Candidates,
4438 const TemplateArgumentListInfo *TArgs) {
4439 const auto *TArgsWritten =
4440 TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4441 return new (Context.Allocate(
4442 totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4443 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4444}
4445
4446DependentFunctionTemplateSpecializationInfo::
4447 DependentFunctionTemplateSpecializationInfo(
4448 const UnresolvedSetImpl &Candidates,
4449 const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4450 : NumCandidates(Candidates.size()),
4451 TemplateArgumentsAsWritten(TemplateArgsWritten) {
4452 std::transform(Candidates.begin(), Candidates.end(), getTrailingObjects(),
4453 [](NamedDecl *ND) {
4455 });
4456}
4457
4459 // For a function template specialization, query the specialization
4460 // information object.
4462 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4463 TemplateOrSpecialization))
4464 return FTSInfo->getTemplateSpecializationKind();
4465
4466 if (MemberSpecializationInfo *MSInfo =
4467 dyn_cast_if_present<MemberSpecializationInfo *>(
4468 TemplateOrSpecialization))
4469 return MSInfo->getTemplateSpecializationKind();
4470
4471 // A dependent function template specialization is an explicit specialization,
4472 // except when it's a friend declaration.
4474 TemplateOrSpecialization) &&
4477
4478 return TSK_Undeclared;
4479}
4480
4483 // This is the same as getTemplateSpecializationKind(), except that for a
4484 // function that is both a function template specialization and a member
4485 // specialization, we prefer the member specialization information. Eg:
4486 //
4487 // template<typename T> struct A {
4488 // template<typename U> void f() {}
4489 // template<> void f<int>() {}
4490 // };
4491 //
4492 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4493 // template specialization; both getTemplateSpecializationKind() and
4494 // getTemplateSpecializationKindForInstantiation() will return
4495 // TSK_ExplicitSpecialization.
4496 //
4497 // For A<int>::f<int>():
4498 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4499 // * getTemplateSpecializationKindForInstantiation() will return
4500 // TSK_ImplicitInstantiation
4501 //
4502 // This reflects the facts that A<int>::f<int> is an explicit specialization
4503 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4504 // from A::f<int> if a definition is needed.
4506 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4507 TemplateOrSpecialization)) {
4508 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4509 return MSInfo->getTemplateSpecializationKind();
4510 return FTSInfo->getTemplateSpecializationKind();
4511 }
4512
4513 if (MemberSpecializationInfo *MSInfo =
4514 dyn_cast_if_present<MemberSpecializationInfo *>(
4515 TemplateOrSpecialization))
4516 return MSInfo->getTemplateSpecializationKind();
4517
4519 TemplateOrSpecialization) &&
4522
4523 return TSK_Undeclared;
4524}
4525
4526void
4528 SourceLocation PointOfInstantiation) {
4530 dyn_cast<FunctionTemplateSpecializationInfo *>(
4531 TemplateOrSpecialization)) {
4532 FTSInfo->setTemplateSpecializationKind(TSK);
4533 if (TSK != TSK_ExplicitSpecialization &&
4534 PointOfInstantiation.isValid() &&
4535 FTSInfo->getPointOfInstantiation().isInvalid()) {
4536 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4538 L->InstantiationRequested(this);
4539 }
4540 } else if (MemberSpecializationInfo *MSInfo =
4541 dyn_cast<MemberSpecializationInfo *>(
4542 TemplateOrSpecialization)) {
4543 MSInfo->setTemplateSpecializationKind(TSK);
4544 if (TSK != TSK_ExplicitSpecialization &&
4545 PointOfInstantiation.isValid() &&
4546 MSInfo->getPointOfInstantiation().isInvalid()) {
4547 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4549 L->InstantiationRequested(this);
4550 }
4551 } else
4552 llvm_unreachable("Function cannot have a template specialization kind");
4553}
4554
4556 auto HasImplicitAttr = [this](const Attr *A) {
4557 return A ? A->isImplicit() : isImplicit();
4558 };
4559 if (!HasImplicitAttr(getAttr<CUDAHostAttr>()) ||
4560 !HasImplicitAttr(getAttr<CUDADeviceAttr>()))
4561 return false;
4562 auto IsExplicitInstTSK = [](TemplateSpecializationKind TSK) {
4565 };
4566 if (IsExplicitInstTSK(getTemplateSpecializationKind()))
4567 return true;
4568 if (const auto *MD = dyn_cast<CXXMethodDecl>(this))
4569 if (const auto *Spec =
4570 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()))
4571 return IsExplicitInstTSK(Spec->getTemplateSpecializationKind());
4572 return false;
4573}
4574
4577 = TemplateOrSpecialization.dyn_cast<
4579 return FTSInfo->getPointOfInstantiation();
4580 if (MemberSpecializationInfo *MSInfo =
4581 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4582 return MSInfo->getPointOfInstantiation();
4583
4584 return SourceLocation();
4585}
4586
4588 if (Decl::isOutOfLine())
4589 return true;
4590
4591 // If this function was instantiated from a member function of a
4592 // class template, check whether that member function was defined out-of-line.
4594 const FunctionDecl *Definition;
4595 if (FD->hasBody(Definition))
4596 return Definition->isOutOfLine();
4597 }
4598
4599 // If this function was instantiated from a function template,
4600 // check whether that function template was defined out-of-line.
4601 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4602 const FunctionDecl *Definition;
4603 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4604 return Definition->isOutOfLine();
4605 }
4606
4607 return false;
4608}
4609
4611 return SourceRange(getOuterLocStart(), EndRangeLoc);
4612}
4613
4615 IdentifierInfo *FnInfo = getIdentifier();
4616
4617 if (!FnInfo)
4618 return 0;
4619
4620 // Builtin handling.
4621 switch (getBuiltinID()) {
4622 case Builtin::BI__builtin_memset:
4623 case Builtin::BI__builtin___memset_chk:
4624 case Builtin::BImemset:
4625 return Builtin::BImemset;
4626
4627 case Builtin::BI__builtin_memcpy:
4628 case Builtin::BI__builtin___memcpy_chk:
4629 case Builtin::BImemcpy:
4630 return Builtin::BImemcpy;
4631
4632 case Builtin::BI__builtin_mempcpy:
4633 case Builtin::BI__builtin___mempcpy_chk:
4634 case Builtin::BImempcpy:
4635 return Builtin::BImempcpy;
4636
4637 case Builtin::BI__builtin_trivially_relocate:
4638 case Builtin::BI__builtin_memmove:
4639 case Builtin::BI__builtin___memmove_chk:
4640 case Builtin::BImemmove:
4641 return Builtin::BImemmove;
4642
4643 case Builtin::BI__builtin_strlcpy:
4644 case Builtin::BIstrlcpy:
4645 case Builtin::BI__builtin___strlcpy_chk:
4646 return Builtin::BIstrlcpy;
4647
4648 case Builtin::BI__builtin_strlcat:
4649 case Builtin::BIstrlcat:
4650 case Builtin::BI__builtin___strlcat_chk:
4651 return Builtin::BIstrlcat;
4652
4653 case Builtin::BI__builtin_memcmp:
4654 case Builtin::BImemcmp:
4655 return Builtin::BImemcmp;
4656
4657 case Builtin::BI__builtin_bcmp:
4658 case Builtin::BIbcmp:
4659 return Builtin::BIbcmp;
4660
4661 case Builtin::BI__builtin_strncpy:
4662 case Builtin::BI__builtin___strncpy_chk:
4663 case Builtin::BIstrncpy:
4664 return Builtin::BIstrncpy;
4665
4666 case Builtin::BI__builtin_strncmp:
4667 case Builtin::BIstrncmp:
4668 return Builtin::BIstrncmp;
4669
4670 case Builtin::BI__builtin_strncasecmp:
4671 case Builtin::BIstrncasecmp:
4672 return Builtin::BIstrncasecmp;
4673
4674 case Builtin::BI__builtin_strncat:
4675 case Builtin::BI__builtin___strncat_chk:
4676 case Builtin::BIstrncat:
4677 return Builtin::BIstrncat;
4678
4679 case Builtin::BI__builtin_strndup:
4680 case Builtin::BIstrndup:
4681 return Builtin::BIstrndup;
4682
4683 case Builtin::BI__builtin_strlen:
4684 case Builtin::BIstrlen:
4685 return Builtin::BIstrlen;
4686
4687 case Builtin::BI__builtin_bzero:
4688 case Builtin::BIbzero:
4689 return Builtin::BIbzero;
4690
4691 case Builtin::BI__builtin_bcopy:
4692 case Builtin::BIbcopy:
4693 return Builtin::BIbcopy;
4694
4695 case Builtin::BIfree:
4696 return Builtin::BIfree;
4697
4698 default:
4699 if (isExternC()) {
4700 if (FnInfo->isStr("memset"))
4701 return Builtin::BImemset;
4702 if (FnInfo->isStr("memcpy"))
4703 return Builtin::BImemcpy;
4704 if (FnInfo->isStr("mempcpy"))
4705 return Builtin::BImempcpy;
4706 if (FnInfo->isStr("memmove"))
4707 return Builtin::BImemmove;
4708 if (FnInfo->isStr("memcmp"))
4709 return Builtin::BImemcmp;
4710 if (FnInfo->isStr("bcmp"))
4711 return Builtin::BIbcmp;
4712 if (FnInfo->isStr("strncpy"))
4713 return Builtin::BIstrncpy;
4714 if (FnInfo->isStr("strncmp"))
4715 return Builtin::BIstrncmp;
4716 if (FnInfo->isStr("strncasecmp"))
4717 return Builtin::BIstrncasecmp;
4718 if (FnInfo->isStr("strncat"))
4719 return Builtin::BIstrncat;
4720 if (FnInfo->isStr("strndup"))
4721 return Builtin::BIstrndup;
4722 if (FnInfo->isStr("strlen"))
4723 return Builtin::BIstrlen;
4724 if (FnInfo->isStr("bzero"))
4725 return Builtin::BIbzero;
4726 if (FnInfo->isStr("bcopy"))
4727 return Builtin::BIbcopy;
4728 if (FnInfo->isStr("strlcat"))
4729 return Builtin::BIstrlcat;
4730 if (FnInfo->isStr("strlcpy"))
4731 return Builtin::BIstrlcpy;
4732 } else if (isInStdNamespace()) {
4733 if (FnInfo->isStr("free"))
4734 return Builtin::BIfree;
4735 }
4736 break;
4737 }
4738 return 0;
4739}
4740
4742 assert(hasODRHash());
4743 return ODRHash;
4744}
4745
4747 if (hasODRHash())
4748 return ODRHash;
4749
4750 if (auto *FT = getInstantiatedFromMemberFunction()) {
4751 setHasODRHash(true);
4752 ODRHash = FT->getODRHash();
4753 return ODRHash;
4754 }
4755
4756 class ODRHash Hash;
4757 Hash.AddFunctionDecl(this);
4758 setHasODRHash(true);
4759 ODRHash = Hash.CalculateHash();
4760 return ODRHash;
4761}
4762
4763//===----------------------------------------------------------------------===//
4764// FieldDecl Implementation
4765//===----------------------------------------------------------------------===//
4766
4768 SourceLocation StartLoc, SourceLocation IdLoc,
4769 const IdentifierInfo *Id, QualType T,
4770 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4771 InClassInitStyle InitStyle) {
4772 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4773 BW, Mutable, InitStyle);
4774}
4775
4777 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4778 SourceLocation(), nullptr, QualType(), nullptr,
4779 nullptr, false, ICIS_NoInit);
4780}
4781
4783 if (!isImplicit() || getDeclName())
4784 return false;
4785
4786 if (const auto *Record = getType()->getAsCanonical<RecordType>())
4787 return Record->getDecl()->isAnonymousStructOrUnion();
4788
4789 return false;
4790}
4791
4793 if (!hasInClassInitializer())
4794 return nullptr;
4795
4796 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4797 return cast_if_present<Expr>(
4798 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4799 : InitPtr.get(nullptr));
4800}
4801
4803 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4804}
4805
4806void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4808 if (BitField)
4809 InitAndBitWidth->Init = NewInit;
4810 else
4811 Init = NewInit;
4812}
4813
4815 const auto *CE = dyn_cast_if_present<ConstantExpr>(getBitWidth());
4816 return CE && CE->getAPValueResult().isInt();
4817}
4818
4820 assert(isBitField() && "not a bitfield");
4823 ->getAPValueResult()
4824 .getInt()
4825 .getZExtValue();
4826}
4827
4830 getBitWidthValue() == 0;
4831}
4832
4833bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4835 return true;
4836
4837 // C++2a [intro.object]p7:
4838 // An object has nonzero size if it
4839 // -- is not a potentially-overlapping subobject, or
4841 return false;
4842
4843 // -- is not of class type, or
4844 const auto *RT = getType()->getAsCanonical<RecordType>();
4845 if (!RT)
4846 return false;
4847 const RecordDecl *RD = RT->getDecl()->getDefinition();
4848 if (!RD) {
4849 assert(isInvalidDecl() && "valid field has incomplete type");
4850 return false;
4851 }
4852
4853 // -- [has] virtual member functions or virtual base classes, or
4854 // -- has subobjects of nonzero size or bit-fields of nonzero length
4855 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4856 if (!CXXRD->isEmpty())
4857 return false;
4858
4859 // Otherwise, [...] the circumstances under which the object has zero size
4860 // are implementation-defined.
4861 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4862 return true;
4863
4864 // MS ABI: has nonzero size if it is a class type with class type fields,
4865 // whether or not they have nonzero size
4866 return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4867 return Field->getType()->isRecordType();
4868 });
4869}
4870
4874
4875void FieldDecl::setCachedFieldIndex() const {
4876 assert(this == getCanonicalDecl() &&
4877 "should be called on the canonical decl");
4878
4879 unsigned Index = 0;
4880 const RecordDecl *RD = getParent()->getDefinition();
4881 assert(RD && "requested index for field of struct with no definition");
4882
4883 for (auto *Field : RD->fields()) {
4884 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4885 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4886 "overflow in field numbering");
4887 ++Index;
4888 }
4889
4890 assert(CachedFieldIndex && "failed to find field in parent");
4891}
4892
4894 const Expr *FinalExpr = getInClassInitializer();
4895 if (!FinalExpr)
4896 FinalExpr = getBitWidth();
4897 if (FinalExpr)
4898 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4900}
4901
4903 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4904 "capturing type in non-lambda or captured record.");
4905 assert(StorageKind == ISK_NoInit && !BitField &&
4906 "bit-field or field with default member initializer cannot capture "
4907 "VLA type");
4908 StorageKind = ISK_CapturedVLAType;
4909 CapturedVLAType = VLAType;
4910}
4911
4912void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4913 // Print unnamed members using name of their type.
4915 this->getType().print(OS, Policy);
4916 return;
4917 }
4918 // Otherwise, do the normal printing.
4919 DeclaratorDecl::printName(OS, Policy);
4920}
4921
4923 const auto *CAT = getType()->getAs<CountAttributedType>();
4924 if (!CAT)
4925 return nullptr;
4926
4927 const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr());
4928 const auto *CountDecl = CountDRE->getDecl();
4929 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl))
4930 CountDecl = IFD->getAnonField();
4931
4932 return dyn_cast<FieldDecl>(CountDecl);
4933}
4934
4935//===----------------------------------------------------------------------===//
4936// TagDecl Implementation
4937//===----------------------------------------------------------------------===//
4938
4940 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4941 SourceLocation StartL)
4942 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4943 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4944 assert((DK != Enum || TK == TagTypeKind::Enum) &&
4945 "EnumDecl not matched with TagTypeKind::Enum");
4946 setPreviousDecl(PrevDecl);
4947 setTagKind(TK);
4948 setCompleteDefinition(false);
4949 setBeingDefined(false);
4951 setFreeStanding(false);
4953 TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4954}
4955
4959
4961 SourceLocation RBraceLoc = BraceRange.getEnd();
4962 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4963 return SourceRange(getOuterLocStart(), E);
4964}
4965
4967
4969 TypedefNameDeclOrQualifier = TDD;
4970 assert(isLinkageValid());
4971}
4972
4974 setBeingDefined(true);
4975
4976 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4977 struct CXXRecordDecl::DefinitionData *Data =
4978 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4979 for (auto *I : redecls())
4980 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4981 }
4982}
4983
4985 assert((!isa<CXXRecordDecl>(this) ||
4987 "definition completed but not started");
4988
4990 setBeingDefined(false);
4991
4993 L->CompletedTagDefinition(this);
4994}
4995
4998 return const_cast<TagDecl *>(this);
4999
5000 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
5001 return CXXRD->getDefinition();
5002
5003 for (TagDecl *R :
5005 if (R->isCompleteDefinition() || R->isBeingDefined())
5006 return R;
5007 return nullptr;
5008}
5009
5011 if (QualifierLoc) {
5012 // Make sure the extended qualifier info is allocated.
5013 if (!hasExtInfo())
5014 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
5015 // Set qualifier info.
5016 getExtInfo()->QualifierLoc = QualifierLoc;
5017 } else {
5018 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
5019 if (hasExtInfo()) {
5020 if (getExtInfo()->NumTemplParamLists == 0) {
5021 getASTContext().Deallocate(getExtInfo());
5022 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
5023 }
5024 else
5025 getExtInfo()->QualifierLoc = QualifierLoc;
5026 }
5027 }
5028}
5029
5031 llvm::raw_ostream &OS, const PrintingPolicy &Policy) const {
5032 PresumedLoc PLoc =
5034 if (!PLoc.isValid())
5035 return;
5036
5037 OS << " at ";
5038 StringRef File = PLoc.getFilename();
5039 llvm::SmallString<1024> WrittenFile(File);
5040 if (auto *Callbacks = Policy.Callbacks)
5041 WrittenFile = Callbacks->remapPath(File);
5042 // Fix inconsistent path separator created by
5043 // clang::DirectoryLookup::LookupFile when the file path is relative
5044 // path.
5045 llvm::sys::path::Style Style =
5046 llvm::sys::path::is_absolute(WrittenFile)
5047 ? llvm::sys::path::Style::native
5048 : (Policy.MSVCFormatting ? llvm::sys::path::Style::windows_backslash
5049 : llvm::sys::path::Style::posix);
5050 llvm::sys::path::native(WrittenFile, Style);
5051 OS << WrittenFile << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
5052}
5053
5054void TagDecl::printAnonymousTagDecl(llvm::raw_ostream &OS,
5055 const PrintingPolicy &Policy) const {
5057 assert(Typedef->getIdentifier() && "Typedef without identifier?");
5058 OS << Typedef->getIdentifier()->getName();
5059 return;
5060 }
5061
5062 bool SuppressTagKeywordInName = Policy.SuppressTagKeywordInAnonNames;
5063
5064 // Emit leading keyword. Since we printed a leading keyword make sure we
5065 // don't print the tag as part of the name too.
5066 if (!Policy.SuppressTagKeyword) {
5067 OS << getKindName() << ' ';
5068 SuppressTagKeywordInName = true;
5069 }
5070
5071 // Make an unambiguous representation for anonymous types, e.g.
5072 // (anonymous enum at /usr/include/string.h:120:9)
5073 OS << (Policy.MSVCFormatting ? '`' : '(');
5074
5075 if (isa<CXXRecordDecl>(this) && cast<CXXRecordDecl>(this)->isLambda()) {
5076 OS << "lambda";
5077 SuppressTagKeywordInName = true;
5078 } else if ((isa<RecordDecl>(this) &&
5079 cast<RecordDecl>(this)->isAnonymousStructOrUnion())) {
5080 OS << "anonymous";
5081 } else {
5082 OS << "unnamed";
5083 }
5084
5085 if (!SuppressTagKeywordInName)
5086 OS << ' ' << getKindName();
5087
5088 if (Policy.AnonymousTagNameStyle ==
5091
5092 OS << (Policy.MSVCFormatting ? '\'' : ')');
5093}
5094
5095void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
5097 // If the name is supposed to have an identifier but does not have one, then
5098 // the tag is anonymous and we should print it differently.
5099 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
5100 printAnonymousTagDecl(OS, Policy);
5101
5102 return;
5103 }
5104
5105 // Otherwise, do the normal printing.
5106 Name.print(OS, Policy);
5107}
5108
5111 assert(!TPLists.empty());
5112 // Make sure the extended decl info is allocated.
5113 if (!hasExtInfo())
5114 // Allocate external info struct.
5115 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
5116 // Set the template parameter lists info.
5117 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
5118}
5119
5120//===----------------------------------------------------------------------===//
5121// EnumDecl Implementation
5122//===----------------------------------------------------------------------===//
5123
5124EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5125 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
5126 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
5127 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5128 assert(Scoped || !ScopedUsingClassTag);
5129 IntegerType = nullptr;
5130 setNumPositiveBits(0);
5131 setNumNegativeBits(0);
5132 setScoped(Scoped);
5133 setScopedUsingClassTag(ScopedUsingClassTag);
5134 setFixed(Fixed);
5135 setHasODRHash(false);
5136 ODRHash = 0;
5137}
5138
5139void EnumDecl::anchor() {}
5140
5142 SourceLocation StartLoc, SourceLocation IdLoc,
5143 IdentifierInfo *Id,
5144 EnumDecl *PrevDecl, bool IsScoped,
5145 bool IsScopedUsingClassTag, bool IsFixed) {
5146 return new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, IsScoped,
5147 IsScopedUsingClassTag, IsFixed);
5148}
5149
5151 return new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
5152 nullptr, nullptr, false, false, false);
5153}
5154
5156 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
5157 return TI->getTypeLoc().getSourceRange();
5158 return SourceRange();
5159}
5160
5162 QualType NewPromotionType,
5163 unsigned NumPositiveBits,
5164 unsigned NumNegativeBits) {
5165 assert(!isCompleteDefinition() && "Cannot redefine enums!");
5166 if (!IntegerType)
5167 IntegerType = NewType.getTypePtr();
5168 PromotionType = NewPromotionType;
5169 setNumPositiveBits(NumPositiveBits);
5170 setNumNegativeBits(NumNegativeBits);
5172}
5173
5175 if (const auto *A = getAttr<EnumExtensibilityAttr>())
5176 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
5177 return true;
5178}
5179
5181 return isClosed() && hasAttr<FlagEnumAttr>();
5182}
5183
5185 return isClosed() && !hasAttr<FlagEnumAttr>();
5186}
5187
5190 return MSI->getTemplateSpecializationKind();
5191
5192 return TSK_Undeclared;
5193}
5194
5196 SourceLocation PointOfInstantiation) {
5198 assert(MSI && "Not an instantiated member enumeration?");
5200 if (TSK != TSK_ExplicitSpecialization &&
5201 PointOfInstantiation.isValid() &&
5203 MSI->setPointOfInstantiation(PointOfInstantiation);
5204}
5205
5208 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
5209 EnumDecl *ED = getInstantiatedFromMemberEnum();
5210 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5211 ED = NewED;
5212 return ED;
5213 }
5214 }
5215
5217 "couldn't find pattern for enum instantiation");
5218 return nullptr;
5219}
5220
5222 if (SpecializationInfo)
5223 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
5224
5225 return nullptr;
5226}
5227
5228void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
5230 assert(!SpecializationInfo && "Member enum is already a specialization");
5231 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
5232}
5233
5235 if (hasODRHash())
5236 return ODRHash;
5237
5238 class ODRHash Hash;
5239 Hash.AddEnumDecl(this);
5240 setHasODRHash(true);
5241 ODRHash = Hash.CalculateHash();
5242 return ODRHash;
5243}
5244
5246 auto Res = TagDecl::getSourceRange();
5247 // Set end-point to enum-base, e.g. enum foo : ^bar
5248 if (auto *TSI = getIntegerTypeSourceInfo()) {
5249 // TagDecl doesn't know about the enum base.
5250 if (!getBraceRange().getEnd().isValid())
5251 Res.setEnd(TSI->getTypeLoc().getEndLoc());
5252 }
5253 return Res;
5254}
5255
5256void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
5257 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
5258 unsigned NumNegativeBits = getNumNegativeBits();
5259 unsigned NumPositiveBits = getNumPositiveBits();
5260
5261 if (NumNegativeBits) {
5262 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
5263 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
5264 Min = -Max;
5265 } else {
5266 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
5267 Min = llvm::APInt::getZero(Bitwidth);
5268 }
5269}
5270
5271//===----------------------------------------------------------------------===//
5272// RecordDecl Implementation
5273//===----------------------------------------------------------------------===//
5274
5276 DeclContext *DC, SourceLocation StartLoc,
5277 SourceLocation IdLoc, IdentifierInfo *Id,
5278 RecordDecl *PrevDecl)
5279 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5280 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5283 setHasObjectMember(false);
5284 setHasVolatileMember(false);
5295 setIsRandomized(false);
5296 setODRHash(0);
5297}
5298
5300 SourceLocation StartLoc, SourceLocation IdLoc,
5301 IdentifierInfo *Id, RecordDecl* PrevDecl) {
5302 return new (C, DC)
5303 RecordDecl(Record, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl);
5304}
5305
5307 GlobalDeclID ID) {
5308 return new (C, ID)
5310 SourceLocation(), nullptr, nullptr);
5311}
5312
5314 if (auto RD = dyn_cast<CXXRecordDecl>(this))
5315 return RD->isLambda();
5316 return false;
5317}
5318
5322
5324 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
5325}
5326
5328 if (isUnion())
5329 return true;
5330
5331 if (const RecordDecl *Def = getDefinition()) {
5332 for (const FieldDecl *FD : Def->fields()) {
5333 const RecordType *RT = FD->getType()->getAsCanonical<RecordType>();
5334 if (RT && RT->getDecl()->isOrContainsUnion())
5335 return true;
5336 }
5337 }
5338
5339 return false;
5340}
5341
5344 LoadFieldsFromExternalStorage();
5345 // This is necessary for correctness for C++ with modules.
5346 // FIXME: Come up with a test case that breaks without definition.
5347 if (RecordDecl *D = getDefinition(); D && D != this)
5348 return D->field_begin();
5350}
5351
5355
5356/// completeDefinition - Notes that the definition of this type is now
5357/// complete.
5359 assert(!isCompleteDefinition() && "Cannot redefine record!");
5361
5362 ASTContext &Ctx = getASTContext();
5363
5364 // Layouts are dumped when computed, so if we are dumping for all complete
5365 // types, we need to force usage to get types that wouldn't be used elsewhere.
5366 //
5367 // If the type is dependent, then we can't compute its layout because there
5368 // is no way for us to know the size or alignment of a dependent type. Also
5369 // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5370 // on that.
5371 if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5372 !isInvalidDecl())
5373 (void)Ctx.getASTRecordLayout(this);
5374}
5375
5376/// isMsStruct - Get whether or not this record uses ms_struct layout.
5377/// This which can be turned on with an attribute, pragma, or the
5378/// -mms-bitfields command-line option.
5381 return false;
5383 return true;
5384 auto LayoutCompatibility = C.getLangOpts().getLayoutCompatibility();
5385 if (LayoutCompatibility == LangOptions::LayoutCompatibilityKind::Default)
5386 return C.defaultsToMsStruct();
5387 return LayoutCompatibility == LangOptions::LayoutCompatibilityKind::Microsoft;
5388}
5389
5391 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
5392 LastDecl->NextInContextAndBits.setPointer(nullptr);
5393 setIsRandomized(true);
5394}
5395
5396void RecordDecl::LoadFieldsFromExternalStorage() const {
5398 assert(hasExternalLexicalStorage() && Source && "No external storage?");
5399
5400 // Notify that we have a RecordDecl doing some initialization.
5401 ExternalASTSource::Deserializing TheFields(Source);
5402
5405 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
5407 }, Decls);
5408
5409#ifndef NDEBUG
5410 // Check that all decls we got were FieldDecls.
5411 for (unsigned i=0, e=Decls.size(); i != e; ++i)
5412 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5413#endif
5414
5415 if (Decls.empty())
5416 return;
5417
5418 auto [ExternalFirst, ExternalLast] =
5419 BuildDeclChain(Decls,
5420 /*FieldsAlreadyLoaded=*/false);
5421 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5422 FirstDecl = ExternalFirst;
5423 if (!LastDecl)
5424 LastDecl = ExternalLast;
5425}
5426
5427bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5428 ASTContext &Context = getASTContext();
5429 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5430 (SanitizerKind::Address | SanitizerKind::KernelAddress);
5431 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5432 return false;
5433 const auto &NoSanitizeList = Context.getNoSanitizeList();
5434 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
5435 // We may be able to relax some of these requirements.
5436 int ReasonToReject = -1;
5437 if (!CXXRD || CXXRD->isExternCContext())
5438 ReasonToReject = 0; // is not C++.
5439 else if (CXXRD->hasAttr<PackedAttr>())
5440 ReasonToReject = 1; // is packed.
5441 else if (CXXRD->isUnion())
5442 ReasonToReject = 2; // is a union.
5443 else if (CXXRD->isTriviallyCopyable())
5444 ReasonToReject = 3; // is trivially copyable.
5445 else if (CXXRD->hasTrivialDestructor())
5446 ReasonToReject = 4; // has trivial destructor.
5447 else if (CXXRD->isStandardLayout())
5448 ReasonToReject = 5; // is standard layout.
5449 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
5450 "field-padding"))
5451 ReasonToReject = 6; // is in an excluded file.
5453 EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
5454 ReasonToReject = 7; // The type is excluded.
5455
5456 if (EmitRemark) {
5457 if (ReasonToReject >= 0)
5458 Context.getDiagnostics().Report(
5459 getLocation(),
5460 diag::remark_sanitize_address_insert_extra_padding_rejected)
5461 << getQualifiedNameAsString() << ReasonToReject;
5462 else
5463 Context.getDiagnostics().Report(
5464 getLocation(),
5465 diag::remark_sanitize_address_insert_extra_padding_accepted)
5467 }
5468 return ReasonToReject < 0;
5469}
5470
5472 for (const auto *I : fields()) {
5473 if (I->getIdentifier())
5474 return I;
5475
5476 if (const auto *RD = I->getType()->getAsRecordDecl())
5477 if (const FieldDecl *NamedDataMember = RD->findFirstNamedDataMember())
5478 return NamedDataMember;
5479 }
5480
5481 // We didn't find a named data member.
5482 return nullptr;
5483}
5484
5486 if (hasODRHash())
5487 return RecordDeclBits.ODRHash;
5488
5489 // Only calculate hash on first call of getODRHash per record.
5490 ODRHash Hash;
5491 Hash.AddRecordDecl(this);
5492 // For RecordDecl the ODRHash is stored in the remaining
5493 // bits of RecordDeclBits, adjust the hash to accommodate.
5494 static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32);
5495 setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits));
5496 return RecordDeclBits.ODRHash;
5497}
5498
5499//===----------------------------------------------------------------------===//
5500// BlockDecl Implementation
5501//===----------------------------------------------------------------------===//
5502
5504 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5505 setIsVariadic(false);
5506 setCapturesCXXThis(false);
5509 setDoesNotEscape(false);
5510 setCanAvoidCopyToHeap(false);
5511}
5512
5514 assert(!ParamInfo && "Already has param info!");
5515
5516 // Zero params -> null pointer.
5517 if (!NewParamInfo.empty()) {
5518 NumParams = NewParamInfo.size();
5519 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5520 llvm::copy(NewParamInfo, ParamInfo);
5521 }
5522}
5523
5525 bool CapturesCXXThis) {
5526 this->setCapturesCXXThis(CapturesCXXThis);
5527 this->NumCaptures = Captures.size();
5528
5529 if (Captures.empty()) {
5530 this->Captures = nullptr;
5531 return;
5532 }
5533
5534 this->Captures = Captures.copy(Context).data();
5535}
5536
5537bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5538 for (const auto &I : captures())
5539 // Only auto vars can be captured, so no redeclaration worries.
5540 if (I.getVariable() == variable)
5541 return true;
5542
5543 return false;
5544}
5545
5547 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5548}
5549
5550//===----------------------------------------------------------------------===//
5551// Other Decl Allocation/Deallocation Method Implementations
5552//===----------------------------------------------------------------------===//
5553
5554void TranslationUnitDecl::anchor() {}
5555
5557 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5558}
5559
5561 AnonymousNamespace = D;
5562
5563 if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5564 Listener->AddedAnonymousNamespace(this, D);
5565}
5566
5567void PragmaCommentDecl::anchor() {}
5568
5569PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
5571 SourceLocation CommentLoc,
5572 PragmaMSCommentKind CommentKind,
5573 StringRef Arg) {
5574 PragmaCommentDecl *PCD =
5575 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
5576 PragmaCommentDecl(DC, CommentLoc, CommentKind);
5577 llvm::copy(Arg, PCD->getTrailingObjects());
5578 PCD->getTrailingObjects()[Arg.size()] = '\0';
5579 return PCD;
5580}
5581
5583 GlobalDeclID ID,
5584 unsigned ArgSize) {
5585 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
5586 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
5587}
5588
5589void PragmaDetectMismatchDecl::anchor() {}
5590
5593 SourceLocation Loc, StringRef Name,
5594 StringRef Value) {
5595 size_t ValueStart = Name.size() + 1;
5596 PragmaDetectMismatchDecl *PDMD =
5597 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
5598 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5599 llvm::copy(Name, PDMD->getTrailingObjects());
5600 PDMD->getTrailingObjects()[Name.size()] = '\0';
5601 llvm::copy(Value, PDMD->getTrailingObjects() + ValueStart);
5602 PDMD->getTrailingObjects()[ValueStart + Value.size()] = '\0';
5603 return PDMD;
5604}
5605
5608 unsigned NameValueSize) {
5609 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5610 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
5611}
5612
5613void ExternCContextDecl::anchor() {}
5614
5615ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
5616 TranslationUnitDecl *DC) {
5617 return new (C, DC) ExternCContextDecl(DC);
5618}
5619
5620void LabelDecl::anchor() {}
5621
5623 SourceLocation IdentL, IdentifierInfo *II) {
5624 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5625}
5626
5628 SourceLocation IdentL, IdentifierInfo *II,
5629 SourceLocation GnuLabelL) {
5630 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5631 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5632}
5633
5635 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5636 SourceLocation());
5637}
5638
5639void LabelDecl::setMSAsmLabel(StringRef Name) {
5640char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5641llvm::copy(Name, Buffer);
5642Buffer[Name.size()] = '\0';
5643MSAsmName = Buffer;
5644}
5645
5646void ValueDecl::anchor() {}
5647
5648bool ValueDecl::isWeak() const {
5649 auto *MostRecent = getMostRecentDecl();
5650 return MostRecent->hasAttr<WeakAttr>() ||
5651 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5652}
5653
5655 if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5656 return Var->isInitCapture();
5657 return false;
5658}
5659
5661 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
5662 return NTTP->isParameterPack();
5663
5664 return isa_and_nonnull<PackExpansionType>(getType().getTypePtrOrNull());
5665}
5666
5667void ImplicitParamDecl::anchor() {}
5668
5670 SourceLocation IdLoc,
5671 const IdentifierInfo *Id,
5672 QualType Type,
5673 ImplicitParamKind ParamKind) {
5674 auto *Parm = new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5676 return Parm;
5677}
5678
5680 ImplicitParamKind ParamKind) {
5681 auto *Parm = new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5683 return Parm;
5684}
5685
5690
5693 const DeclarationNameInfo &NameInfo, QualType T,
5694 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5696 ConstexprSpecKind ConstexprKind,
5697 const AssociatedConstraint &TrailingRequiresClause) {
5698 FunctionDecl *New = new (C, DC) FunctionDecl(
5699 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5700 isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5701 New->setHasWrittenPrototype(hasWrittenPrototype);
5702 return New;
5703}
5704
5706 return new (C, ID) FunctionDecl(
5708 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified,
5709 /*TrailingRequiresClause=*/{});
5710}
5711
5713 return hasAttr<CUDAGlobalAttr>() ||
5714 DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>());
5715}
5716
5718 return new (C, DC) BlockDecl(DC, L);
5719}
5720
5724
5725OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams)
5726 : Decl(OutlinedFunction, DC, SourceLocation()),
5727 DeclContext(OutlinedFunction), NumParams(NumParams),
5728 BodyAndNothrow(nullptr, false) {}
5729
5731 DeclContext *DC,
5732 unsigned NumParams) {
5733 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5734 OutlinedFunctionDecl(DC, NumParams);
5735}
5736
5739 unsigned NumParams) {
5740 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5741 OutlinedFunctionDecl(nullptr, NumParams);
5742}
5743
5745 return BodyAndNothrow.getPointer();
5746}
5747void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5748
5749bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5751 BodyAndNothrow.setInt(Nothrow);
5752}
5753
5754CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5755 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5756 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5757
5759 unsigned NumParams) {
5760 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5761 CapturedDecl(DC, NumParams);
5762}
5763
5765 unsigned NumParams) {
5766 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5767 CapturedDecl(nullptr, NumParams);
5768}
5769
5770Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5771void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5772
5773bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5774void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5775
5778 QualType T, Expr *E, const llvm::APSInt &V)
5779 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5780 setInitVal(C, V);
5781}
5782
5786 Expr *E, const llvm::APSInt &V) {
5787 return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5788}
5789
5791 GlobalDeclID ID) {
5792 return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5793 QualType(), nullptr, llvm::APSInt());
5794}
5795
5796void IndirectFieldDecl::anchor() {}
5797
5798IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5800 QualType T,
5802 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5803 ChainingSize(CH.size()) {
5804 // In C++, indirect field declarations conflict with tag declarations in the
5805 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5806 if (C.getLangOpts().CPlusPlus)
5808}
5809
5812 const IdentifierInfo *Id,
5813 QualType T,
5815 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5816}
5817
5819 GlobalDeclID ID) {
5820 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
5821 DeclarationName(), QualType(), {});
5822}
5823
5826 if (Init)
5827 End = Init->getEndLoc();
5828 return SourceRange(getLocation(), End);
5829}
5830
5831void TypeDecl::anchor() {}
5832
5834 SourceLocation StartLoc, SourceLocation IdLoc,
5835 const IdentifierInfo *Id,
5836 TypeSourceInfo *TInfo) {
5837 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5838}
5839
5840void TypedefNameDecl::anchor() {}
5841
5843 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5844 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5845 auto *ThisTypedef = this;
5846 if (AnyRedecl && OwningTypedef) {
5847 OwningTypedef = OwningTypedef->getCanonicalDecl();
5848 ThisTypedef = ThisTypedef->getCanonicalDecl();
5849 }
5850 if (OwningTypedef == ThisTypedef)
5851 return TT->getDecl()->getDefinitionOrSelf();
5852 }
5853
5854 return nullptr;
5855}
5856
5857bool TypedefNameDecl::isTransparentTagSlow() const {
5858 auto determineIsTransparent = [&]() {
5859 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5860 if (auto *TD = TT->getDecl()) {
5861 if (TD->getName() != getName())
5862 return false;
5863 SourceLocation TTLoc = getLocation();
5864 SourceLocation TDLoc = TD->getLocation();
5865 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5866 return false;
5868 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5869 }
5870 }
5871 return false;
5872 };
5873
5874 bool isTransparent = determineIsTransparent();
5875 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5876 return isTransparent;
5877}
5878
5880 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5881 nullptr, nullptr);
5882}
5883
5885 SourceLocation StartLoc,
5886 SourceLocation IdLoc,
5887 const IdentifierInfo *Id,
5888 TypeSourceInfo *TInfo) {
5889 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5890}
5891
5893 GlobalDeclID ID) {
5894 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5895 SourceLocation(), nullptr, nullptr);
5896}
5897
5899 SourceLocation RangeEnd = getLocation();
5900 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5901 if (TInfo->getType().hasPostfixDeclaratorSyntax())
5902 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5903 }
5904 return SourceRange(getBeginLoc(), RangeEnd);
5905}
5906
5908 SourceLocation RangeEnd = getBeginLoc();
5909 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5910 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5911 return SourceRange(getBeginLoc(), RangeEnd);
5912}
5913
5914void FileScopeAsmDecl::anchor() {}
5915
5917 Expr *Str, SourceLocation AsmLoc,
5918 SourceLocation RParenLoc) {
5919 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5920}
5921
5923 GlobalDeclID ID) {
5924 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5925 SourceLocation());
5926}
5927
5931
5932void TopLevelStmtDecl::anchor() {}
5933
5934TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {
5935 assert(C.getLangOpts().IncrementalExtensions &&
5936 "Must be used only in incremental mode");
5937
5938 SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5939 DeclContext *DC = C.getTranslationUnitDecl();
5940
5941 return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5942}
5943
5945 GlobalDeclID ID) {
5946 return new (C, ID)
5947 TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5948}
5949
5951 return SourceRange(getLocation(), Statement->getEndLoc());
5952}
5953
5955 assert(S);
5956 Statement = S;
5957 setLocation(Statement->getBeginLoc());
5958}
5959
5960void EmptyDecl::anchor() {}
5961
5963 return new (C, DC) EmptyDecl(DC, L);
5964}
5965
5967 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5968}
5969
5970HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5971 SourceLocation KwLoc, IdentifierInfo *ID,
5972 SourceLocation IDLoc, SourceLocation LBrace)
5973 : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5974 DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5975 IsCBuffer(CBuffer), HasValidPackoffset(false), LayoutStruct(nullptr) {}
5976
5978 DeclContext *LexicalParent, bool CBuffer,
5979 SourceLocation KwLoc, IdentifierInfo *ID,
5980 SourceLocation IDLoc,
5981 SourceLocation LBrace) {
5982 // For hlsl like this
5983 // cbuffer A {
5984 // cbuffer B {
5985 // }
5986 // }
5987 // compiler should treat it as
5988 // cbuffer A {
5989 // }
5990 // cbuffer B {
5991 // }
5992 // FIXME: support nested buffers if required for back-compat.
5993 DeclContext *DC = LexicalParent;
5994 HLSLBufferDecl *Result =
5995 new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5996 return Result;
5997}
5998
6001 ArrayRef<Decl *> DefaultCBufferDecls) {
6002 DeclContext *DC = LexicalParent;
6003 IdentifierInfo *II = &C.Idents.get("$Globals", tok::TokenKind::identifier);
6004 HLSLBufferDecl *Result = new (C, DC) HLSLBufferDecl(
6005 DC, true, SourceLocation(), II, SourceLocation(), SourceLocation());
6006 Result->setImplicit(true);
6007 Result->setDefaultBufferDecls(DefaultCBufferDecls);
6008 return Result;
6009}
6010
6012 GlobalDeclID ID) {
6013 return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
6015}
6016
6018 assert(LayoutStruct == nullptr && "layout struct has already been set");
6019 LayoutStruct = LS;
6020 addDecl(LS);
6021}
6022
6023void HLSLBufferDecl::setDefaultBufferDecls(ArrayRef<Decl *> Decls) {
6024 assert(!Decls.empty());
6025 assert(DefaultBufferDecls.empty() && "default decls are already set");
6026 assert(isImplicit() &&
6027 "default decls can only be added to the implicit/default constant "
6028 "buffer $Globals");
6029
6030 // allocate array for default decls with ASTContext allocator
6031 Decl **DeclsArray = new (getASTContext()) Decl *[Decls.size()];
6032 llvm::copy(Decls, DeclsArray);
6033 DefaultBufferDecls = ArrayRef<Decl *>(DeclsArray, Decls.size());
6034}
6035
6038 return buffer_decl_iterator(llvm::iterator_range(DefaultBufferDecls.begin(),
6039 DefaultBufferDecls.end()),
6041}
6042
6044 return buffer_decl_iterator(
6045 llvm::iterator_range(DefaultBufferDecls.end(), DefaultBufferDecls.end()),
6047}
6048
6050 return DefaultBufferDecls.empty() && decls_empty();
6051}
6052
6053//===----------------------------------------------------------------------===//
6054// HLSLRootSignatureDecl Implementation
6055//===----------------------------------------------------------------------===//
6056
6057HLSLRootSignatureDecl::HLSLRootSignatureDecl(
6059 llvm::dxbc::RootSignatureVersion Version, unsigned NumElems)
6060 : NamedDecl(Decl::Kind::HLSLRootSignature, DC, Loc, DeclarationName(ID)),
6061 Version(Version), NumElems(NumElems) {}
6062
6063HLSLRootSignatureDecl *HLSLRootSignatureDecl::Create(
6065 llvm::dxbc::RootSignatureVersion Version,
6067 HLSLRootSignatureDecl *RSDecl =
6068 new (C, DC,
6069 additionalSizeToAlloc<llvm::hlsl::rootsig::RootElement>(
6070 RootElements.size()))
6071 HLSLRootSignatureDecl(DC, Loc, ID, Version, RootElements.size());
6072 auto *StoredElems = RSDecl->getElems();
6073 llvm::uninitialized_copy(RootElements, StoredElems);
6074 return RSDecl;
6075}
6076
6079 HLSLRootSignatureDecl *Result = new (C, ID)
6080 HLSLRootSignatureDecl(nullptr, SourceLocation(), nullptr,
6081 /*Version*/ llvm::dxbc::RootSignatureVersion::V1_1,
6082 /*NumElems=*/0);
6083 return Result;
6084}
6085
6086//===----------------------------------------------------------------------===//
6087// ImportDecl Implementation
6088//===----------------------------------------------------------------------===//
6089
6090/// Retrieve the number of module identifiers needed to name the given
6091/// module.
6092static unsigned getNumModuleIdentifiers(Module *Mod) {
6093 unsigned Result = 1;
6094 while (Mod->Parent) {
6095 Mod = Mod->Parent;
6096 ++Result;
6097 }
6098 return Result;
6099}
6100
6101ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
6102 Module *Imported,
6103 ArrayRef<SourceLocation> IdentifierLocs)
6104 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
6105 NextLocalImportAndComplete(nullptr, true) {
6106 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
6107 auto *StoredLocs = getTrailingObjects();
6108 llvm::uninitialized_copy(IdentifierLocs, StoredLocs);
6109}
6110
6111ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
6112 Module *Imported, SourceLocation EndLoc)
6113 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
6114 NextLocalImportAndComplete(nullptr, false) {
6115 *getTrailingObjects() = EndLoc;
6116}
6117
6119 SourceLocation StartLoc, Module *Imported,
6120 ArrayRef<SourceLocation> IdentifierLocs) {
6121 return new (C, DC,
6122 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
6123 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
6124}
6125
6127 SourceLocation StartLoc,
6128 Module *Imported,
6129 SourceLocation EndLoc) {
6130 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
6131 ImportDecl(DC, StartLoc, Imported, EndLoc);
6132 Import->setImplicit();
6133 return Import;
6134}
6135
6137 unsigned NumLocations) {
6138 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
6139 ImportDecl(EmptyShell());
6140}
6141
6143 if (!isImportComplete())
6144 return {};
6145
6146 return getTrailingObjects(getNumModuleIdentifiers(getImportedModule()));
6147}
6148
6150 if (!isImportComplete())
6151 return SourceRange(getLocation(), *getTrailingObjects());
6152
6153 return SourceRange(getLocation(), getIdentifierLocs().back());
6154}
6155
6156//===----------------------------------------------------------------------===//
6157// ExportDecl Implementation
6158//===----------------------------------------------------------------------===//
6159
6160void ExportDecl::anchor() {}
6161
6163 SourceLocation ExportLoc) {
6164 return new (C, DC) ExportDecl(DC, ExportLoc);
6165}
6166
6168 return new (C, ID) ExportDecl(nullptr, SourceLocation());
6169}
6170
6172 bool IncludeLocallyStreaming) {
6173 if (IncludeLocallyStreaming)
6174 if (FD->hasAttr<ArmLocallyStreamingAttr>())
6175 return true;
6176
6177 assert(!FD->getType().isNull() && "Expected a valid FunctionDecl");
6178 if (const auto *FPT = FD->getType()->getAs<FunctionProtoType>())
6179 if (FPT->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
6180 return true;
6181
6182 return false;
6183}
6184
6186 const auto *T = FD->getType()->getAs<FunctionProtoType>();
6187 return (T && FunctionType::getArmZAState(T->getAArch64SMEAttributes()) !=
6189 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
6190}
6191
6193 const auto *T = FD->getType()->getAs<FunctionProtoType>();
6194 return (T && FunctionType::getArmZT0State(T->getAArch64SMEAttributes()) !=
6196 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
6197}
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:6092
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:186
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:239
SourceManager & getSourceManager()
Definition ASTContext.h:907
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:926
const LangOptions & getLangOpts() const
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:965
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:5503
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5513
void setDoesNotEscape(bool B=true)
Definition Decl.h:4959
void setCapturesCXXThis(bool B=true)
Definition Decl.h:4940
void setCanAvoidCopyToHeap(bool B=true)
Definition Decl.h:4964
void setIsConversionFromLambda(bool val=true)
Definition Decl.h:4954
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4946
ArrayRef< Capture > captures() const
Definition Decl.h:4934
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5546
static BlockDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5721
void setIsVariadic(bool value)
Definition Decl.h:4883
bool capturesVariable(const VarDecl *var) const
Definition Decl.cpp:5537
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5524
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5717
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
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:5771
static CapturedDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumParams)
Definition Decl.cpp:5764
bool isNothrow() const
Definition Decl.cpp:5773
void setNothrow(bool Nothrow=true)
Definition Decl.cpp:5774
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition Decl.cpp:5758
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:5770
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:3908
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3498
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:823
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:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL)
Definition Decl.h:801
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2018
void setTrailingRequiresClause(const AssociatedConstraint &AC)
Definition Decl.cpp:2037
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4436
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5962
static EmptyDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5966
EnumConstantDecl(const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5776
static EnumConstantDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5790
void setInitVal(const ASTContext &C, const llvm::APSInt &V)
Definition Decl.h:3583
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5783
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5824
Represents an enum.
Definition Decl.h:4146
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4418
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition Decl.h:4356
unsigned getODRHash()
Definition Decl.cpp:5234
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:5195
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5141
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition Decl.h:4335
static EnumDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5150
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5180
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5155
SourceRange getSourceRange() const override LLVM_READONLY
Overrides to provide correct range when there's an enum-base specifier with forward declarations.
Definition Decl.cpp:5245
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5221
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition Decl.h:4345
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition Decl.cpp:5188
bool isClosed() const
Returns true if this enum is either annotated with enum_extensibility(closed) or isn't annotated with...
Definition Decl.cpp:5174
EnumDecl * getTemplateInstantiationPattern() const
Retrieve the enum definition from which this enumeration could be instantiated, if it is an instantia...
Definition Decl.cpp:5206
bool isClosedNonFlag() const
Returns true if this enum is annotated with neither flag_enum nor enum_extensibility(open).
Definition Decl.cpp:5184
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:5256
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition Decl.cpp:6162
static ExportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:6167
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:3722
QualType getType() const
Definition Expr.h:145
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5615
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:3295
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4792
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3475
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:3355
LazyDeclStmtPtr Init
Definition Decl.h:3345
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4819
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4782
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4893
bool hasConstantIntegerBitWidth() const
Determines whether the bit width of this field is a constant integer.
Definition Decl.cpp:4814
static FieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:4776
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4802
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
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:4833
InitAndBitWidthStorage * InitAndBitWidth
Definition Decl.h:3349
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:4767
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3542
static bool classofKind(Kind K)
Definition Decl.h:3547
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3401
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4828
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3411
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:4912
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4922
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition Decl.cpp:4871
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Definition Decl.cpp:4902
const VariableArrayType * CapturedVLAType
Definition Decl.h:3351
std::string getAsmString() const
Definition Decl.cpp:5928
const Expr * getAsmStringExpr() const
Definition Decl.h:4755
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5916
static FileScopeAsmDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5922
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2123
Stashed information about a defaulted/deleted function body, including the active FP pragma overrides...
Definition Decl.h:2090
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:2059
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4614
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2773
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:2820
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:2303
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
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:4246
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3777
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4239
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4234
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:2337
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:5705
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:4575
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:3052
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:3040
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:2905
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:4305
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:2617
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:4354
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2575
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4213
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4364
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:2440
bool isConstexprSpecified() const
Definition Decl.h:2606
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition Decl.cpp:4430
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
SourceRange getExceptionSpecSourceRange() const
Attempt to compute an informative source range covering the function exception specification,...
Definition Decl.cpp:4097
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:2367
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:4746
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition Decl.cpp:4482
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:4298
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3913
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition Decl.h:2064
@ TK_FunctionTemplateSpecialization
Definition Decl.h:2075
@ TK_DependentFunctionTemplateSpecialization
Definition Decl.h:2078
UsualDeleteParams getUsualDeleteParams() const
Definition Decl.cpp:3611
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3019
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4587
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition Decl.cpp:3570
bool FriendConstraintRefersToEnclosingTemplate() const
Definition Decl.h:2838
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4185
void setInstantiatedFromDecl(FunctionDecl *FD)
Specify that this function declaration was instantiated from a FunctionDecl FD.
Definition Decl.cpp:4252
bool isDeletedAsWritten() const
Definition Decl.h:2671
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:4419
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:2769
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition Decl.cpp:4263
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:2414
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:2390
LazyDeclStmtPtr Body
The body of the function.
Definition Decl.h:2180
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:2182
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:3047
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:2512
bool isReferenceableKernel() const
Definition Decl.cpp:5712
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4610
FunctionDecl * getInstantiatedFromDecl() const
Definition Decl.cpp:4258
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4527
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4179
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4171
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4458
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:2609
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:4555
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:4206
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:4119
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:2325
Redeclarable< FunctionDecl > redeclarable_base
Definition Decl.h:2274
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:4081
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:3030
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:2816
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4380
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
param_type_iterator param_type_begin() const
Definition TypeBase.h:5829
unsigned getNumParams() const
Definition TypeBase.h:5663
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5789
param_type_iterator param_type_end() const
Definition TypeBase.h:5833
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:4581
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4890
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4886
static std::string ExtractStringFromGCCAsmStmtComponent(const Expr *E)
Definition Stmt.cpp:554
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5329
buffer_decl_iterator buffer_decls_begin() const
Definition Decl.cpp:6037
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
Definition Decl.cpp:5977
void addLayoutStruct(CXXRecordDecl *LS)
Definition Decl.cpp:6017
bool buffer_decls_empty()
Definition Decl.cpp:6049
llvm::concat_iterator< Decl *const, SmallVector< Decl * >::const_iterator, decl_iterator > buffer_decl_iterator
Definition Decl.h:5399
static HLSLBufferDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:6011
buffer_decl_iterator buffer_decls_end() const
Definition Decl.cpp:6043
static HLSLBufferDecl * CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, ArrayRef< Decl * > DefaultCBufferDecls)
Definition Decl.cpp:6000
static HLSLRootSignatureDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, llvm::dxbc::RootSignatureVersion Version, ArrayRef< llvm::hlsl::rootsig::RootElement > RootElements)
Definition Decl.cpp:6063
static HLSLRootSignatureDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:6078
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:1782
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5669
static ImplicitParamDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5686
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition Decl.cpp:6118
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:6149
static ImportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumLocations)
Create a new, deserialized module import declaration.
Definition Decl.cpp:6136
friend class ASTContext
Definition Decl.h:5189
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:6142
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition Decl.h:5246
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:6126
static bool classofKind(Kind K)
Definition Decl.h:3644
static IndirectFieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5818
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5810
void setMSAsmLabel(StringRef Name)
Definition Decl.cpp:5639
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition Decl.cpp:5622
static LabelDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5634
@ 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:5146
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
ExplicitVisibilityKind
Kinds of explicit visibility.
Definition Decl.h:453
@ VisibilityForValue
Do an LV computation for, ultimately, a non-type declaration.
Definition Decl.h:462
@ VisibilityForType
Do an LV computation for, ultimately, a type.
Definition Decl.h:457
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:296
NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
Definition Decl.h:287
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:302
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:341
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:502
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:398
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:593
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:790
void AddFunctionDecl(const FunctionDecl *Function, bool SkipBody=false)
Definition ODRHash.cpp:697
void AddRecordDecl(const RecordDecl *Record)
Definition ODRHash.cpp:652
unsigned CalculateHash()
Definition ODRHash.cpp:244
Represents a partial function definition.
Definition Decl.h:5014
static OutlinedFunctionDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition Decl.cpp:5730
void setNothrow(bool Nothrow=true)
Definition Decl.cpp:5750
static OutlinedFunctionDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumParams)
Definition Decl.cpp:5738
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:5744
Represents a parameter to a function.
Definition Decl.h:1820
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:1826
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1949
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:1953
bool isDestroyedInCallee() const
Determines whether this parameter is destroyed in the callee function.
Definition Decl.cpp:2983
bool hasInheritedDefaultArg() const
Definition Decl.h:1965
bool isExplicitObjectParameter() const
Definition Decl.h:1908
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:5569
static PragmaCommentDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned ArgSize)
Definition Decl.cpp:5582
Represents a #pragma detect_mismatch line.
Definition Decl.h:202
static PragmaDetectMismatchDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation Loc, StringRef Name, StringRef Value)
Definition Decl.cpp:5592
static PragmaDetectMismatchDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NameValueSize)
Definition Decl.cpp:5607
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:8418
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:8464
Represents a struct/union/class.
Definition Decl.h:4460
bool hasLoadedFieldsFromExternalStorage() const
Definition Decl.h:4529
unsigned getODRHash()
Get precomputed ODRHash or add a new one.
Definition Decl.cpp:5485
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5313
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:5379
void setAnonymousStructOrUnion(bool Anon)
Definition Decl.h:4516
RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl)
Definition Decl.cpp:5275
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition Decl.cpp:5471
field_iterator noload_field_begin() const
Definition Decl.cpp:5352
void setArgPassingRestrictions(RecordArgPassingKind Kind)
Definition Decl.h:4606
void setNonTrivialToPrimitiveCopy(bool V)
Definition Decl.h:4550
bool isCapturedRecord() const
Determine whether this record is a record for captured variables in CapturedStmt construct.
Definition Decl.cpp:5319
void setHasNonTrivialToPrimitiveCopyCUnion(bool V)
Definition Decl.h:4582
field_range fields() const
Definition Decl.h:4663
void setHasNonTrivialToPrimitiveDestructCUnion(bool V)
Definition Decl.h:4574
void setHasFlexibleArrayMember(bool V)
Definition Decl.h:4497
void setParamDestroyedInCallee(bool V)
Definition Decl.h:4614
void setNonTrivialToPrimitiveDestroy(bool V)
Definition Decl.h:4558
void setHasObjectMember(bool val)
Definition Decl.h:4521
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5299
void setHasVolatileMember(bool val)
Definition Decl.h:4525
void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V)
Definition Decl.h:4566
void reorderDecls(const SmallVectorImpl< Decl * > &Decls)
Definition Decl.cpp:5390
void setIsRandomized(bool V)
Definition Decl.h:4620
static RecordDecl * CreateDeserialized(const ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5306
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition Decl.cpp:5427
static bool classof(const Decl *D)
Definition Decl.h:4700
bool isOrContainsUnion() const
Returns whether this record is a union, or contains (at any nesting level) a union member.
Definition Decl.cpp:5327
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5358
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition Decl.cpp:5323
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
void setHasUninitializedExplicitInitFields(bool V)
Definition Decl.h:4590
void setNonTrivialToPrimitiveDefaultInitialize(bool V)
Definition Decl.h:4542
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
friend class DeclContext
Definition Decl.h:4464
void setHasLoadedFieldsFromExternalStorage(bool val) const
Definition Decl.h:4533
field_iterator field_begin() const
Definition Decl.cpp:5342
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.
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:3852
void setTagKind(TagKind TK)
Definition Decl.h:4056
void setCompleteDefinitionRequired(bool V=true)
True if this complete decl is required to be complete for some existing use.
Definition Decl.h:3968
SourceRange getBraceRange() const
Definition Decl.h:3929
TagTypeKind TagKind
Definition Decl.h:3857
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3973
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:4996
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:3983
StringRef getKindName() const
Definition Decl.h:4048
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
redeclarable_base::redecl_iterator redecl_iterator
Definition Decl.h:3920
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4089
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4973
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4966
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4968
SourceLocation getOuterLocStart() const
Return SourceLocation representing start of source range taking into account any outer template decla...
Definition Decl.cpp:4956
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4960
void printAnonymousTagDeclLocation(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const
Definition Decl.cpp:5030
bool isUnion() const
Definition Decl.h:4063
void setBeingDefined(bool V=true)
True if this decl is currently being defined.
Definition Decl.h:3907
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:5010
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5109
void completeDefinition()
Completes the definition of this tag declaration.
Definition Decl.cpp:4984
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:5095
Redeclarable< TagDecl > redeclarable_base
Definition Decl.h:3887
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition Decl.h:3991
redeclarable_base::redecl_range redecl_range
Definition Decl.h:3919
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3998
void printAnonymousTagDecl(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const
Definition Decl.cpp:5054
TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, SourceLocation StartL)
Definition Decl.cpp:4939
void setCompleteDefinition(bool V=true)
True if this decl has its body fully specified.
Definition Decl.h:3956
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:5944
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5934
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5950
void setStmt(Stmt *S)
Definition Decl.cpp:5954
The top declaration context.
Definition Decl.h:106
static TranslationUnitDecl * Create(ASTContext &C)
Definition Decl.cpp:5556
ASTContext & getASTContext() const
Definition Decl.h:142
void setAnonymousNamespace(NamespaceDecl *D)
Definition Decl.cpp:5560
static TypeAliasDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5892
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5884
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5907
friend class ASTContext
Definition Decl.h:3649
TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, SourceLocation StartL=SourceLocation())
Definition Decl.h:3664
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
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:8389
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:8400
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9027
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:8754
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9071
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
bool isReferenceType() const
Definition TypeBase.h:8679
bool isEnumeralType() const
Definition TypeBase.h:8786
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:5034
bool isSamplerT() const
Definition TypeBase.h:8899
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9254
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5833
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5898
static TypedefDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition Decl.cpp:5879
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3747
QualType getUnderlyingType() const
Definition Decl.h:3752
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition Decl.cpp:5842
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:713
ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T)
Definition Decl.h:719
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5660
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5648
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5654
Represents a variable declaration or definition.
Definition Decl.h:933
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:1332
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1594
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:1010
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:1131
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind hasDefinition() const
Definition Decl.h:1338
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:1603
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:1307
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:1248
VarDeclBitfields VarDeclBits
Definition Decl.h:1130
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:1129
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:1366
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:1576
const Expr * getInit() const
Definition Decl.h:1392
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:1132
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1239
InitType Init
The initializer for this variable or, for a ParmVarDecl, the C++ default argument.
Definition Decl.h:979
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:1139
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2411
TLSKind
Kinds of thread-local storage.
Definition Decl.h:951
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:956
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:959
@ TLS_None
Not a TLS variable.
Definition Decl.h:953
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:1322
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1325
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:1251
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1175
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:1501
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:1354
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:1382
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:4044
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:6192
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6008
@ Struct
The "struct" keyword.
Definition TypeBase.h:6010
@ Enum
The "enum" keyword.
Definition TypeBase.h:6022
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:2044
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2041
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2038
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2035
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:4439
bool isLegalForVariable(StorageClass SC)
Checks whether the given storage class is legal for variables.
Definition Specifiers.h:267
MultiVersionKind
Definition Decl.h:2009
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:5997
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:6171
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:1755
@ Other
Other implicit parameter.
Definition Decl.h:1775
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:6185
#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:100
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:886
unsigned CheckedForICEInit
Definition Decl.h:915
unsigned WasEvaluated
Whether this statement was already evaluated.
Definition Decl.h:889
unsigned HasConstantInitialization
Whether this variable is known to have constant initialization.
Definition Decl.h:900
LazyDeclStmtPtr Value
Definition Decl.h:922
unsigned HasICEInit
In C++98, whether the initializer is an ICE.
Definition Decl.h:913
unsigned HasSideEffects
Definition Decl.h:918
APValue Evaluated
Definition Decl.h:923
unsigned CheckedForSideEffects
Definition Decl.h:920
unsigned IsEvaluating
Whether this statement is being evaluated.
Definition Decl.h:893
unsigned HasConstantDestruction
Whether this variable is known to have constant destruction.
Definition Decl.h:908
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:768
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:761
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