1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Decl.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CanonicalType.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/DeclarationName.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExternalASTSource.h"
29 #include "clang/AST/ODRHash.h"
30 #include "clang/AST/PrettyPrinter.h"
31 #include "clang/AST/Redeclarable.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/Basic/Builtins.h"
37 #include "clang/Basic/IdentifierTable.h"
38 #include "clang/Basic/LLVM.h"
39 #include "clang/Basic/LangOptions.h"
40 #include "clang/Basic/Linkage.h"
41 #include "clang/Basic/Module.h"
42 #include "clang/Basic/PartialDiagnostic.h"
43 #include "clang/Basic/SanitizerBlacklist.h"
44 #include "clang/Basic/Sanitizers.h"
45 #include "clang/Basic/SourceLocation.h"
46 #include "clang/Basic/SourceManager.h"
47 #include "clang/Basic/Specifiers.h"
48 #include "clang/Basic/TargetCXXABI.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "clang/Basic/Visibility.h"
51 #include "clang/Frontend/FrontendDiagnostic.h"
52 #include "llvm/ADT/APSInt.h"
53 #include "llvm/ADT/ArrayRef.h"
54 #include "llvm/ADT/None.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/raw_ostream.h"
71 #include <type_traits>
73 using namespace clang;
75 Decl *clang::getPrimaryMergedDecl(Decl *D) {
76 return D->getASTContext().getPrimaryMergedDecl(D);
79 // Defined here so that it can be inlined into its direct callers.
80 bool Decl::isOutOfLine() const {
81 return !getLexicalDeclContext()->Equals(getDeclContext());
84 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
85 : Decl(TranslationUnit, nullptr, SourceLocation()),
86 DeclContext(TranslationUnit), Ctx(ctx) {}
88 //===----------------------------------------------------------------------===//
89 // NamedDecl Implementation
90 //===----------------------------------------------------------------------===//
92 // Visibility rules aren't rigorously externally specified, but here
93 // are the basic principles behind what we implement:
95 // 1. An explicit visibility attribute is generally a direct expression
96 // of the user's intent and should be honored. Only the innermost
97 // visibility attribute applies. If no visibility attribute applies,
98 // global visibility settings are considered.
100 // 2. There is one caveat to the above: on or in a template pattern,
101 // an explicit visibility attribute is just a default rule, and
102 // visibility can be decreased by the visibility of template
103 // arguments. But this, too, has an exception: an attribute on an
104 // explicit specialization or instantiation causes all the visibility
105 // restrictions of the template arguments to be ignored.
107 // 3. A variable that does not otherwise have explicit visibility can
108 // be restricted by the visibility of its type.
110 // 4. A visibility restriction is explicit if it comes from an
111 // attribute (or something like it), not a global visibility setting.
112 // When emitting a reference to an external symbol, visibility
113 // restrictions are ignored unless they are explicit.
115 // 5. When computing the visibility of a non-type, including a
116 // non-type member of a class, only non-type visibility restrictions
117 // are considered: the 'visibility' attribute, global value-visibility
118 // settings, and a few special cases like __private_extern.
120 // 6. When computing the visibility of a type, including a type member
121 // of a class, only type visibility restrictions are considered:
122 // the 'type_visibility' attribute and global type-visibility settings.
123 // However, a 'visibility' attribute counts as a 'type_visibility'
124 // attribute on any declaration that only has the former.
126 // The visibility of a "secondary" entity, like a template argument,
127 // is computed using the kind of that entity, not the kind of the
128 // primary entity for which we are computing visibility. For example,
129 // the visibility of a specialization of either of these templates:
130 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
131 // template <class T, bool (&compare)(T, X)> class matcher;
132 // is restricted according to the type visibility of the argument 'T',
133 // the type visibility of 'bool(&)(T,X)', and the value visibility of
134 // the argument function 'compare'. That 'has_match' is a value
135 // and 'matcher' is a type only matters when looking for attributes
136 // and settings from the immediate context.
138 /// Does this computation kind permit us to consider additional
139 /// visibility settings from attributes and the like?
140 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
141 return computation.IgnoreExplicitVisibility;
144 /// Given an LVComputationKind, return one of the same type/value sort
145 /// that records that it already has explicit visibility.
146 static LVComputationKind
147 withExplicitVisibilityAlready(LVComputationKind Kind) {
148 Kind.IgnoreExplicitVisibility = true;
152 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
153 LVComputationKind kind) {
154 assert(!kind.IgnoreExplicitVisibility &&
155 "asking for explicit visibility when we shouldn't be");
156 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
159 /// Is the given declaration a "type" or a "value" for the purposes of
160 /// visibility computation?
161 static bool usesTypeVisibility(const NamedDecl *D) {
162 return isa<TypeDecl>(D) ||
163 isa<ClassTemplateDecl>(D) ||
164 isa<ObjCInterfaceDecl>(D);
167 /// Does the given declaration have member specialization information,
168 /// and if so, is it an explicit specialization?
169 template <class T> static typename
170 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
171 isExplicitMemberSpecialization(const T *D) {
172 if (const MemberSpecializationInfo *member =
173 D->getMemberSpecializationInfo()) {
174 return member->isExplicitSpecialization();
179 /// For templates, this question is easier: a member template can't be
180 /// explicitly instantiated, so there's a single bit indicating whether
181 /// or not this is an explicit member specialization.
182 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
183 return D->isMemberSpecialization();
186 /// Given a visibility attribute, return the explicit visibility
187 /// associated with it.
189 static Visibility getVisibilityFromAttr(const T *attr) {
190 switch (attr->getVisibility()) {
192 return DefaultVisibility;
194 return HiddenVisibility;
196 return ProtectedVisibility;
198 llvm_unreachable("bad visibility kind");
201 /// Return the explicit visibility of the given declaration.
202 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
203 NamedDecl::ExplicitVisibilityKind kind) {
204 // If we're ultimately computing the visibility of a type, look for
205 // a 'type_visibility' attribute before looking for 'visibility'.
206 if (kind == NamedDecl::VisibilityForType) {
207 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
208 return getVisibilityFromAttr(A);
212 // If this declaration has an explicit visibility attribute, use it.
213 if (const auto *A = D->getAttr<VisibilityAttr>()) {
214 return getVisibilityFromAttr(A);
220 LinkageInfo LinkageComputer::getLVForType(const Type &T,
221 LVComputationKind computation) {
222 if (computation.IgnoreAllVisibility)
223 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
224 return getTypeLinkageAndVisibility(&T);
227 /// \brief Get the most restrictive linkage for the types in the given
228 /// template parameter list. For visibility purposes, template
229 /// parameters are part of the signature of a template.
230 LinkageInfo LinkageComputer::getLVForTemplateParameterList(
231 const TemplateParameterList *Params, LVComputationKind computation) {
233 for (const NamedDecl *P : *Params) {
234 // Template type parameters are the most common and never
235 // contribute to visibility, pack or not.
236 if (isa<TemplateTypeParmDecl>(P))
239 // Non-type template parameters can be restricted by the value type, e.g.
240 // template <enum X> class A { ... };
241 // We have to be careful here, though, because we can be dealing with
243 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
244 // Handle the non-pack case first.
245 if (!NTTP->isExpandedParameterPack()) {
246 if (!NTTP->getType()->isDependentType()) {
247 LV.merge(getLVForType(*NTTP->getType(), computation));
252 // Look at all the types in an expanded pack.
253 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
254 QualType type = NTTP->getExpansionType(i);
255 if (!type->isDependentType())
256 LV.merge(getTypeLinkageAndVisibility(type));
261 // Template template parameters can be restricted by their
262 // template parameters, recursively.
263 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
265 // Handle the non-pack case first.
266 if (!TTP->isExpandedParameterPack()) {
267 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
272 // Look at all expansions in an expanded pack.
273 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
275 LV.merge(getLVForTemplateParameterList(
276 TTP->getExpansionTemplateParameters(i), computation));
283 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
284 const Decl *Ret = nullptr;
285 const DeclContext *DC = D->getDeclContext();
286 while (DC->getDeclKind() != Decl::TranslationUnit) {
287 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
288 Ret = cast<Decl>(DC);
289 DC = DC->getParent();
294 /// \brief Get the most restrictive linkage for the types and
295 /// declarations in the given template argument list.
297 /// Note that we don't take an LVComputationKind because we always
298 /// want to honor the visibility of template arguments in the same way.
300 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
301 LVComputationKind computation) {
304 for (const TemplateArgument &Arg : Args) {
305 switch (Arg.getKind()) {
306 case TemplateArgument::Null:
307 case TemplateArgument::Integral:
308 case TemplateArgument::Expression:
311 case TemplateArgument::Type:
312 LV.merge(getLVForType(*Arg.getAsType(), computation));
315 case TemplateArgument::Declaration:
316 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
317 assert(!usesTypeVisibility(ND));
318 LV.merge(getLVForDecl(ND, computation));
322 case TemplateArgument::NullPtr:
323 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
326 case TemplateArgument::Template:
327 case TemplateArgument::TemplateExpansion:
328 if (TemplateDecl *Template =
329 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
330 LV.merge(getLVForDecl(Template, computation));
333 case TemplateArgument::Pack:
334 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
337 llvm_unreachable("bad template argument kind");
344 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
345 LVComputationKind computation) {
346 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
349 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
350 const FunctionTemplateSpecializationInfo *specInfo) {
351 // Include visibility from the template parameters and arguments
352 // only if this is not an explicit instantiation or specialization
353 // with direct explicit visibility. (Implicit instantiations won't
354 // have a direct attribute.)
355 if (!specInfo->isExplicitInstantiationOrSpecialization())
358 return !fn->hasAttr<VisibilityAttr>();
361 /// Merge in template-related linkage and visibility for the given
362 /// function template specialization.
364 /// We don't need a computation kind here because we can assume
367 /// \param[out] LV the computation to use for the parent
368 void LinkageComputer::mergeTemplateLV(
369 LinkageInfo &LV, const FunctionDecl *fn,
370 const FunctionTemplateSpecializationInfo *specInfo,
371 LVComputationKind computation) {
372 bool considerVisibility =
373 shouldConsiderTemplateVisibility(fn, specInfo);
375 // Merge information from the template parameters.
376 FunctionTemplateDecl *temp = specInfo->getTemplate();
378 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
379 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
381 // Merge information from the template arguments.
382 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
383 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
384 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
387 /// Does the given declaration have a direct visibility attribute
388 /// that would match the given rules?
389 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
390 LVComputationKind computation) {
391 if (computation.IgnoreAllVisibility)
394 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
395 D->hasAttr<VisibilityAttr>();
398 /// Should we consider visibility associated with the template
399 /// arguments and parameters of the given class template specialization?
400 static bool shouldConsiderTemplateVisibility(
401 const ClassTemplateSpecializationDecl *spec,
402 LVComputationKind computation) {
403 // Include visibility from the template parameters and arguments
404 // only if this is not an explicit instantiation or specialization
405 // with direct explicit visibility (and note that implicit
406 // instantiations won't have a direct attribute).
408 // Furthermore, we want to ignore template parameters and arguments
409 // for an explicit specialization when computing the visibility of a
410 // member thereof with explicit visibility.
412 // This is a bit complex; let's unpack it.
414 // An explicit class specialization is an independent, top-level
415 // declaration. As such, if it or any of its members has an
416 // explicit visibility attribute, that must directly express the
417 // user's intent, and we should honor it. The same logic applies to
418 // an explicit instantiation of a member of such a thing.
420 // Fast path: if this is not an explicit instantiation or
421 // specialization, we always want to consider template-related
422 // visibility restrictions.
423 if (!spec->isExplicitInstantiationOrSpecialization())
426 // This is the 'member thereof' check.
427 if (spec->isExplicitSpecialization() &&
428 hasExplicitVisibilityAlready(computation))
431 return !hasDirectVisibilityAttribute(spec, computation);
434 /// Merge in template-related linkage and visibility for the given
435 /// class template specialization.
436 void LinkageComputer::mergeTemplateLV(
437 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
438 LVComputationKind computation) {
439 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
441 // Merge information from the template parameters, but ignore
442 // visibility if we're only considering template arguments.
444 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
446 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
447 LV.mergeMaybeWithVisibility(tempLV,
448 considerVisibility && !hasExplicitVisibilityAlready(computation));
450 // Merge information from the template arguments. We ignore
451 // template-argument visibility if we've got an explicit
452 // instantiation with a visibility attribute.
453 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
454 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
455 if (considerVisibility)
456 LV.mergeVisibility(argsLV);
457 LV.mergeExternalVisibility(argsLV);
460 /// Should we consider visibility associated with the template
461 /// arguments and parameters of the given variable template
462 /// specialization? As usual, follow class template specialization
463 /// logic up to initialization.
464 static bool shouldConsiderTemplateVisibility(
465 const VarTemplateSpecializationDecl *spec,
466 LVComputationKind computation) {
467 // Include visibility from the template parameters and arguments
468 // only if this is not an explicit instantiation or specialization
469 // with direct explicit visibility (and note that implicit
470 // instantiations won't have a direct attribute).
471 if (!spec->isExplicitInstantiationOrSpecialization())
474 // An explicit variable specialization is an independent, top-level
475 // declaration. As such, if it has an explicit visibility attribute,
476 // that must directly express the user's intent, and we should honor
478 if (spec->isExplicitSpecialization() &&
479 hasExplicitVisibilityAlready(computation))
482 return !hasDirectVisibilityAttribute(spec, computation);
485 /// Merge in template-related linkage and visibility for the given
486 /// variable template specialization. As usual, follow class template
487 /// specialization logic up to initialization.
488 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
489 const VarTemplateSpecializationDecl *spec,
490 LVComputationKind computation) {
491 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
493 // Merge information from the template parameters, but ignore
494 // visibility if we're only considering template arguments.
496 VarTemplateDecl *temp = spec->getSpecializedTemplate();
498 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
499 LV.mergeMaybeWithVisibility(tempLV,
500 considerVisibility && !hasExplicitVisibilityAlready(computation));
502 // Merge information from the template arguments. We ignore
503 // template-argument visibility if we've got an explicit
504 // instantiation with a visibility attribute.
505 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
506 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
507 if (considerVisibility)
508 LV.mergeVisibility(argsLV);
509 LV.mergeExternalVisibility(argsLV);
512 static bool useInlineVisibilityHidden(const NamedDecl *D) {
513 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
514 const LangOptions &Opts = D->getASTContext().getLangOpts();
515 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
518 const auto *FD = dyn_cast<FunctionDecl>(D);
522 TemplateSpecializationKind TSK = TSK_Undeclared;
523 if (FunctionTemplateSpecializationInfo *spec
524 = FD->getTemplateSpecializationInfo()) {
525 TSK = spec->getTemplateSpecializationKind();
526 } else if (MemberSpecializationInfo *MSI =
527 FD->getMemberSpecializationInfo()) {
528 TSK = MSI->getTemplateSpecializationKind();
531 const FunctionDecl *Def = nullptr;
532 // InlineVisibilityHidden only applies to definitions, and
533 // isInlined() only gives meaningful answers on definitions
535 return TSK != TSK_ExplicitInstantiationDeclaration &&
536 TSK != TSK_ExplicitInstantiationDefinition &&
537 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
540 template <typename T> static bool isFirstInExternCContext(T *D) {
541 const T *First = D->getFirstDecl();
542 return First->isInExternCContext();
545 static bool isSingleLineLanguageLinkage(const Decl &D) {
546 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
547 if (!SD->hasBraces())
552 static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
553 // FIXME: Handle isModulePrivate.
554 switch (D->getModuleOwnershipKind()) {
555 case Decl::ModuleOwnershipKind::Unowned:
556 case Decl::ModuleOwnershipKind::ModulePrivate:
558 case Decl::ModuleOwnershipKind::Visible:
559 case Decl::ModuleOwnershipKind::VisibleWhenImported:
560 if (auto *M = D->getOwningModule())
561 return M->Kind == Module::ModuleInterfaceUnit;
563 llvm_unreachable("unexpected module ownership kind");
566 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
567 // Internal linkage declarations within a module interface unit are modeled
568 // as "module-internal linkage", which means that they have internal linkage
569 // formally but can be indirectly accessed from outside the module via inline
570 // functions and templates defined within the module.
571 if (auto *M = D->getOwningModule())
572 if (M->Kind == Module::ModuleInterfaceUnit)
573 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
575 return LinkageInfo::internal();
578 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
579 // C++ Modules TS [basic.link]/6.8:
580 // - A name declared at namespace scope that does not have internal linkage
581 // by the previous rules and that is introduced by a non-exported
582 // declaration has module linkage.
583 if (auto *M = D->getOwningModule())
584 if (M->Kind == Module::ModuleInterfaceUnit)
585 if (!isExportedFromModuleIntefaceUnit(
586 cast<NamedDecl>(D->getCanonicalDecl())))
587 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
589 return LinkageInfo::external();
593 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
594 LVComputationKind computation,
595 bool IgnoreVarTypeLinkage) {
596 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
597 "Not a name having namespace scope");
598 ASTContext &Context = D->getASTContext();
600 // C++ [basic.link]p3:
601 // A name having namespace scope (3.3.6) has internal linkage if it
603 // - an object, reference, function or function template that is
604 // explicitly declared static; or,
605 // (This bullet corresponds to C99 6.2.2p3.)
606 if (const auto *Var = dyn_cast<VarDecl>(D)) {
607 // Explicitly declared static.
608 if (Var->getStorageClass() == SC_Static)
609 return getInternalLinkageFor(Var);
611 // - a non-inline, non-volatile object or reference that is explicitly
612 // declared const or constexpr and neither explicitly declared extern
613 // nor previously declared to have external linkage; or (there is no
614 // equivalent in C99)
615 // The C++ modules TS adds "non-exported" to this list.
616 if (Context.getLangOpts().CPlusPlus &&
617 Var->getType().isConstQualified() &&
618 !Var->getType().isVolatileQualified() &&
620 !isExportedFromModuleIntefaceUnit(Var)) {
621 const VarDecl *PrevVar = Var->getPreviousDecl();
623 return getLVForDecl(PrevVar, computation);
625 if (Var->getStorageClass() != SC_Extern &&
626 Var->getStorageClass() != SC_PrivateExtern &&
627 !isSingleLineLanguageLinkage(*Var))
628 return getInternalLinkageFor(Var);
631 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
632 PrevVar = PrevVar->getPreviousDecl()) {
633 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
634 Var->getStorageClass() == SC_None)
635 return getDeclLinkageAndVisibility(PrevVar);
636 // Explicitly declared static.
637 if (PrevVar->getStorageClass() == SC_Static)
638 return getInternalLinkageFor(Var);
640 } else if (const FunctionDecl *Function = D->getAsFunction()) {
642 // A non-member function template can have internal linkage; any
643 // other template name shall have external linkage.
645 // Explicitly declared static.
646 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
647 return getInternalLinkageFor(Function);
648 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
649 // - a data member of an anonymous union.
650 const VarDecl *VD = IFD->getVarDecl();
651 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
652 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
654 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
656 if (D->isInAnonymousNamespace()) {
657 const auto *Var = dyn_cast<VarDecl>(D);
658 const auto *Func = dyn_cast<FunctionDecl>(D);
659 // FIXME: The check for extern "C" here is not justified by the standard
660 // wording, but we retain it from the pre-DR1113 model to avoid breaking
663 // C++11 [basic.link]p4:
664 // An unnamed namespace or a namespace declared directly or indirectly
665 // within an unnamed namespace has internal linkage.
666 if ((!Var || !isFirstInExternCContext(Var)) &&
667 (!Func || !isFirstInExternCContext(Func)))
668 return getInternalLinkageFor(D);
671 // Set up the defaults.
674 // If the declaration of an identifier for an object has file
675 // scope and no storage-class specifier, its linkage is
677 LinkageInfo LV = getExternalLinkageFor(D);
679 if (!hasExplicitVisibilityAlready(computation)) {
680 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
681 LV.mergeVisibility(*Vis, true);
683 // If we're declared in a namespace with a visibility attribute,
684 // use that namespace's visibility, and it still counts as explicit.
685 for (const DeclContext *DC = D->getDeclContext();
686 !isa<TranslationUnitDecl>(DC);
687 DC = DC->getParent()) {
688 const auto *ND = dyn_cast<NamespaceDecl>(DC);
690 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
691 LV.mergeVisibility(*Vis, true);
697 // Add in global settings if the above didn't give us direct visibility.
698 if (!LV.isVisibilityExplicit()) {
699 // Use global type/value visibility as appropriate.
700 Visibility globalVisibility =
701 computation.isValueVisibility()
702 ? Context.getLangOpts().getValueVisibilityMode()
703 : Context.getLangOpts().getTypeVisibilityMode();
704 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
706 // If we're paying attention to global visibility, apply
707 // -finline-visibility-hidden if this is an inline method.
708 if (useInlineVisibilityHidden(D))
709 LV.mergeVisibility(HiddenVisibility, true);
713 // C++ [basic.link]p4:
715 // A name having namespace scope has external linkage if it is the
718 // - an object or reference, unless it has internal linkage; or
719 if (const auto *Var = dyn_cast<VarDecl>(D)) {
720 // GCC applies the following optimization to variables and static
721 // data members, but not to functions:
723 // Modify the variable's LV by the LV of its type unless this is
724 // C or extern "C". This follows from [basic.link]p9:
725 // A type without linkage shall not be used as the type of a
726 // variable or function with external linkage unless
727 // - the entity has C language linkage, or
728 // - the entity is declared within an unnamed namespace, or
729 // - the entity is not used or is defined in the same
731 // and [basic.link]p10:
732 // ...the types specified by all declarations referring to a
733 // given variable or function shall be identical...
734 // C does not have an equivalent rule.
736 // Ignore this if we've got an explicit attribute; the user
737 // probably knows what they're doing.
739 // Note that we don't want to make the variable non-external
740 // because of this, but unique-external linkage suits us.
741 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
742 !IgnoreVarTypeLinkage) {
743 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
744 if (!isExternallyVisible(TypeLV.getLinkage()))
745 return LinkageInfo::uniqueExternal();
746 if (!LV.isVisibilityExplicit())
747 LV.mergeVisibility(TypeLV);
750 if (Var->getStorageClass() == SC_PrivateExtern)
751 LV.mergeVisibility(HiddenVisibility, true);
753 // Note that Sema::MergeVarDecl already takes care of implementing
754 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
757 // As per function and class template specializations (below),
758 // consider LV for the template and template arguments. We're at file
759 // scope, so we do not need to worry about nested specializations.
760 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
761 mergeTemplateLV(LV, spec, computation);
764 // - a function, unless it has internal linkage; or
765 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
766 // In theory, we can modify the function's LV by the LV of its
767 // type unless it has C linkage (see comment above about variables
768 // for justification). In practice, GCC doesn't do this, so it's
769 // just too painful to make work.
771 if (Function->getStorageClass() == SC_PrivateExtern)
772 LV.mergeVisibility(HiddenVisibility, true);
774 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
775 // merging storage classes and visibility attributes, so we don't have to
776 // look at previous decls in here.
778 // In C++, then if the type of the function uses a type with
779 // unique-external linkage, it's not legally usable from outside
780 // this translation unit. However, we should use the C linkage
781 // rules instead for extern "C" declarations.
782 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
783 // Only look at the type-as-written. Otherwise, deducing the return type
784 // of a function could change its linkage.
785 QualType TypeAsWritten = Function->getType();
786 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
787 TypeAsWritten = TSI->getType();
788 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
789 return LinkageInfo::uniqueExternal();
792 // Consider LV from the template and the template arguments.
793 // We're at file scope, so we do not need to worry about nested
795 if (FunctionTemplateSpecializationInfo *specInfo
796 = Function->getTemplateSpecializationInfo()) {
797 mergeTemplateLV(LV, Function, specInfo, computation);
800 // - a named class (Clause 9), or an unnamed class defined in a
801 // typedef declaration in which the class has the typedef name
802 // for linkage purposes (7.1.3); or
803 // - a named enumeration (7.2), or an unnamed enumeration
804 // defined in a typedef declaration in which the enumeration
805 // has the typedef name for linkage purposes (7.1.3); or
806 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
807 // Unnamed tags have no linkage.
808 if (!Tag->hasNameForLinkage())
809 return LinkageInfo::none();
811 // If this is a class template specialization, consider the
812 // linkage of the template and template arguments. We're at file
813 // scope, so we do not need to worry about nested specializations.
814 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
815 mergeTemplateLV(LV, spec, computation);
818 // - an enumerator belonging to an enumeration with external linkage;
819 } else if (isa<EnumConstantDecl>(D)) {
820 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
822 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
823 return LinkageInfo::none();
826 // - a template, unless it is a function template that has
827 // internal linkage (Clause 14);
828 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
829 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
831 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
832 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
834 // - a namespace (7.3), unless it is declared within an unnamed
837 // We handled names in anonymous namespaces above.
838 } else if (isa<NamespaceDecl>(D)) {
841 // By extension, we assign external linkage to Objective-C
843 } else if (isa<ObjCInterfaceDecl>(D)) {
846 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
847 // A typedef declaration has linkage if it gives a type a name for
849 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
850 return LinkageInfo::none();
852 // Everything not covered here has no linkage.
854 return LinkageInfo::none();
857 // If we ended up with non-externally-visible linkage, visibility should
858 // always be default.
859 if (!isExternallyVisible(LV.getLinkage()))
860 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
866 LinkageComputer::getLVForClassMember(const NamedDecl *D,
867 LVComputationKind computation,
868 bool IgnoreVarTypeLinkage) {
869 // Only certain class members have linkage. Note that fields don't
870 // really have linkage, but it's convenient to say they do for the
871 // purposes of calculating linkage of pointer-to-data-member
872 // template arguments.
874 // Templates also don't officially have linkage, but since we ignore
875 // the C++ standard and look at template arguments when determining
876 // linkage and visibility of a template specialization, we might hit
877 // a template template argument that way. If we do, we need to
878 // consider its linkage.
879 if (!(isa<CXXMethodDecl>(D) ||
882 isa<IndirectFieldDecl>(D) ||
884 isa<TemplateDecl>(D)))
885 return LinkageInfo::none();
889 // If we have an explicit visibility attribute, merge that in.
890 if (!hasExplicitVisibilityAlready(computation)) {
891 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
892 LV.mergeVisibility(*Vis, true);
893 // If we're paying attention to global visibility, apply
894 // -finline-visibility-hidden if this is an inline method.
896 // Note that we do this before merging information about
897 // the class visibility.
898 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
899 LV.mergeVisibility(HiddenVisibility, true);
902 // If this class member has an explicit visibility attribute, the only
903 // thing that can change its visibility is the template arguments, so
904 // only look for them when processing the class.
905 LVComputationKind classComputation = computation;
906 if (LV.isVisibilityExplicit())
907 classComputation = withExplicitVisibilityAlready(computation);
909 LinkageInfo classLV =
910 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
911 // The member has the same linkage as the class. If that's not externally
912 // visible, we don't need to compute anything about the linkage.
913 // FIXME: If we're only computing linkage, can we bail out here?
914 if (!isExternallyVisible(classLV.getLinkage()))
918 // Otherwise, don't merge in classLV yet, because in certain cases
919 // we need to completely ignore the visibility from it.
921 // Specifically, if this decl exists and has an explicit attribute.
922 const NamedDecl *explicitSpecSuppressor = nullptr;
924 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
925 // Only look at the type-as-written. Otherwise, deducing the return type
926 // of a function could change its linkage.
927 QualType TypeAsWritten = MD->getType();
928 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
929 TypeAsWritten = TSI->getType();
930 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
931 return LinkageInfo::uniqueExternal();
933 // If this is a method template specialization, use the linkage for
934 // the template parameters and arguments.
935 if (FunctionTemplateSpecializationInfo *spec
936 = MD->getTemplateSpecializationInfo()) {
937 mergeTemplateLV(LV, MD, spec, computation);
938 if (spec->isExplicitSpecialization()) {
939 explicitSpecSuppressor = MD;
940 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
941 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
943 } else if (isExplicitMemberSpecialization(MD)) {
944 explicitSpecSuppressor = MD;
947 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
948 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
949 mergeTemplateLV(LV, spec, computation);
950 if (spec->isExplicitSpecialization()) {
951 explicitSpecSuppressor = spec;
953 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
954 if (isExplicitMemberSpecialization(temp)) {
955 explicitSpecSuppressor = temp->getTemplatedDecl();
958 } else if (isExplicitMemberSpecialization(RD)) {
959 explicitSpecSuppressor = RD;
962 // Static data members.
963 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
964 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
965 mergeTemplateLV(LV, spec, computation);
967 // Modify the variable's linkage by its type, but ignore the
968 // type's visibility unless it's a definition.
969 if (!IgnoreVarTypeLinkage) {
970 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
971 // FIXME: If the type's linkage is not externally visible, we can
972 // give this static data member UniqueExternalLinkage.
973 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
974 LV.mergeVisibility(typeLV);
975 LV.mergeExternalVisibility(typeLV);
978 if (isExplicitMemberSpecialization(VD)) {
979 explicitSpecSuppressor = VD;
983 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
984 bool considerVisibility =
985 (!LV.isVisibilityExplicit() &&
986 !classLV.isVisibilityExplicit() &&
987 !hasExplicitVisibilityAlready(computation));
989 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
990 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
992 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
993 if (isExplicitMemberSpecialization(redeclTemp)) {
994 explicitSpecSuppressor = temp->getTemplatedDecl();
999 // We should never be looking for an attribute directly on a template.
1000 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1002 // If this member is an explicit member specialization, and it has
1003 // an explicit attribute, ignore visibility from the parent.
1004 bool considerClassVisibility = true;
1005 if (explicitSpecSuppressor &&
1006 // optimization: hasDVA() is true only with explicit visibility.
1007 LV.isVisibilityExplicit() &&
1008 classLV.getVisibility() != DefaultVisibility &&
1009 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1010 considerClassVisibility = false;
1013 // Finally, merge in information from the class.
1014 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1018 void NamedDecl::anchor() {}
1020 bool NamedDecl::isLinkageValid() const {
1021 if (!hasCachedLinkage())
1024 Linkage L = LinkageComputer{}
1025 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1027 return L == getCachedLinkage();
1030 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1031 StringRef name = getName();
1032 if (name.empty()) return SFF_None;
1034 if (name.front() == 'C')
1035 if (name == "CFStringCreateWithFormat" ||
1036 name == "CFStringCreateWithFormatAndArguments" ||
1037 name == "CFStringAppendFormat" ||
1038 name == "CFStringAppendFormatAndArguments")
1039 return SFF_CFString;
1043 Linkage NamedDecl::getLinkageInternal() const {
1044 // We don't care about visibility here, so ask for the cheapest
1045 // possible visibility analysis.
1046 return LinkageComputer{}
1047 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1051 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1052 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1055 static Optional<Visibility>
1056 getExplicitVisibilityAux(const NamedDecl *ND,
1057 NamedDecl::ExplicitVisibilityKind kind,
1058 bool IsMostRecent) {
1059 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1061 // Check the declaration itself first.
1062 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1065 // If this is a member class of a specialization of a class template
1066 // and the corresponding decl has explicit visibility, use that.
1067 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1068 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1069 if (InstantiatedFrom)
1070 return getVisibilityOf(InstantiatedFrom, kind);
1073 // If there wasn't explicit visibility there, and this is a
1074 // specialization of a class template, check for visibility
1076 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1077 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1080 // Use the most recent declaration.
1081 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1082 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1083 if (MostRecent != ND)
1084 return getExplicitVisibilityAux(MostRecent, kind, true);
1087 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1088 if (Var->isStaticDataMember()) {
1089 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1090 if (InstantiatedFrom)
1091 return getVisibilityOf(InstantiatedFrom, kind);
1094 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1095 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1100 // Also handle function template specializations.
1101 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1102 // If the function is a specialization of a template with an
1103 // explicit visibility attribute, use that.
1104 if (FunctionTemplateSpecializationInfo *templateInfo
1105 = fn->getTemplateSpecializationInfo())
1106 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1109 // If the function is a member of a specialization of a class template
1110 // and the corresponding decl has explicit visibility, use that.
1111 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1112 if (InstantiatedFrom)
1113 return getVisibilityOf(InstantiatedFrom, kind);
1118 // The visibility of a template is stored in the templated decl.
1119 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1120 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1125 Optional<Visibility>
1126 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1127 return getExplicitVisibilityAux(this, kind, false);
1130 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1132 LVComputationKind computation) {
1133 // This lambda has its linkage/visibility determined by its owner.
1134 const NamedDecl *Owner;
1136 Owner = dyn_cast<NamedDecl>(DC);
1137 else if (isa<ParmVarDecl>(ContextDecl))
1139 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1141 Owner = cast<NamedDecl>(ContextDecl);
1144 return LinkageInfo::none();
1146 // If the owner has a deduced type, we need to skip querying the linkage and
1147 // visibility of that type, because it might involve this closure type. The
1148 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1149 // than NoLinkage when we don't strictly need to, which is benign.
1150 auto *VD = dyn_cast<VarDecl>(Owner);
1151 LinkageInfo OwnerLV =
1152 VD && VD->getType()->getContainedDeducedType()
1153 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1154 : getLVForDecl(Owner, computation);
1156 // A lambda never formally has linkage. But if the owner is externally
1157 // visible, then the lambda is too. We apply the same rules to blocks.
1158 if (!isExternallyVisible(OwnerLV.getLinkage()))
1159 return LinkageInfo::none();
1160 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1161 OwnerLV.isVisibilityExplicit());
1164 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1165 LVComputationKind computation) {
1166 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1167 if (Function->isInAnonymousNamespace() &&
1168 !isFirstInExternCContext(Function))
1169 return getInternalLinkageFor(Function);
1171 // This is a "void f();" which got merged with a file static.
1172 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1173 return getInternalLinkageFor(Function);
1176 if (!hasExplicitVisibilityAlready(computation)) {
1177 if (Optional<Visibility> Vis =
1178 getExplicitVisibility(Function, computation))
1179 LV.mergeVisibility(*Vis, true);
1182 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1183 // merging storage classes and visibility attributes, so we don't have to
1184 // look at previous decls in here.
1189 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1190 if (Var->hasExternalStorage()) {
1191 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1192 return getInternalLinkageFor(Var);
1195 if (Var->getStorageClass() == SC_PrivateExtern)
1196 LV.mergeVisibility(HiddenVisibility, true);
1197 else if (!hasExplicitVisibilityAlready(computation)) {
1198 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1199 LV.mergeVisibility(*Vis, true);
1202 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1203 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1204 if (PrevLV.getLinkage())
1205 LV.setLinkage(PrevLV.getLinkage());
1206 LV.mergeVisibility(PrevLV);
1212 if (!Var->isStaticLocal())
1213 return LinkageInfo::none();
1216 ASTContext &Context = D->getASTContext();
1217 if (!Context.getLangOpts().CPlusPlus)
1218 return LinkageInfo::none();
1220 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1221 if (!OuterD || OuterD->isInvalidDecl())
1222 return LinkageInfo::none();
1225 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1226 if (!BD->getBlockManglingNumber())
1227 return LinkageInfo::none();
1229 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1230 BD->getBlockManglingContextDecl(), computation);
1232 const auto *FD = cast<FunctionDecl>(OuterD);
1233 if (!FD->isInlined() &&
1234 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1235 return LinkageInfo::none();
1237 LV = getLVForDecl(FD, computation);
1239 if (!isExternallyVisible(LV.getLinkage()))
1240 return LinkageInfo::none();
1241 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1242 LV.isVisibilityExplicit());
1245 static inline const CXXRecordDecl*
1246 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1247 const CXXRecordDecl *Ret = Record;
1248 while (Record && Record->isLambda()) {
1250 if (!Record->getParent()) break;
1251 // Get the Containing Class of this Lambda Class
1252 Record = dyn_cast_or_null<CXXRecordDecl>(
1253 Record->getParent()->getParent());
1258 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1259 LVComputationKind computation,
1260 bool IgnoreVarTypeLinkage) {
1261 // Internal_linkage attribute overrides other considerations.
1262 if (D->hasAttr<InternalLinkageAttr>())
1263 return getInternalLinkageFor(D);
1265 // Objective-C: treat all Objective-C declarations as having external
1267 switch (D->getKind()) {
1271 // Per C++ [basic.link]p2, only the names of objects, references,
1272 // functions, types, templates, namespaces, and values ever have linkage.
1274 // Note that the name of a typedef, namespace alias, using declaration,
1275 // and so on are not the name of the corresponding type, namespace, or
1276 // declaration, so they do *not* have linkage.
1277 case Decl::ImplicitParam:
1279 case Decl::NamespaceAlias:
1282 case Decl::UsingShadow:
1283 case Decl::UsingDirective:
1284 return LinkageInfo::none();
1286 case Decl::EnumConstant:
1287 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1288 if (D->getASTContext().getLangOpts().CPlusPlus)
1289 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1290 return LinkageInfo::visible_none();
1293 case Decl::TypeAlias:
1294 // A typedef declaration has linkage if it gives a type a name for
1295 // linkage purposes.
1296 if (!cast<TypedefNameDecl>(D)
1297 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1298 return LinkageInfo::none();
1301 case Decl::TemplateTemplateParm: // count these as external
1302 case Decl::NonTypeTemplateParm:
1303 case Decl::ObjCAtDefsField:
1304 case Decl::ObjCCategory:
1305 case Decl::ObjCCategoryImpl:
1306 case Decl::ObjCCompatibleAlias:
1307 case Decl::ObjCImplementation:
1308 case Decl::ObjCMethod:
1309 case Decl::ObjCProperty:
1310 case Decl::ObjCPropertyImpl:
1311 case Decl::ObjCProtocol:
1312 return getExternalLinkageFor(D);
1314 case Decl::CXXRecord: {
1315 const auto *Record = cast<CXXRecordDecl>(D);
1316 if (Record->isLambda()) {
1317 if (!Record->getLambdaManglingNumber()) {
1318 // This lambda has no mangling number, so it's internal.
1319 return getInternalLinkageFor(D);
1322 // This lambda has its linkage/visibility determined:
1323 // - either by the outermost lambda if that lambda has no mangling
1325 // - or by the parent of the outer most lambda
1326 // This prevents infinite recursion in settings such as nested lambdas
1327 // used in NSDMI's, for e.g.
1330 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1332 const CXXRecordDecl *OuterMostLambda =
1333 getOutermostEnclosingLambda(Record);
1334 if (!OuterMostLambda->getLambdaManglingNumber())
1335 return getInternalLinkageFor(D);
1337 return getLVForClosure(
1338 OuterMostLambda->getDeclContext()->getRedeclContext(),
1339 OuterMostLambda->getLambdaContextDecl(), computation);
1346 // Handle linkage for namespace-scope names.
1347 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1348 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1350 // C++ [basic.link]p5:
1351 // In addition, a member function, static data member, a named
1352 // class or enumeration of class scope, or an unnamed class or
1353 // enumeration defined in a class-scope typedef declaration such
1354 // that the class or enumeration has the typedef name for linkage
1355 // purposes (7.1.3), has external linkage if the name of the class
1356 // has external linkage.
1357 if (D->getDeclContext()->isRecord())
1358 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1360 // C++ [basic.link]p6:
1361 // The name of a function declared in block scope and the name of
1362 // an object declared by a block scope extern declaration have
1363 // linkage. If there is a visible declaration of an entity with
1364 // linkage having the same name and type, ignoring entities
1365 // declared outside the innermost enclosing namespace scope, the
1366 // block scope declaration declares that same entity and receives
1367 // the linkage of the previous declaration. If there is more than
1368 // one such matching entity, the program is ill-formed. Otherwise,
1369 // if no matching entity is found, the block scope entity receives
1370 // external linkage.
1371 if (D->getDeclContext()->isFunctionOrMethod())
1372 return getLVForLocalDecl(D, computation);
1374 // C++ [basic.link]p6:
1375 // Names not covered by these rules have no linkage.
1376 return LinkageInfo::none();
1379 /// getLVForDecl - Get the linkage and visibility for the given declaration.
1380 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1381 LVComputationKind computation) {
1382 // Internal_linkage attribute overrides other considerations.
1383 if (D->hasAttr<InternalLinkageAttr>())
1384 return getInternalLinkageFor(D);
1386 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1387 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1389 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1392 LinkageInfo LV = computeLVForDecl(D, computation);
1393 if (D->hasCachedLinkage())
1394 assert(D->getCachedLinkage() == LV.getLinkage());
1396 D->setCachedLinkage(LV.getLinkage());
1397 cache(D, computation, LV);
1400 // In C (because of gnu inline) and in c++ with microsoft extensions an
1401 // static can follow an extern, so we can have two decls with different
1403 const LangOptions &Opts = D->getASTContext().getLangOpts();
1404 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1407 // We have just computed the linkage for this decl. By induction we know
1408 // that all other computed linkages match, check that the one we just
1409 // computed also does.
1410 NamedDecl *Old = nullptr;
1411 for (auto I : D->redecls()) {
1412 auto *T = cast<NamedDecl>(I);
1415 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1420 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1426 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1427 return getLVForDecl(D,
1428 LVComputationKind(usesTypeVisibility(D)
1429 ? NamedDecl::VisibilityForType
1430 : NamedDecl::VisibilityForValue));
1433 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1434 Module *M = getOwningModule();
1439 case Module::ModuleMapModule:
1440 // Module map modules have no special linkage semantics.
1443 case Module::ModuleInterfaceUnit:
1446 case Module::GlobalModuleFragment: {
1447 // External linkage declarations in the global module have no owning module
1448 // for linkage purposes. But internal linkage declarations in the global
1449 // module fragment of a particular module are owned by that module for
1450 // linkage purposes.
1453 bool InternalLinkage;
1454 if (auto *ND = dyn_cast<NamedDecl>(this))
1455 InternalLinkage = !ND->hasExternalFormalLinkage();
1457 auto *NSD = dyn_cast<NamespaceDecl>(this);
1458 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1459 isInAnonymousNamespace();
1461 return InternalLinkage ? M->Parent : nullptr;
1465 llvm_unreachable("unknown module kind");
1468 void NamedDecl::printName(raw_ostream &os) const {
1472 std::string NamedDecl::getQualifiedNameAsString() const {
1473 std::string QualName;
1474 llvm::raw_string_ostream OS(QualName);
1475 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1479 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1480 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1483 void NamedDecl::printQualifiedName(raw_ostream &OS,
1484 const PrintingPolicy &P) const {
1485 const DeclContext *Ctx = getDeclContext();
1487 // For ObjC methods, look through categories and use the interface as context.
1488 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1489 if (auto *ID = MD->getClassInterface())
1492 if (Ctx->isFunctionOrMethod()) {
1497 using ContextsTy = SmallVector<const DeclContext *, 8>;
1498 ContextsTy Contexts;
1500 // Collect contexts.
1501 while (Ctx && isa<NamedDecl>(Ctx)) {
1502 Contexts.push_back(Ctx);
1503 Ctx = Ctx->getParent();
1506 for (const DeclContext *DC : llvm::reverse(Contexts)) {
1507 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1508 OS << Spec->getName();
1509 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1510 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
1511 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1512 if (P.SuppressUnwrittenScope &&
1513 (ND->isAnonymousNamespace() || ND->isInline()))
1515 if (ND->isAnonymousNamespace()) {
1516 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1517 : "(anonymous namespace)");
1521 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1522 if (!RD->getIdentifier())
1523 OS << "(anonymous " << RD->getKindName() << ')';
1526 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1527 const FunctionProtoType *FT = nullptr;
1528 if (FD->hasWrittenPrototype())
1529 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1533 unsigned NumParams = FD->getNumParams();
1534 for (unsigned i = 0; i < NumParams; ++i) {
1537 OS << FD->getParamDecl(i)->getType().stream(P);
1540 if (FT->isVariadic()) {
1547 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1548 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1549 // enumerator is declared in the scope that immediately contains
1550 // the enum-specifier. Each scoped enumerator is declared in the
1551 // scope of the enumeration.
1552 // For the case of unscoped enumerator, do not include in the qualified
1553 // name any information about its enum enclosing scope, as its visibility
1560 OS << *cast<NamedDecl>(DC);
1565 if (getDeclName() || isa<DecompositionDecl>(this))
1568 OS << "(anonymous)";
1571 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1572 const PrintingPolicy &Policy,
1573 bool Qualified) const {
1575 printQualifiedName(OS, Policy);
1580 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1583 static bool isRedeclarableImpl(...) { return false; }
1584 static bool isRedeclarable(Decl::Kind K) {
1586 #define DECL(Type, Base) \
1588 return isRedeclarableImpl((Type##Decl *)nullptr);
1589 #define ABSTRACT_DECL(DECL)
1590 #include "clang/AST/DeclNodes.inc"
1592 llvm_unreachable("unknown decl kind");
1595 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1596 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1598 // Never replace one imported declaration with another; we need both results
1599 // when re-exporting.
1600 if (OldD->isFromASTFile() && isFromASTFile())
1603 // A kind mismatch implies that the declaration is not replaced.
1604 if (OldD->getKind() != getKind())
1607 // For method declarations, we never replace. (Why?)
1608 if (isa<ObjCMethodDecl>(this))
1611 // For parameters, pick the newer one. This is either an error or (in
1612 // Objective-C) permitted as an extension.
1613 if (isa<ParmVarDecl>(this))
1616 // Inline namespaces can give us two declarations with the same
1617 // name and kind in the same scope but different contexts; we should
1618 // keep both declarations in this case.
1619 if (!this->getDeclContext()->getRedeclContext()->Equals(
1620 OldD->getDeclContext()->getRedeclContext()))
1623 // Using declarations can be replaced if they import the same name from the
1625 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1626 ASTContext &Context = getASTContext();
1627 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1628 Context.getCanonicalNestedNameSpecifier(
1629 cast<UsingDecl>(OldD)->getQualifier());
1631 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1632 ASTContext &Context = getASTContext();
1633 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1634 Context.getCanonicalNestedNameSpecifier(
1635 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1638 if (isRedeclarable(getKind())) {
1639 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1645 // Check whether this is actually newer than OldD. We want to keep the
1646 // newer declaration. This loop will usually only iterate once, because
1647 // OldD is usually the previous declaration.
1648 for (auto D : redecls()) {
1652 // If we reach the canonical declaration, then OldD is not actually older
1655 // FIXME: In this case, we should not add this decl to the lookup table.
1656 if (D->isCanonicalDecl())
1660 // It's a newer declaration of the same kind of declaration in the same
1661 // scope: we want this decl instead of the existing one.
1665 // In all other cases, we need to keep both declarations in case they have
1666 // different visibility. Any attempt to use the name will result in an
1667 // ambiguity if more than one is visible.
1671 bool NamedDecl::hasLinkage() const {
1672 return getFormalLinkage() != NoLinkage;
1675 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1676 NamedDecl *ND = this;
1677 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1678 ND = UD->getTargetDecl();
1680 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1681 return AD->getClassInterface();
1683 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1684 return AD->getNamespace();
1689 bool NamedDecl::isCXXInstanceMember() const {
1690 if (!isCXXClassMember())
1693 const NamedDecl *D = this;
1694 if (isa<UsingShadowDecl>(D))
1695 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1697 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1699 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1700 return MD->isInstance();
1704 //===----------------------------------------------------------------------===//
1705 // DeclaratorDecl Implementation
1706 //===----------------------------------------------------------------------===//
1708 template <typename DeclT>
1709 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1710 if (decl->getNumTemplateParameterLists() > 0)
1711 return decl->getTemplateParameterList(0)->getTemplateLoc();
1713 return decl->getInnerLocStart();
1716 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1717 TypeSourceInfo *TSI = getTypeSourceInfo();
1718 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1719 return SourceLocation();
1722 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1724 // Make sure the extended decl info is allocated.
1725 if (!hasExtInfo()) {
1726 // Save (non-extended) type source info pointer.
1727 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1728 // Allocate external info struct.
1729 DeclInfo = new (getASTContext()) ExtInfo;
1730 // Restore savedTInfo into (extended) decl info.
1731 getExtInfo()->TInfo = savedTInfo;
1733 // Set qualifier info.
1734 getExtInfo()->QualifierLoc = QualifierLoc;
1736 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1738 if (getExtInfo()->NumTemplParamLists == 0) {
1739 // Save type source info pointer.
1740 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1741 // Deallocate the extended decl info.
1742 getASTContext().Deallocate(getExtInfo());
1743 // Restore savedTInfo into (non-extended) decl info.
1744 DeclInfo = savedTInfo;
1747 getExtInfo()->QualifierLoc = QualifierLoc;
1752 void DeclaratorDecl::setTemplateParameterListsInfo(
1753 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1754 assert(!TPLists.empty());
1755 // Make sure the extended decl info is allocated.
1756 if (!hasExtInfo()) {
1757 // Save (non-extended) type source info pointer.
1758 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1759 // Allocate external info struct.
1760 DeclInfo = new (getASTContext()) ExtInfo;
1761 // Restore savedTInfo into (extended) decl info.
1762 getExtInfo()->TInfo = savedTInfo;
1764 // Set the template parameter lists info.
1765 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1768 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1769 return getTemplateOrInnerLocStart(this);
1772 // Helper function: returns true if QT is or contains a type
1773 // having a postfix component.
1774 static bool typeIsPostfix(QualType QT) {
1776 const Type* T = QT.getTypePtr();
1777 switch (T->getTypeClass()) {
1781 QT = cast<PointerType>(T)->getPointeeType();
1783 case Type::BlockPointer:
1784 QT = cast<BlockPointerType>(T)->getPointeeType();
1786 case Type::MemberPointer:
1787 QT = cast<MemberPointerType>(T)->getPointeeType();
1789 case Type::LValueReference:
1790 case Type::RValueReference:
1791 QT = cast<ReferenceType>(T)->getPointeeType();
1793 case Type::PackExpansion:
1794 QT = cast<PackExpansionType>(T)->getPattern();
1797 case Type::ConstantArray:
1798 case Type::DependentSizedArray:
1799 case Type::IncompleteArray:
1800 case Type::VariableArray:
1801 case Type::FunctionProto:
1802 case Type::FunctionNoProto:
1808 SourceRange DeclaratorDecl::getSourceRange() const {
1809 SourceLocation RangeEnd = getLocation();
1810 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1811 // If the declaration has no name or the type extends past the name take the
1812 // end location of the type.
1813 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1814 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1816 return SourceRange(getOuterLocStart(), RangeEnd);
1819 void QualifierInfo::setTemplateParameterListsInfo(
1820 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1821 // Free previous template parameters (if any).
1822 if (NumTemplParamLists > 0) {
1823 Context.Deallocate(TemplParamLists);
1824 TemplParamLists = nullptr;
1825 NumTemplParamLists = 0;
1827 // Set info on matched template parameter lists (if any).
1828 if (!TPLists.empty()) {
1829 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1830 NumTemplParamLists = TPLists.size();
1831 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1835 //===----------------------------------------------------------------------===//
1836 // VarDecl Implementation
1837 //===----------------------------------------------------------------------===//
1839 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1841 case SC_None: break;
1842 case SC_Auto: return "auto";
1843 case SC_Extern: return "extern";
1844 case SC_PrivateExtern: return "__private_extern__";
1845 case SC_Register: return "register";
1846 case SC_Static: return "static";
1849 llvm_unreachable("Invalid storage class");
1852 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1853 SourceLocation StartLoc, SourceLocation IdLoc,
1854 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1856 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1857 redeclarable_base(C) {
1858 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1859 "VarDeclBitfields too large!");
1860 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1861 "ParmVarDeclBitfields too large!");
1862 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1863 "NonParmVarDeclBitfields too large!");
1865 VarDeclBits.SClass = SC;
1866 // Everything else is implicitly initialized to false.
1869 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1870 SourceLocation StartL, SourceLocation IdL,
1871 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1873 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1876 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1878 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1879 QualType(), nullptr, SC_None);
1882 void VarDecl::setStorageClass(StorageClass SC) {
1883 assert(isLegalForVariable(SC));
1884 VarDeclBits.SClass = SC;
1887 VarDecl::TLSKind VarDecl::getTLSKind() const {
1888 switch (VarDeclBits.TSCSpec) {
1889 case TSCS_unspecified:
1890 if (!hasAttr<ThreadAttr>() &&
1891 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1892 getASTContext().getTargetInfo().isTLSSupported() &&
1893 hasAttr<OMPThreadPrivateDeclAttr>()))
1895 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1896 LangOptions::MSVC2015)) ||
1897 hasAttr<OMPThreadPrivateDeclAttr>())
1900 case TSCS___thread: // Fall through.
1901 case TSCS__Thread_local:
1903 case TSCS_thread_local:
1906 llvm_unreachable("Unknown thread storage class specifier!");
1909 SourceRange VarDecl::getSourceRange() const {
1910 if (const Expr *Init = getInit()) {
1911 SourceLocation InitEnd = Init->getLocEnd();
1912 // If Init is implicit, ignore its source range and fallback on
1913 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1914 if (InitEnd.isValid() && InitEnd != getLocation())
1915 return SourceRange(getOuterLocStart(), InitEnd);
1917 return DeclaratorDecl::getSourceRange();
1920 template<typename T>
1921 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1922 // C++ [dcl.link]p1: All function types, function names with external linkage,
1923 // and variable names with external linkage have a language linkage.
1924 if (!D.hasExternalFormalLinkage())
1925 return NoLanguageLinkage;
1927 // Language linkage is a C++ concept, but saying that everything else in C has
1928 // C language linkage fits the implementation nicely.
1929 ASTContext &Context = D.getASTContext();
1930 if (!Context.getLangOpts().CPlusPlus)
1931 return CLanguageLinkage;
1933 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1934 // language linkage of the names of class members and the function type of
1935 // class member functions.
1936 const DeclContext *DC = D.getDeclContext();
1938 return CXXLanguageLinkage;
1940 // If the first decl is in an extern "C" context, any other redeclaration
1941 // will have C language linkage. If the first one is not in an extern "C"
1942 // context, we would have reported an error for any other decl being in one.
1943 if (isFirstInExternCContext(&D))
1944 return CLanguageLinkage;
1945 return CXXLanguageLinkage;
1948 template<typename T>
1949 static bool isDeclExternC(const T &D) {
1950 // Since the context is ignored for class members, they can only have C++
1951 // language linkage or no language linkage.
1952 const DeclContext *DC = D.getDeclContext();
1953 if (DC->isRecord()) {
1954 assert(D.getASTContext().getLangOpts().CPlusPlus);
1958 return D.getLanguageLinkage() == CLanguageLinkage;
1961 LanguageLinkage VarDecl::getLanguageLinkage() const {
1962 return getDeclLanguageLinkage(*this);
1965 bool VarDecl::isExternC() const {
1966 return isDeclExternC(*this);
1969 bool VarDecl::isInExternCContext() const {
1970 return getLexicalDeclContext()->isExternCContext();
1973 bool VarDecl::isInExternCXXContext() const {
1974 return getLexicalDeclContext()->isExternCXXContext();
1977 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1979 VarDecl::DefinitionKind
1980 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
1981 if (isThisDeclarationADemotedDefinition())
1982 return DeclarationOnly;
1984 // C++ [basic.def]p2:
1985 // A declaration is a definition unless [...] it contains the 'extern'
1986 // specifier or a linkage-specification and neither an initializer [...],
1987 // it declares a non-inline static data member in a class declaration [...],
1988 // it declares a static data member outside a class definition and the variable
1989 // was defined within the class with the constexpr specifier [...],
1990 // C++1y [temp.expl.spec]p15:
1991 // An explicit specialization of a static data member or an explicit
1992 // specialization of a static data member template is a definition if the
1993 // declaration includes an initializer; otherwise, it is a declaration.
1995 // FIXME: How do you declare (but not define) a partial specialization of
1996 // a static data member template outside the containing class?
1997 if (isStaticDataMember()) {
1998 if (isOutOfLine() &&
1999 !(getCanonicalDecl()->isInline() &&
2000 getCanonicalDecl()->isConstexpr()) &&
2002 // If the first declaration is out-of-line, this may be an
2003 // instantiation of an out-of-line partial specialization of a variable
2004 // template for which we have not yet instantiated the initializer.
2005 (getFirstDecl()->isOutOfLine()
2006 ? getTemplateSpecializationKind() == TSK_Undeclared
2007 : getTemplateSpecializationKind() !=
2008 TSK_ExplicitSpecialization) ||
2009 isa<VarTemplatePartialSpecializationDecl>(this)))
2011 else if (!isOutOfLine() && isInline())
2014 return DeclarationOnly;
2017 // A definition of an identifier is a declaration for that identifier that
2018 // [...] causes storage to be reserved for that object.
2019 // Note: that applies for all non-file-scope objects.
2021 // If the declaration of an identifier for an object has file scope and an
2022 // initializer, the declaration is an external definition for the identifier
2026 if (hasDefiningAttr())
2029 if (const auto *SAA = getAttr<SelectAnyAttr>())
2030 if (!SAA->isInherited())
2033 // A variable template specialization (other than a static data member
2034 // template or an explicit specialization) is a declaration until we
2035 // instantiate its initializer.
2036 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2037 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2038 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2039 !VTSD->IsCompleteDefinition)
2040 return DeclarationOnly;
2043 if (hasExternalStorage())
2044 return DeclarationOnly;
2047 // A declaration directly contained in a linkage-specification is treated
2048 // as if it contains the extern specifier for the purpose of determining
2049 // the linkage of the declared name and whether it is a definition.
2050 if (isSingleLineLanguageLinkage(*this))
2051 return DeclarationOnly;
2054 // A declaration of an object that has file scope without an initializer,
2055 // and without a storage class specifier or the scs 'static', constitutes
2056 // a tentative definition.
2057 // No such thing in C++.
2058 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2059 return TentativeDefinition;
2061 // What's left is (in C, block-scope) declarations without initializers or
2062 // external storage. These are definitions.
2066 VarDecl *VarDecl::getActingDefinition() {
2067 DefinitionKind Kind = isThisDeclarationADefinition();
2068 if (Kind != TentativeDefinition)
2071 VarDecl *LastTentative = nullptr;
2072 VarDecl *First = getFirstDecl();
2073 for (auto I : First->redecls()) {
2074 Kind = I->isThisDeclarationADefinition();
2075 if (Kind == Definition)
2077 else if (Kind == TentativeDefinition)
2080 return LastTentative;
2083 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2084 VarDecl *First = getFirstDecl();
2085 for (auto I : First->redecls()) {
2086 if (I->isThisDeclarationADefinition(C) == Definition)
2092 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2093 DefinitionKind Kind = DeclarationOnly;
2095 const VarDecl *First = getFirstDecl();
2096 for (auto I : First->redecls()) {
2097 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2098 if (Kind == Definition)
2105 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2106 for (auto I : redecls()) {
2107 if (auto Expr = I->getInit()) {
2115 bool VarDecl::hasInit() const {
2116 if (auto *P = dyn_cast<ParmVarDecl>(this))
2117 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2120 return !Init.isNull();
2123 Expr *VarDecl::getInit() {
2127 if (auto *S = Init.dyn_cast<Stmt *>())
2128 return cast<Expr>(S);
2130 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2133 Stmt **VarDecl::getInitAddress() {
2134 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2137 return Init.getAddrOfPtr1();
2140 bool VarDecl::isOutOfLine() const {
2141 if (Decl::isOutOfLine())
2144 if (!isStaticDataMember())
2147 // If this static data member was instantiated from a static data member of
2148 // a class template, check whether that static data member was defined
2150 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2151 return VD->isOutOfLine();
2156 void VarDecl::setInit(Expr *I) {
2157 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2158 Eval->~EvaluatedStmt();
2159 getASTContext().Deallocate(Eval);
2165 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
2166 const LangOptions &Lang = C.getLangOpts();
2168 if (!Lang.CPlusPlus)
2171 // In C++11, any variable of reference type can be used in a constant
2172 // expression if it is initialized by a constant expression.
2173 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2176 // Only const objects can be used in constant expressions in C++. C++98 does
2177 // not require the variable to be non-volatile, but we consider this to be a
2179 if (!getType().isConstQualified() || getType().isVolatileQualified())
2182 // In C++, const, non-volatile variables of integral or enumeration types
2183 // can be used in constant expressions.
2184 if (getType()->isIntegralOrEnumerationType())
2187 // Additionally, in C++11, non-volatile constexpr variables can be used in
2188 // constant expressions.
2189 return Lang.CPlusPlus11 && isConstexpr();
2192 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2193 /// form, which contains extra information on the evaluated value of the
2195 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2196 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2198 // Note: EvaluatedStmt contains an APValue, which usually holds
2199 // resources not allocated from the ASTContext. We need to do some
2200 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2201 // where we can detect whether there's anything to clean up or not.
2202 Eval = new (getASTContext()) EvaluatedStmt;
2203 Eval->Value = Init.get<Stmt *>();
2209 APValue *VarDecl::evaluateValue() const {
2210 SmallVector<PartialDiagnosticAt, 8> Notes;
2211 return evaluateValue(Notes);
2214 APValue *VarDecl::evaluateValue(
2215 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2216 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2218 // We only produce notes indicating why an initializer is non-constant the
2219 // first time it is evaluated. FIXME: The notes won't always be emitted the
2220 // first time we try evaluation, so might not be produced at all.
2221 if (Eval->WasEvaluated)
2222 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2224 const auto *Init = cast<Expr>(Eval->Value);
2225 assert(!Init->isValueDependent());
2227 if (Eval->IsEvaluating) {
2228 // FIXME: Produce a diagnostic for self-initialization.
2229 Eval->CheckedICE = true;
2230 Eval->IsICE = false;
2234 Eval->IsEvaluating = true;
2236 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2239 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2240 // or that it's empty (so that there's nothing to clean up) if evaluation
2243 Eval->Evaluated = APValue();
2244 else if (Eval->Evaluated.needsCleanup())
2245 getASTContext().addDestruction(&Eval->Evaluated);
2247 Eval->IsEvaluating = false;
2248 Eval->WasEvaluated = true;
2250 // In C++11, we have determined whether the initializer was a constant
2251 // expression as a side-effect.
2252 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2253 Eval->CheckedICE = true;
2254 Eval->IsICE = Result && Notes.empty();
2257 return Result ? &Eval->Evaluated : nullptr;
2260 APValue *VarDecl::getEvaluatedValue() const {
2261 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2262 if (Eval->WasEvaluated)
2263 return &Eval->Evaluated;
2268 bool VarDecl::isInitKnownICE() const {
2269 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2270 return Eval->CheckedICE;
2275 bool VarDecl::isInitICE() const {
2276 assert(isInitKnownICE() &&
2277 "Check whether we already know that the initializer is an ICE");
2278 return Init.get<EvaluatedStmt *>()->IsICE;
2281 bool VarDecl::checkInitIsICE() const {
2282 // Initializers of weak variables are never ICEs.
2286 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2287 if (Eval->CheckedICE)
2288 // We have already checked whether this subexpression is an
2289 // integral constant expression.
2292 const auto *Init = cast<Expr>(Eval->Value);
2293 assert(!Init->isValueDependent());
2295 // In C++11, evaluate the initializer to check whether it's a constant
2297 if (getASTContext().getLangOpts().CPlusPlus11) {
2298 SmallVector<PartialDiagnosticAt, 8> Notes;
2299 evaluateValue(Notes);
2303 // It's an ICE whether or not the definition we found is
2304 // out-of-line. See DR 721 and the discussion in Clang PR
2305 // 6206 for details.
2307 if (Eval->CheckingICE)
2309 Eval->CheckingICE = true;
2311 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2312 Eval->CheckingICE = false;
2313 Eval->CheckedICE = true;
2317 template<typename DeclT>
2318 static DeclT *getDefinitionOrSelf(DeclT *D) {
2320 if (auto *Def = D->getDefinition())
2325 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2326 // If it's a variable template specialization, find the template or partial
2327 // specialization from which it was instantiated.
2328 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2329 auto From = VDTemplSpec->getInstantiatedFrom();
2330 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2331 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2332 if (NewVTD->isMemberSpecialization())
2336 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2339 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2340 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2341 if (NewVTPSD->isMemberSpecialization())
2345 return getDefinitionOrSelf<VarDecl>(VTPSD);
2349 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2350 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2351 VarDecl *VD = getInstantiatedFromStaticDataMember();
2352 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2354 return getDefinitionOrSelf(VD);
2358 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
2359 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2360 if (VarTemplate->isMemberSpecialization())
2362 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2365 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2370 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2371 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2372 return cast<VarDecl>(MSI->getInstantiatedFrom());
2377 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2378 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2379 return Spec->getSpecializationKind();
2381 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2382 return MSI->getTemplateSpecializationKind();
2384 return TSK_Undeclared;
2387 SourceLocation VarDecl::getPointOfInstantiation() const {
2388 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2389 return Spec->getPointOfInstantiation();
2391 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2392 return MSI->getPointOfInstantiation();
2394 return SourceLocation();
2397 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2398 return getASTContext().getTemplateOrSpecializationInfo(this)
2399 .dyn_cast<VarTemplateDecl *>();
2402 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2403 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2406 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2407 if (isStaticDataMember())
2409 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2410 return getASTContext().getTemplateOrSpecializationInfo(this)
2411 .dyn_cast<MemberSpecializationInfo *>();
2415 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2416 SourceLocation PointOfInstantiation) {
2417 assert((isa<VarTemplateSpecializationDecl>(this) ||
2418 getMemberSpecializationInfo()) &&
2419 "not a variable or static data member template specialization");
2421 if (VarTemplateSpecializationDecl *Spec =
2422 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2423 Spec->setSpecializationKind(TSK);
2424 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2425 Spec->getPointOfInstantiation().isInvalid()) {
2426 Spec->setPointOfInstantiation(PointOfInstantiation);
2427 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2428 L->InstantiationRequested(this);
2432 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2433 MSI->setTemplateSpecializationKind(TSK);
2434 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2435 MSI->getPointOfInstantiation().isInvalid()) {
2436 MSI->setPointOfInstantiation(PointOfInstantiation);
2437 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2438 L->InstantiationRequested(this);
2444 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2445 TemplateSpecializationKind TSK) {
2446 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2447 "Previous template or instantiation?");
2448 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2451 //===----------------------------------------------------------------------===//
2452 // ParmVarDecl Implementation
2453 //===----------------------------------------------------------------------===//
2455 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2456 SourceLocation StartLoc,
2457 SourceLocation IdLoc, IdentifierInfo *Id,
2458 QualType T, TypeSourceInfo *TInfo,
2459 StorageClass S, Expr *DefArg) {
2460 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2464 QualType ParmVarDecl::getOriginalType() const {
2465 TypeSourceInfo *TSI = getTypeSourceInfo();
2466 QualType T = TSI ? TSI->getType() : getType();
2467 if (const auto *DT = dyn_cast<DecayedType>(T))
2468 return DT->getOriginalType();
2472 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2474 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2475 nullptr, QualType(), nullptr, SC_None, nullptr);
2478 SourceRange ParmVarDecl::getSourceRange() const {
2479 if (!hasInheritedDefaultArg()) {
2480 SourceRange ArgRange = getDefaultArgRange();
2481 if (ArgRange.isValid())
2482 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2485 // DeclaratorDecl considers the range of postfix types as overlapping with the
2486 // declaration name, but this is not the case with parameters in ObjC methods.
2487 if (isa<ObjCMethodDecl>(getDeclContext()))
2488 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2490 return DeclaratorDecl::getSourceRange();
2493 Expr *ParmVarDecl::getDefaultArg() {
2494 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2495 assert(!hasUninstantiatedDefaultArg() &&
2496 "Default argument is not yet instantiated!");
2498 Expr *Arg = getInit();
2499 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2500 return E->getSubExpr();
2505 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2506 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2510 SourceRange ParmVarDecl::getDefaultArgRange() const {
2511 switch (ParmVarDeclBits.DefaultArgKind) {
2514 // Nothing we can do here.
2515 return SourceRange();
2517 case DAK_Uninstantiated:
2518 return getUninstantiatedDefaultArg()->getSourceRange();
2521 if (const Expr *E = getInit())
2522 return E->getSourceRange();
2524 // Missing an actual expression, may be invalid.
2525 return SourceRange();
2527 llvm_unreachable("Invalid default argument kind.");
2530 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2531 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2535 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2536 assert(hasUninstantiatedDefaultArg() &&
2537 "Wrong kind of initialization expression!");
2538 return cast_or_null<Expr>(Init.get<Stmt *>());
2541 bool ParmVarDecl::hasDefaultArg() const {
2542 // FIXME: We should just return false for DAK_None here once callers are
2543 // prepared for the case that we encountered an invalid default argument and
2544 // were unable to even build an invalid expression.
2545 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2549 bool ParmVarDecl::isParameterPack() const {
2550 return isa<PackExpansionType>(getType());
2553 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2554 getASTContext().setParameterIndex(this, parameterIndex);
2555 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2558 unsigned ParmVarDecl::getParameterIndexLarge() const {
2559 return getASTContext().getParameterIndex(this);
2562 //===----------------------------------------------------------------------===//
2563 // FunctionDecl Implementation
2564 //===----------------------------------------------------------------------===//
2566 void FunctionDecl::getNameForDiagnostic(
2567 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2568 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2569 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2571 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2574 bool FunctionDecl::isVariadic() const {
2575 if (const auto *FT = getType()->getAs<FunctionProtoType>())
2576 return FT->isVariadic();
2580 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2581 for (auto I : redecls()) {
2582 if (I->doesThisDeclarationHaveABody()) {
2591 bool FunctionDecl::hasTrivialBody() const
2593 Stmt *S = getBody();
2595 // Since we don't have a body for this function, we don't know if it's
2600 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2605 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2606 for (auto I : redecls()) {
2607 if (I->isThisDeclarationADefinition()) {
2616 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2617 if (!hasBody(Definition))
2620 if (Definition->Body)
2621 return Definition->Body.get(getASTContext().getExternalSource());
2626 void FunctionDecl::setBody(Stmt *B) {
2629 EndRangeLoc = B->getLocEnd();
2632 void FunctionDecl::setPure(bool P) {
2635 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2636 Parent->markedVirtualFunctionPure();
2639 template<std::size_t Len>
2640 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2641 IdentifierInfo *II = ND->getIdentifier();
2642 return II && II->isStr(Str);
2645 bool FunctionDecl::isMain() const {
2646 const TranslationUnitDecl *tunit =
2647 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2649 !tunit->getASTContext().getLangOpts().Freestanding &&
2650 isNamed(this, "main");
2653 bool FunctionDecl::isMSVCRTEntryPoint() const {
2654 const TranslationUnitDecl *TUnit =
2655 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2659 // Even though we aren't really targeting MSVCRT if we are freestanding,
2660 // semantic analysis for these functions remains the same.
2662 // MSVCRT entry points only exist on MSVCRT targets.
2663 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2666 // Nameless functions like constructors cannot be entry points.
2667 if (!getIdentifier())
2670 return llvm::StringSwitch<bool>(getName())
2671 .Cases("main", // an ANSI console app
2672 "wmain", // a Unicode console App
2673 "WinMain", // an ANSI GUI app
2674 "wWinMain", // a Unicode GUI app
2680 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2681 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2682 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2683 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2684 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2685 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2687 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2690 const auto *proto = getType()->castAs<FunctionProtoType>();
2691 if (proto->getNumParams() != 2 || proto->isVariadic())
2694 ASTContext &Context =
2695 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2698 // The result type and first argument type are constant across all
2699 // these operators. The second argument must be exactly void*.
2700 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2703 bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
2704 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2706 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2707 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2708 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2709 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2712 if (isa<CXXRecordDecl>(getDeclContext()))
2715 // This can only fail for an invalid 'operator new' declaration.
2716 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2719 const auto *FPT = getType()->castAs<FunctionProtoType>();
2720 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
2723 // If this is a single-parameter function, it must be a replaceable global
2724 // allocation or deallocation function.
2725 if (FPT->getNumParams() == 1)
2728 unsigned Params = 1;
2729 QualType Ty = FPT->getParamType(Params);
2730 ASTContext &Ctx = getASTContext();
2732 auto Consume = [&] {
2734 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2737 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2738 bool IsSizedDelete = false;
2739 if (Ctx.getLangOpts().SizedDeallocation &&
2740 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2741 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2742 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2743 IsSizedDelete = true;
2747 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2749 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2755 // Finally, if this is not a sized delete, the final parameter can
2756 // be a 'const std::nothrow_t&'.
2757 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2758 Ty = Ty->getPointeeType();
2759 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2761 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2762 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2766 return Params == FPT->getNumParams();
2769 bool FunctionDecl::isDestroyingOperatorDelete() const {
2771 // Within a class C, a single object deallocation function with signature
2772 // (T, std::destroying_delete_t, <more params>)
2773 // is a destroying operator delete.
2774 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2778 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2779 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2780 RD->getIdentifier()->isStr("destroying_delete_t");
2783 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2784 return getDeclLanguageLinkage(*this);
2787 bool FunctionDecl::isExternC() const {
2788 return isDeclExternC(*this);
2791 bool FunctionDecl::isInExternCContext() const {
2792 return getLexicalDeclContext()->isExternCContext();
2795 bool FunctionDecl::isInExternCXXContext() const {
2796 return getLexicalDeclContext()->isExternCXXContext();
2799 bool FunctionDecl::isGlobal() const {
2800 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
2801 return Method->isStatic();
2803 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2806 for (const DeclContext *DC = getDeclContext();
2808 DC = DC->getParent()) {
2809 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
2810 if (!Namespace->getDeclName())
2819 bool FunctionDecl::isNoReturn() const {
2820 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2821 hasAttr<C11NoReturnAttr>())
2824 if (auto *FnTy = getType()->getAs<FunctionType>())
2825 return FnTy->getNoReturnAttr();
2831 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2832 redeclarable_base::setPreviousDecl(PrevDecl);
2834 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2835 FunctionTemplateDecl *PrevFunTmpl
2836 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2837 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2838 FunTmpl->setPreviousDecl(PrevFunTmpl);
2841 if (PrevDecl && PrevDecl->IsInline)
2845 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2847 /// \brief Returns a value indicating whether this function
2848 /// corresponds to a builtin function.
2850 /// The function corresponds to a built-in function if it is
2851 /// declared at translation scope or within an extern "C" block and
2852 /// its name matches with the name of a builtin. The returned value
2853 /// will be 0 for functions that do not correspond to a builtin, a
2854 /// value of type \c Builtin::ID if in the target-independent range
2855 /// \c [1,Builtin::First), or a target-specific builtin value.
2856 unsigned FunctionDecl::getBuiltinID() const {
2857 if (!getIdentifier())
2860 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2864 ASTContext &Context = getASTContext();
2865 if (Context.getLangOpts().CPlusPlus) {
2866 const auto *LinkageDecl =
2867 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
2868 // In C++, the first declaration of a builtin is always inside an implicit
2870 // FIXME: A recognised library function may not be directly in an extern "C"
2871 // declaration, for instance "extern "C" { namespace std { decl } }".
2873 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2874 Context.getTargetInfo().getCXXABI().isMicrosoft())
2875 return Builtin::BI__GetExceptionInfo;
2878 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2882 // If the function is marked "overloadable", it has a different mangled name
2883 // and is not the C library function.
2884 if (hasAttr<OverloadableAttr>())
2887 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2890 // This function has the name of a known C library
2891 // function. Determine whether it actually refers to the C library
2892 // function or whether it just has the same name.
2894 // If this is a static function, it's not a builtin.
2895 if (getStorageClass() == SC_Static)
2898 // OpenCL v1.2 s6.9.f - The library functions defined in
2899 // the C99 standard headers are not available.
2900 if (Context.getLangOpts().OpenCL &&
2901 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2907 /// getNumParams - Return the number of parameters this function must have
2908 /// based on its FunctionType. This is the length of the ParamInfo array
2909 /// after it has been created.
2910 unsigned FunctionDecl::getNumParams() const {
2911 const auto *FPT = getType()->getAs<FunctionProtoType>();
2912 return FPT ? FPT->getNumParams() : 0;
2915 void FunctionDecl::setParams(ASTContext &C,
2916 ArrayRef<ParmVarDecl *> NewParamInfo) {
2917 assert(!ParamInfo && "Already has param info!");
2918 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2920 // Zero params -> null pointer.
2921 if (!NewParamInfo.empty()) {
2922 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2923 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2927 /// getMinRequiredArguments - Returns the minimum number of arguments
2928 /// needed to call this function. This may be fewer than the number of
2929 /// function parameters, if some of the parameters have default
2930 /// arguments (in C++) or are parameter packs (C++11).
2931 unsigned FunctionDecl::getMinRequiredArguments() const {
2932 if (!getASTContext().getLangOpts().CPlusPlus)
2933 return getNumParams();
2935 unsigned NumRequiredArgs = 0;
2936 for (auto *Param : parameters())
2937 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2939 return NumRequiredArgs;
2942 /// \brief The combination of the extern and inline keywords under MSVC forces
2943 /// the function to be required.
2945 /// Note: This function assumes that we will only get called when isInlined()
2946 /// would return true for this FunctionDecl.
2947 bool FunctionDecl::isMSExternInline() const {
2948 assert(isInlined() && "expected to get called on an inlined function!");
2950 const ASTContext &Context = getASTContext();
2951 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2952 !hasAttr<DLLExportAttr>())
2955 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2956 FD = FD->getPreviousDecl())
2957 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2963 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2964 if (Redecl->getStorageClass() != SC_Extern)
2967 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2968 FD = FD->getPreviousDecl())
2969 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2975 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2976 // Only consider file-scope declarations in this test.
2977 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2980 // Only consider explicit declarations; the presence of a builtin for a
2981 // libcall shouldn't affect whether a definition is externally visible.
2982 if (Redecl->isImplicit())
2985 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2986 return true; // Not an inline definition
2991 /// \brief For a function declaration in C or C++, determine whether this
2992 /// declaration causes the definition to be externally visible.
2994 /// For instance, this determines if adding the current declaration to the set
2995 /// of redeclarations of the given functions causes
2996 /// isInlineDefinitionExternallyVisible to change from false to true.
2997 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2998 assert(!doesThisDeclarationHaveABody() &&
2999 "Must have a declaration without a body.");
3001 ASTContext &Context = getASTContext();
3003 if (Context.getLangOpts().MSVCCompat) {
3004 const FunctionDecl *Definition;
3005 if (hasBody(Definition) && Definition->isInlined() &&
3006 redeclForcesDefMSVC(this))
3010 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3011 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3012 // an externally visible definition.
3014 // FIXME: What happens if gnu_inline gets added on after the first
3016 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3019 const FunctionDecl *Prev = this;
3020 bool FoundBody = false;
3021 while ((Prev = Prev->getPreviousDecl())) {
3022 FoundBody |= Prev->Body.isValid();
3025 // If it's not the case that both 'inline' and 'extern' are
3026 // specified on the definition, then it is always externally visible.
3027 if (!Prev->isInlineSpecified() ||
3028 Prev->getStorageClass() != SC_Extern)
3030 } else if (Prev->isInlineSpecified() &&
3031 Prev->getStorageClass() != SC_Extern) {
3038 if (Context.getLangOpts().CPlusPlus)
3042 // [...] If all of the file scope declarations for a function in a
3043 // translation unit include the inline function specifier without extern,
3044 // then the definition in that translation unit is an inline definition.
3045 if (isInlineSpecified() && getStorageClass() != SC_Extern)
3047 const FunctionDecl *Prev = this;
3048 bool FoundBody = false;
3049 while ((Prev = Prev->getPreviousDecl())) {
3050 FoundBody |= Prev->Body.isValid();
3051 if (RedeclForcesDefC99(Prev))
3057 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3058 const TypeSourceInfo *TSI = getTypeSourceInfo();
3060 return SourceRange();
3061 FunctionTypeLoc FTL =
3062 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3064 return SourceRange();
3066 // Skip self-referential return types.
3067 const SourceManager &SM = getASTContext().getSourceManager();
3068 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3069 SourceLocation Boundary = getNameInfo().getLocStart();
3070 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3071 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3072 return SourceRange();
3077 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3078 const TypeSourceInfo *TSI = getTypeSourceInfo();
3080 return SourceRange();
3081 FunctionTypeLoc FTL =
3082 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3084 return SourceRange();
3086 return FTL.getExceptionSpecRange();
3089 const Attr *FunctionDecl::getUnusedResultAttr() const {
3090 QualType RetType = getReturnType();
3091 if (RetType->isRecordType()) {
3092 if (const auto *Ret =
3093 dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) {
3094 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3097 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3098 if (const EnumDecl *ED = ET->getDecl()) {
3099 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3103 return getAttr<WarnUnusedResultAttr>();
3106 /// \brief For an inline function definition in C, or for a gnu_inline function
3107 /// in C++, determine whether the definition will be externally visible.
3109 /// Inline function definitions are always available for inlining optimizations.
3110 /// However, depending on the language dialect, declaration specifiers, and
3111 /// attributes, the definition of an inline function may or may not be
3112 /// "externally" visible to other translation units in the program.
3114 /// In C99, inline definitions are not externally visible by default. However,
3115 /// if even one of the global-scope declarations is marked "extern inline", the
3116 /// inline definition becomes externally visible (C99 6.7.4p6).
3118 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3119 /// definition, we use the GNU semantics for inline, which are nearly the
3120 /// opposite of C99 semantics. In particular, "inline" by itself will create
3121 /// an externally visible symbol, but "extern inline" will not create an
3122 /// externally visible symbol.
3123 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3124 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3125 "Must be a function definition");
3126 assert(isInlined() && "Function must be inline");
3127 ASTContext &Context = getASTContext();
3129 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3130 // Note: If you change the logic here, please change
3131 // doesDeclarationForceExternallyVisibleDefinition as well.
3133 // If it's not the case that both 'inline' and 'extern' are
3134 // specified on the definition, then this inline definition is
3135 // externally visible.
3136 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3139 // If any declaration is 'inline' but not 'extern', then this definition
3140 // is externally visible.
3141 for (auto Redecl : redecls()) {
3142 if (Redecl->isInlineSpecified() &&
3143 Redecl->getStorageClass() != SC_Extern)
3150 // The rest of this function is C-only.
3151 assert(!Context.getLangOpts().CPlusPlus &&
3152 "should not use C inline rules in C++");
3155 // [...] If all of the file scope declarations for a function in a
3156 // translation unit include the inline function specifier without extern,
3157 // then the definition in that translation unit is an inline definition.
3158 for (auto Redecl : redecls()) {
3159 if (RedeclForcesDefC99(Redecl))
3164 // An inline definition does not provide an external definition for the
3165 // function, and does not forbid an external definition in another
3166 // translation unit.
3170 /// getOverloadedOperator - Which C++ overloaded operator this
3171 /// function represents, if any.
3172 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3173 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3174 return getDeclName().getCXXOverloadedOperator();
3179 /// getLiteralIdentifier - The literal suffix identifier this function
3180 /// represents, if any.
3181 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3182 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3183 return getDeclName().getCXXLiteralIdentifier();
3188 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3189 if (TemplateOrSpecialization.isNull())
3190 return TK_NonTemplate;
3191 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3192 return TK_FunctionTemplate;
3193 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3194 return TK_MemberSpecialization;
3195 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3196 return TK_FunctionTemplateSpecialization;
3197 if (TemplateOrSpecialization.is
3198 <DependentFunctionTemplateSpecializationInfo*>())
3199 return TK_DependentFunctionTemplateSpecialization;
3201 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3204 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3205 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3206 return cast<FunctionDecl>(Info->getInstantiatedFrom());
3211 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3212 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3216 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3218 TemplateSpecializationKind TSK) {
3219 assert(TemplateOrSpecialization.isNull() &&
3220 "Member function is already a specialization");
3221 MemberSpecializationInfo *Info
3222 = new (C) MemberSpecializationInfo(FD, TSK);
3223 TemplateOrSpecialization = Info;
3226 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3227 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3230 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3231 TemplateOrSpecialization = Template;
3234 bool FunctionDecl::isImplicitlyInstantiable() const {
3235 // If the function is invalid, it can't be implicitly instantiated.
3236 if (isInvalidDecl())
3239 switch (getTemplateSpecializationKind()) {
3240 case TSK_Undeclared:
3241 case TSK_ExplicitInstantiationDefinition:
3244 case TSK_ImplicitInstantiation:
3247 // It is possible to instantiate TSK_ExplicitSpecialization kind
3248 // if the FunctionDecl has a class scope specialization pattern.
3249 case TSK_ExplicitSpecialization:
3250 return getClassScopeSpecializationPattern() != nullptr;
3252 case TSK_ExplicitInstantiationDeclaration:
3257 // Find the actual template from which we will instantiate.
3258 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3259 bool HasPattern = false;
3261 HasPattern = PatternDecl->hasBody(PatternDecl);
3263 // C++0x [temp.explicit]p9:
3264 // Except for inline functions, other explicit instantiation declarations
3265 // have the effect of suppressing the implicit instantiation of the entity
3266 // to which they refer.
3267 if (!HasPattern || !PatternDecl)
3270 return PatternDecl->isInlined();
3273 bool FunctionDecl::isTemplateInstantiation() const {
3274 switch (getTemplateSpecializationKind()) {
3275 case TSK_Undeclared:
3276 case TSK_ExplicitSpecialization:
3278 case TSK_ImplicitInstantiation:
3279 case TSK_ExplicitInstantiationDeclaration:
3280 case TSK_ExplicitInstantiationDefinition:
3283 llvm_unreachable("All TSK values handled.");
3286 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3287 // Handle class scope explicit specialization special case.
3288 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3289 if (auto *Spec = getClassScopeSpecializationPattern())
3290 return getDefinitionOrSelf(Spec);
3294 // If this is a generic lambda call operator specialization, its
3295 // instantiation pattern is always its primary template's pattern
3296 // even if its primary template was instantiated from another
3297 // member template (which happens with nested generic lambdas).
3298 // Since a lambda's call operator's body is transformed eagerly,
3299 // we don't have to go hunting for a prototype definition template
3300 // (i.e. instantiated-from-member-template) to use as an instantiation
3303 if (isGenericLambdaCallOperatorSpecialization(
3304 dyn_cast<CXXMethodDecl>(this))) {
3305 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3306 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3309 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3310 while (Primary->getInstantiatedFromMemberTemplate()) {
3311 // If we have hit a point where the user provided a specialization of
3312 // this template, we're done looking.
3313 if (Primary->isMemberSpecialization())
3315 Primary = Primary->getInstantiatedFromMemberTemplate();
3318 return getDefinitionOrSelf(Primary->getTemplatedDecl());
3321 if (auto *MFD = getInstantiatedFromMemberFunction())
3322 return getDefinitionOrSelf(MFD);
3327 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3328 if (FunctionTemplateSpecializationInfo *Info
3329 = TemplateOrSpecialization
3330 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3331 return Info->Template.getPointer();
3336 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3337 return getASTContext().getClassScopeSpecializationPattern(this);
3340 FunctionTemplateSpecializationInfo *
3341 FunctionDecl::getTemplateSpecializationInfo() const {
3342 return TemplateOrSpecialization
3343 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3346 const TemplateArgumentList *
3347 FunctionDecl::getTemplateSpecializationArgs() const {
3348 if (FunctionTemplateSpecializationInfo *Info
3349 = TemplateOrSpecialization
3350 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3351 return Info->TemplateArguments;
3356 const ASTTemplateArgumentListInfo *
3357 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3358 if (FunctionTemplateSpecializationInfo *Info
3359 = TemplateOrSpecialization
3360 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3361 return Info->TemplateArgumentsAsWritten;
3367 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3368 FunctionTemplateDecl *Template,
3369 const TemplateArgumentList *TemplateArgs,
3371 TemplateSpecializationKind TSK,
3372 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3373 SourceLocation PointOfInstantiation) {
3374 assert(TSK != TSK_Undeclared &&
3375 "Must specify the type of function template specialization");
3376 FunctionTemplateSpecializationInfo *Info
3377 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3379 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3381 TemplateArgsAsWritten,
3382 PointOfInstantiation);
3383 TemplateOrSpecialization = Info;
3384 Template->addSpecialization(Info, InsertPos);
3388 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3389 const UnresolvedSetImpl &Templates,
3390 const TemplateArgumentListInfo &TemplateArgs) {
3391 assert(TemplateOrSpecialization.isNull());
3392 DependentFunctionTemplateSpecializationInfo *Info =
3393 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3395 TemplateOrSpecialization = Info;
3398 DependentFunctionTemplateSpecializationInfo *
3399 FunctionDecl::getDependentSpecializationInfo() const {
3400 return TemplateOrSpecialization
3401 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3404 DependentFunctionTemplateSpecializationInfo *
3405 DependentFunctionTemplateSpecializationInfo::Create(
3406 ASTContext &Context, const UnresolvedSetImpl &Ts,
3407 const TemplateArgumentListInfo &TArgs) {
3408 void *Buffer = Context.Allocate(
3409 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3410 TArgs.size(), Ts.size()));
3411 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3414 DependentFunctionTemplateSpecializationInfo::
3415 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3416 const TemplateArgumentListInfo &TArgs)
3417 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3418 NumTemplates = Ts.size();
3419 NumArgs = TArgs.size();
3421 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3422 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3423 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3425 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3426 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3427 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3430 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3431 // For a function template specialization, query the specialization
3432 // information object.
3433 FunctionTemplateSpecializationInfo *FTSInfo
3434 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3436 return FTSInfo->getTemplateSpecializationKind();
3438 MemberSpecializationInfo *MSInfo
3439 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3441 return MSInfo->getTemplateSpecializationKind();
3443 return TSK_Undeclared;
3447 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3448 SourceLocation PointOfInstantiation) {
3449 if (FunctionTemplateSpecializationInfo *FTSInfo
3450 = TemplateOrSpecialization.dyn_cast<
3451 FunctionTemplateSpecializationInfo*>()) {
3452 FTSInfo->setTemplateSpecializationKind(TSK);
3453 if (TSK != TSK_ExplicitSpecialization &&
3454 PointOfInstantiation.isValid() &&
3455 FTSInfo->getPointOfInstantiation().isInvalid()) {
3456 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3457 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3458 L->InstantiationRequested(this);
3460 } else if (MemberSpecializationInfo *MSInfo
3461 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3462 MSInfo->setTemplateSpecializationKind(TSK);
3463 if (TSK != TSK_ExplicitSpecialization &&
3464 PointOfInstantiation.isValid() &&
3465 MSInfo->getPointOfInstantiation().isInvalid()) {
3466 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3467 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3468 L->InstantiationRequested(this);
3471 llvm_unreachable("Function cannot have a template specialization kind");
3474 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3475 if (FunctionTemplateSpecializationInfo *FTSInfo
3476 = TemplateOrSpecialization.dyn_cast<
3477 FunctionTemplateSpecializationInfo*>())
3478 return FTSInfo->getPointOfInstantiation();
3479 else if (MemberSpecializationInfo *MSInfo
3480 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3481 return MSInfo->getPointOfInstantiation();
3483 return SourceLocation();
3486 bool FunctionDecl::isOutOfLine() const {
3487 if (Decl::isOutOfLine())
3490 // If this function was instantiated from a member function of a
3491 // class template, check whether that member function was defined out-of-line.
3492 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3493 const FunctionDecl *Definition;
3494 if (FD->hasBody(Definition))
3495 return Definition->isOutOfLine();
3498 // If this function was instantiated from a function template,
3499 // check whether that function template was defined out-of-line.
3500 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3501 const FunctionDecl *Definition;
3502 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3503 return Definition->isOutOfLine();
3509 SourceRange FunctionDecl::getSourceRange() const {
3510 return SourceRange(getOuterLocStart(), EndRangeLoc);
3513 unsigned FunctionDecl::getMemoryFunctionKind() const {
3514 IdentifierInfo *FnInfo = getIdentifier();
3519 // Builtin handling.
3520 switch (getBuiltinID()) {
3521 case Builtin::BI__builtin_memset:
3522 case Builtin::BI__builtin___memset_chk:
3523 case Builtin::BImemset:
3524 return Builtin::BImemset;
3526 case Builtin::BI__builtin_memcpy:
3527 case Builtin::BI__builtin___memcpy_chk:
3528 case Builtin::BImemcpy:
3529 return Builtin::BImemcpy;
3531 case Builtin::BI__builtin_memmove:
3532 case Builtin::BI__builtin___memmove_chk:
3533 case Builtin::BImemmove:
3534 return Builtin::BImemmove;
3536 case Builtin::BIstrlcpy:
3537 case Builtin::BI__builtin___strlcpy_chk:
3538 return Builtin::BIstrlcpy;
3540 case Builtin::BIstrlcat:
3541 case Builtin::BI__builtin___strlcat_chk:
3542 return Builtin::BIstrlcat;
3544 case Builtin::BI__builtin_memcmp:
3545 case Builtin::BImemcmp:
3546 return Builtin::BImemcmp;
3548 case Builtin::BI__builtin_strncpy:
3549 case Builtin::BI__builtin___strncpy_chk:
3550 case Builtin::BIstrncpy:
3551 return Builtin::BIstrncpy;
3553 case Builtin::BI__builtin_strncmp:
3554 case Builtin::BIstrncmp:
3555 return Builtin::BIstrncmp;
3557 case Builtin::BI__builtin_strncasecmp:
3558 case Builtin::BIstrncasecmp:
3559 return Builtin::BIstrncasecmp;
3561 case Builtin::BI__builtin_strncat:
3562 case Builtin::BI__builtin___strncat_chk:
3563 case Builtin::BIstrncat:
3564 return Builtin::BIstrncat;
3566 case Builtin::BI__builtin_strndup:
3567 case Builtin::BIstrndup:
3568 return Builtin::BIstrndup;
3570 case Builtin::BI__builtin_strlen:
3571 case Builtin::BIstrlen:
3572 return Builtin::BIstrlen;
3574 case Builtin::BI__builtin_bzero:
3575 case Builtin::BIbzero:
3576 return Builtin::BIbzero;
3580 if (FnInfo->isStr("memset"))
3581 return Builtin::BImemset;
3582 else if (FnInfo->isStr("memcpy"))
3583 return Builtin::BImemcpy;
3584 else if (FnInfo->isStr("memmove"))
3585 return Builtin::BImemmove;
3586 else if (FnInfo->isStr("memcmp"))
3587 return Builtin::BImemcmp;
3588 else if (FnInfo->isStr("strncpy"))
3589 return Builtin::BIstrncpy;
3590 else if (FnInfo->isStr("strncmp"))
3591 return Builtin::BIstrncmp;
3592 else if (FnInfo->isStr("strncasecmp"))
3593 return Builtin::BIstrncasecmp;
3594 else if (FnInfo->isStr("strncat"))
3595 return Builtin::BIstrncat;
3596 else if (FnInfo->isStr("strndup"))
3597 return Builtin::BIstrndup;
3598 else if (FnInfo->isStr("strlen"))
3599 return Builtin::BIstrlen;
3600 else if (FnInfo->isStr("bzero"))
3601 return Builtin::BIbzero;
3608 unsigned FunctionDecl::getODRHash() {
3612 if (FunctionDecl *Definition = getDefinition()) {
3613 if (Definition != this) {
3615 ODRHash = Definition->getODRHash();
3621 Hash.AddFunctionDecl(this);
3623 ODRHash = Hash.CalculateHash();
3627 //===----------------------------------------------------------------------===//
3628 // FieldDecl Implementation
3629 //===----------------------------------------------------------------------===//
3631 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3632 SourceLocation StartLoc, SourceLocation IdLoc,
3633 IdentifierInfo *Id, QualType T,
3634 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3635 InClassInitStyle InitStyle) {
3636 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3637 BW, Mutable, InitStyle);
3640 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3641 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3642 SourceLocation(), nullptr, QualType(), nullptr,
3643 nullptr, false, ICIS_NoInit);
3646 bool FieldDecl::isAnonymousStructOrUnion() const {
3647 if (!isImplicit() || getDeclName())
3650 if (const auto *Record = getType()->getAs<RecordType>())
3651 return Record->getDecl()->isAnonymousStructOrUnion();
3656 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3657 assert(isBitField() && "not a bitfield");
3658 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
3661 unsigned FieldDecl::getFieldIndex() const {
3662 const FieldDecl *Canonical = getCanonicalDecl();
3663 if (Canonical != this)
3664 return Canonical->getFieldIndex();
3666 if (CachedFieldIndex) return CachedFieldIndex - 1;
3669 const RecordDecl *RD = getParent()->getDefinition();
3670 assert(RD && "requested index for field of struct with no definition");
3672 for (auto *Field : RD->fields()) {
3673 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3677 assert(CachedFieldIndex && "failed to find field in parent");
3678 return CachedFieldIndex - 1;
3681 SourceRange FieldDecl::getSourceRange() const {
3682 const Expr *FinalExpr = getInClassInitializer();
3684 FinalExpr = getBitWidth();
3686 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3687 return DeclaratorDecl::getSourceRange();
3690 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3691 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3692 "capturing type in non-lambda or captured record.");
3693 assert(InitStorage.getInt() == ISK_NoInit &&
3694 InitStorage.getPointer() == nullptr &&
3695 "bit width, initializer or captured type already set");
3696 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3697 ISK_CapturedVLAType);
3700 //===----------------------------------------------------------------------===//
3701 // TagDecl Implementation
3702 //===----------------------------------------------------------------------===//
3704 SourceLocation TagDecl::getOuterLocStart() const {
3705 return getTemplateOrInnerLocStart(this);
3708 SourceRange TagDecl::getSourceRange() const {
3709 SourceLocation RBraceLoc = BraceRange.getEnd();
3710 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3711 return SourceRange(getOuterLocStart(), E);
3714 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3716 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3717 TypedefNameDeclOrQualifier = TDD;
3718 if (const Type *T = getTypeForDecl()) {
3720 assert(T->isLinkageValid());
3722 assert(isLinkageValid());
3725 void TagDecl::startDefinition() {
3726 IsBeingDefined = true;
3728 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
3729 struct CXXRecordDecl::DefinitionData *Data =
3730 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3731 for (auto I : redecls())
3732 cast<CXXRecordDecl>(I)->DefinitionData = Data;
3736 void TagDecl::completeDefinition() {
3737 assert((!isa<CXXRecordDecl>(this) ||
3738 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3739 "definition completed but not started");
3741 IsCompleteDefinition = true;
3742 IsBeingDefined = false;
3744 if (ASTMutationListener *L = getASTMutationListener())
3745 L->CompletedTagDefinition(this);
3748 TagDecl *TagDecl::getDefinition() const {
3749 if (isCompleteDefinition())
3750 return const_cast<TagDecl *>(this);
3752 // If it's possible for us to have an out-of-date definition, check now.
3753 if (MayHaveOutOfDateDef) {
3754 if (IdentifierInfo *II = getIdentifier()) {
3755 if (II->isOutOfDate()) {
3756 updateOutOfDate(*II);
3761 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
3762 return CXXRD->getDefinition();
3764 for (auto R : redecls())
3765 if (R->isCompleteDefinition())
3771 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3773 // Make sure the extended qualifier info is allocated.
3775 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3776 // Set qualifier info.
3777 getExtInfo()->QualifierLoc = QualifierLoc;
3779 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3781 if (getExtInfo()->NumTemplParamLists == 0) {
3782 getASTContext().Deallocate(getExtInfo());
3783 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
3786 getExtInfo()->QualifierLoc = QualifierLoc;
3791 void TagDecl::setTemplateParameterListsInfo(
3792 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3793 assert(!TPLists.empty());
3794 // Make sure the extended decl info is allocated.
3796 // Allocate external info struct.
3797 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3798 // Set the template parameter lists info.
3799 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
3802 //===----------------------------------------------------------------------===//
3803 // EnumDecl Implementation
3804 //===----------------------------------------------------------------------===//
3806 void EnumDecl::anchor() {}
3808 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3809 SourceLocation StartLoc, SourceLocation IdLoc,
3811 EnumDecl *PrevDecl, bool IsScoped,
3812 bool IsScopedUsingClassTag, bool IsFixed) {
3813 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3814 IsScoped, IsScopedUsingClassTag, IsFixed);
3815 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3816 C.getTypeDeclType(Enum, PrevDecl);
3820 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3822 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3823 nullptr, nullptr, false, false, false);
3824 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3828 SourceRange EnumDecl::getIntegerTypeRange() const {
3829 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3830 return TI->getTypeLoc().getSourceRange();
3831 return SourceRange();
3834 void EnumDecl::completeDefinition(QualType NewType,
3835 QualType NewPromotionType,
3836 unsigned NumPositiveBits,
3837 unsigned NumNegativeBits) {
3838 assert(!isCompleteDefinition() && "Cannot redefine enums!");
3840 IntegerType = NewType.getTypePtr();
3841 PromotionType = NewPromotionType;
3842 setNumPositiveBits(NumPositiveBits);
3843 setNumNegativeBits(NumNegativeBits);
3844 TagDecl::completeDefinition();
3847 bool EnumDecl::isClosed() const {
3848 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3849 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3853 bool EnumDecl::isClosedFlag() const {
3854 return isClosed() && hasAttr<FlagEnumAttr>();
3857 bool EnumDecl::isClosedNonFlag() const {
3858 return isClosed() && !hasAttr<FlagEnumAttr>();
3861 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3862 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3863 return MSI->getTemplateSpecializationKind();
3865 return TSK_Undeclared;
3868 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3869 SourceLocation PointOfInstantiation) {
3870 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3871 assert(MSI && "Not an instantiated member enumeration?");
3872 MSI->setTemplateSpecializationKind(TSK);
3873 if (TSK != TSK_ExplicitSpecialization &&
3874 PointOfInstantiation.isValid() &&
3875 MSI->getPointOfInstantiation().isInvalid())
3876 MSI->setPointOfInstantiation(PointOfInstantiation);
3879 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3880 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3881 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3882 EnumDecl *ED = getInstantiatedFromMemberEnum();
3883 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3885 return getDefinitionOrSelf(ED);
3889 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3890 "couldn't find pattern for enum instantiation");
3894 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3895 if (SpecializationInfo)
3896 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3901 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3902 TemplateSpecializationKind TSK) {
3903 assert(!SpecializationInfo && "Member enum is already a specialization");
3904 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3907 //===----------------------------------------------------------------------===//
3908 // RecordDecl Implementation
3909 //===----------------------------------------------------------------------===//
3911 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3912 DeclContext *DC, SourceLocation StartLoc,
3913 SourceLocation IdLoc, IdentifierInfo *Id,
3914 RecordDecl *PrevDecl)
3915 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3916 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false),
3917 HasObjectMember(false), HasVolatileMember(false),
3918 LoadedFieldsFromExternalStorage(false) {
3919 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3922 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3923 SourceLocation StartLoc, SourceLocation IdLoc,
3924 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3925 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3926 StartLoc, IdLoc, Id, PrevDecl);
3927 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3929 C.getTypeDeclType(R, PrevDecl);
3933 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3935 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3936 SourceLocation(), nullptr, nullptr);
3937 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3941 bool RecordDecl::isInjectedClassName() const {
3942 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3943 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3946 bool RecordDecl::isLambda() const {
3947 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3948 return RD->isLambda();
3952 bool RecordDecl::isCapturedRecord() const {
3953 return hasAttr<CapturedRecordAttr>();
3956 void RecordDecl::setCapturedRecord() {
3957 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3960 RecordDecl::field_iterator RecordDecl::field_begin() const {
3961 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3962 LoadFieldsFromExternalStorage();
3964 return field_iterator(decl_iterator(FirstDecl));
3967 /// completeDefinition - Notes that the definition of this type is now
3969 void RecordDecl::completeDefinition() {
3970 assert(!isCompleteDefinition() && "Cannot redefine record!");
3971 TagDecl::completeDefinition();
3974 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3975 /// This which can be turned on with an attribute, pragma, or the
3976 /// -mms-bitfields command-line option.
3977 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3978 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
3981 void RecordDecl::LoadFieldsFromExternalStorage() const {
3982 ExternalASTSource *Source = getASTContext().getExternalSource();
3983 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3985 // Notify that we have a RecordDecl doing some initialization.
3986 ExternalASTSource::Deserializing TheFields(Source);
3988 SmallVector<Decl*, 64> Decls;
3989 LoadedFieldsFromExternalStorage = true;
3990 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3991 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3995 // Check that all decls we got were FieldDecls.
3996 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3997 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4003 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4004 /*FieldsAlreadyLoaded=*/false);
4007 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4008 ASTContext &Context = getASTContext();
4009 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4010 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4011 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4013 const auto &Blacklist = Context.getSanitizerBlacklist();
4014 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4015 // We may be able to relax some of these requirements.
4016 int ReasonToReject = -1;
4017 if (!CXXRD || CXXRD->isExternCContext())
4018 ReasonToReject = 0; // is not C++.
4019 else if (CXXRD->hasAttr<PackedAttr>())
4020 ReasonToReject = 1; // is packed.
4021 else if (CXXRD->isUnion())
4022 ReasonToReject = 2; // is a union.
4023 else if (CXXRD->isTriviallyCopyable())
4024 ReasonToReject = 3; // is trivially copyable.
4025 else if (CXXRD->hasTrivialDestructor())
4026 ReasonToReject = 4; // has trivial destructor.
4027 else if (CXXRD->isStandardLayout())
4028 ReasonToReject = 5; // is standard layout.
4029 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4031 ReasonToReject = 6; // is in a blacklisted file.
4032 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4033 getQualifiedNameAsString(),
4035 ReasonToReject = 7; // is blacklisted.
4038 if (ReasonToReject >= 0)
4039 Context.getDiagnostics().Report(
4041 diag::remark_sanitize_address_insert_extra_padding_rejected)
4042 << getQualifiedNameAsString() << ReasonToReject;
4044 Context.getDiagnostics().Report(
4046 diag::remark_sanitize_address_insert_extra_padding_accepted)
4047 << getQualifiedNameAsString();
4049 return ReasonToReject < 0;
4052 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4053 for (const auto *I : fields()) {
4054 if (I->getIdentifier())
4057 if (const auto *RT = I->getType()->getAs<RecordType>())
4058 if (const FieldDecl *NamedDataMember =
4059 RT->getDecl()->findFirstNamedDataMember())
4060 return NamedDataMember;
4063 // We didn't find a named data member.
4067 //===----------------------------------------------------------------------===//
4068 // BlockDecl Implementation
4069 //===----------------------------------------------------------------------===//
4071 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4072 assert(!ParamInfo && "Already has param info!");
4074 // Zero params -> null pointer.
4075 if (!NewParamInfo.empty()) {
4076 NumParams = NewParamInfo.size();
4077 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4078 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4082 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4083 bool CapturesCXXThis) {
4084 this->CapturesCXXThis = CapturesCXXThis;
4085 this->NumCaptures = Captures.size();
4087 if (Captures.empty()) {
4088 this->Captures = nullptr;
4092 this->Captures = Captures.copy(Context).data();
4095 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4096 for (const auto &I : captures())
4097 // Only auto vars can be captured, so no redeclaration worries.
4098 if (I.getVariable() == variable)
4104 SourceRange BlockDecl::getSourceRange() const {
4105 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4108 //===----------------------------------------------------------------------===//
4109 // Other Decl Allocation/Deallocation Method Implementations
4110 //===----------------------------------------------------------------------===//
4112 void TranslationUnitDecl::anchor() {}
4114 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4115 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4118 void PragmaCommentDecl::anchor() {}
4120 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4121 TranslationUnitDecl *DC,
4122 SourceLocation CommentLoc,
4123 PragmaMSCommentKind CommentKind,
4125 PragmaCommentDecl *PCD =
4126 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4127 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4128 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4129 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4133 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4136 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4137 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4140 void PragmaDetectMismatchDecl::anchor() {}
4142 PragmaDetectMismatchDecl *
4143 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4144 SourceLocation Loc, StringRef Name,
4146 size_t ValueStart = Name.size() + 1;
4147 PragmaDetectMismatchDecl *PDMD =
4148 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4149 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4150 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4151 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4152 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4154 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4158 PragmaDetectMismatchDecl *
4159 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4160 unsigned NameValueSize) {
4161 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4162 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4165 void ExternCContextDecl::anchor() {}
4167 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4168 TranslationUnitDecl *DC) {
4169 return new (C, DC) ExternCContextDecl(DC);
4172 void LabelDecl::anchor() {}
4174 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4175 SourceLocation IdentL, IdentifierInfo *II) {
4176 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4179 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4180 SourceLocation IdentL, IdentifierInfo *II,
4181 SourceLocation GnuLabelL) {
4182 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4183 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4186 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4187 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4191 void LabelDecl::setMSAsmLabel(StringRef Name) {
4192 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4193 memcpy(Buffer, Name.data(), Name.size());
4194 Buffer[Name.size()] = '\0';
4198 void ValueDecl::anchor() {}
4200 bool ValueDecl::isWeak() const {
4201 for (const auto *I : attrs())
4202 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
4205 return isWeakImported();
4208 void ImplicitParamDecl::anchor() {}
4210 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4211 SourceLocation IdLoc,
4212 IdentifierInfo *Id, QualType Type,
4213 ImplicitParamKind ParamKind) {
4214 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4217 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4218 ImplicitParamKind ParamKind) {
4219 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4222 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4224 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4227 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4228 SourceLocation StartLoc,
4229 const DeclarationNameInfo &NameInfo,
4230 QualType T, TypeSourceInfo *TInfo,
4232 bool isInlineSpecified,
4233 bool hasWrittenPrototype,
4234 bool isConstexprSpecified) {
4236 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4237 SC, isInlineSpecified, isConstexprSpecified);
4238 New->HasWrittenPrototype = hasWrittenPrototype;
4242 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4243 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
4244 DeclarationNameInfo(), QualType(), nullptr,
4245 SC_None, false, false);
4248 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4249 return new (C, DC) BlockDecl(DC, L);
4252 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4253 return new (C, ID) BlockDecl(nullptr, SourceLocation());
4256 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4257 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4258 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4260 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4261 unsigned NumParams) {
4262 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4263 CapturedDecl(DC, NumParams);
4266 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4267 unsigned NumParams) {
4268 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4269 CapturedDecl(nullptr, NumParams);
4272 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4273 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4275 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4276 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4278 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4280 IdentifierInfo *Id, QualType T,
4281 Expr *E, const llvm::APSInt &V) {
4282 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4286 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4287 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4288 QualType(), nullptr, llvm::APSInt());
4291 void IndirectFieldDecl::anchor() {}
4293 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4294 SourceLocation L, DeclarationName N,
4296 MutableArrayRef<NamedDecl *> CH)
4297 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4298 ChainingSize(CH.size()) {
4299 // In C++, indirect field declarations conflict with tag declarations in the
4300 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4301 if (C.getLangOpts().CPlusPlus)
4302 IdentifierNamespace |= IDNS_Tag;
4306 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4307 IdentifierInfo *Id, QualType T,
4308 llvm::MutableArrayRef<NamedDecl *> CH) {
4309 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4312 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4314 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4315 DeclarationName(), QualType(), None);
4318 SourceRange EnumConstantDecl::getSourceRange() const {
4319 SourceLocation End = getLocation();
4321 End = Init->getLocEnd();
4322 return SourceRange(getLocation(), End);
4325 void TypeDecl::anchor() {}
4327 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4328 SourceLocation StartLoc, SourceLocation IdLoc,
4329 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4330 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4333 void TypedefNameDecl::anchor() {}
4335 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4336 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4337 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4338 auto *ThisTypedef = this;
4339 if (AnyRedecl && OwningTypedef) {
4340 OwningTypedef = OwningTypedef->getCanonicalDecl();
4341 ThisTypedef = ThisTypedef->getCanonicalDecl();
4343 if (OwningTypedef == ThisTypedef)
4344 return TT->getDecl();
4350 bool TypedefNameDecl::isTransparentTagSlow() const {
4351 auto determineIsTransparent = [&]() {
4352 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4353 if (auto *TD = TT->getDecl()) {
4354 if (TD->getName() != getName())
4356 SourceLocation TTLoc = getLocation();
4357 SourceLocation TDLoc = TD->getLocation();
4358 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4360 SourceManager &SM = getASTContext().getSourceManager();
4361 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4367 bool isTransparent = determineIsTransparent();
4368 CacheIsTransparentTag = 1;
4370 CacheIsTransparentTag |= 0x2;
4371 return isTransparent;
4374 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4375 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4379 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4380 SourceLocation StartLoc,
4381 SourceLocation IdLoc, IdentifierInfo *Id,
4382 TypeSourceInfo *TInfo) {
4383 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4386 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4387 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4388 SourceLocation(), nullptr, nullptr);
4391 SourceRange TypedefDecl::getSourceRange() const {
4392 SourceLocation RangeEnd = getLocation();
4393 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4394 if (typeIsPostfix(TInfo->getType()))
4395 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4397 return SourceRange(getLocStart(), RangeEnd);
4400 SourceRange TypeAliasDecl::getSourceRange() const {
4401 SourceLocation RangeEnd = getLocStart();
4402 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4403 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4404 return SourceRange(getLocStart(), RangeEnd);
4407 void FileScopeAsmDecl::anchor() {}
4409 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4411 SourceLocation AsmLoc,
4412 SourceLocation RParenLoc) {
4413 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4416 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4418 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4422 void EmptyDecl::anchor() {}
4424 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4425 return new (C, DC) EmptyDecl(DC, L);
4428 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4429 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4432 //===----------------------------------------------------------------------===//
4433 // ImportDecl Implementation
4434 //===----------------------------------------------------------------------===//
4436 /// \brief Retrieve the number of module identifiers needed to name the given
4438 static unsigned getNumModuleIdentifiers(Module *Mod) {
4439 unsigned Result = 1;
4440 while (Mod->Parent) {
4447 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4449 ArrayRef<SourceLocation> IdentifierLocs)
4450 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
4451 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4452 auto *StoredLocs = getTrailingObjects<SourceLocation>();
4453 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4457 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4458 Module *Imported, SourceLocation EndLoc)
4459 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
4460 *getTrailingObjects<SourceLocation>() = EndLoc;
4463 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4464 SourceLocation StartLoc, Module *Imported,
4465 ArrayRef<SourceLocation> IdentifierLocs) {
4467 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4468 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4471 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4472 SourceLocation StartLoc,
4474 SourceLocation EndLoc) {
4475 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4476 ImportDecl(DC, StartLoc, Imported, EndLoc);
4477 Import->setImplicit();
4481 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4482 unsigned NumLocations) {
4483 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4484 ImportDecl(EmptyShell());
4487 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4488 if (!ImportedAndComplete.getInt())
4491 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4492 return llvm::makeArrayRef(StoredLocs,
4493 getNumModuleIdentifiers(getImportedModule()));
4496 SourceRange ImportDecl::getSourceRange() const {
4497 if (!ImportedAndComplete.getInt())
4498 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4500 return SourceRange(getLocation(), getIdentifierLocs().back());
4503 //===----------------------------------------------------------------------===//
4504 // ExportDecl Implementation
4505 //===----------------------------------------------------------------------===//
4507 void ExportDecl::anchor() {}
4509 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4510 SourceLocation ExportLoc) {
4511 return new (C, DC) ExportDecl(DC, ExportLoc);
4514 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4515 return new (C, ID) ExportDecl(nullptr, SourceLocation());